#!/usr/bin/perl

use strict;
use warnings;

use Gtk2 -init;
use Cairo;

my $area = Gtk2::DrawingArea->new();
my $cairo;

sub draw_vertex($$) {
	my ($x, $y) = @_;
	my $rad = 100;
	my $rim = 3;

	my $lg = Cairo::RadialGradient->create($x, $y, 0, $x, $y, $rad);
	$lg->add_color_stop_rgb(0, 0.7, 0, 0.7);
	$lg->add_color_stop_rgb(1, 0.3, 0, 0.3);

	$cairo->arc($x, $y, $rad, 0, 2*3.141592);
	$cairo->set_source($lg);
	$cairo->fill;

	$cairo->arc($x, $y, $rad, 0, 2*3.141592);
	$cairo->set_source_rgb(1, 1, 1);
	$cairo->set_line_width($rim);
	$cairo->stroke;

	$cairo->set_font_size(0.6*$rad);
	my $xt = $cairo->text_extents('Brum');
	$cairo->move_to($x - $xt->{'width'}/2 - $xt->{'x_bearing'},
			$y - $xt->{'height'}/2 - $xt->{'y_bearing'});
	$cairo->show_text("Brum");
}

my $xx=0;
my $pixmap;
my ($lastw, $lasth, $lastd) = (-1, -1, -1);
my ($pixw, $pixh) = (-1, -1);
sub draw($) {
	my ($force) = @_;
	my $win = $area->window;
	my $wgc = Gtk2::Gdk::GC->new($win);
	my $alloc = $area->allocation;
	my $w = $alloc->width;
	my $h = $alloc->height;
	my $d = $win->get_depth;
	# print "Area $w x $h x $d, xx=$xx\n";

	if (!defined($pixmap) || $lastw != $w || $lasth != $h || $lastd != $d) {
		($lastw, $lasth, $lastd) = ($w, $h, $d);
		if ($w/$h >= 4/3) {
			$pixh = $h;
			$pixw = int($h/3*4);
		} else {
			$pixw = $w;
			$pixh = int($w/4*3);
		}
		print "Resized to ${w}x${h}, pixmap size ${pixw}x${pixh}\n";

		if ($force) {
			$wgc->set_rgb_background(0);
			$wgc->set_rgb_foreground(0);
			$win->draw_rectangle($wgc, 1, 0, 0, $w, $h);
		}

		$pixmap = Gtk2::Gdk::Pixmap->new($win, $pixw, $pixh, $d);
		$cairo = Gtk2::Gdk::Cairo::Context->create($pixmap);
		$cairo->select_font_face('URW Palladio L', 'normal', 'normal');
		my $scale = $pixw/1024;
		$cairo->scale($scale, $scale);
	}

	$cairo->rectangle(0, 0, 1024, 768);
	$cairo->set_source_rgb(0, 0, 0);
	$cairo->fill;

	draw_vertex(4/3*$xx, $xx);

	$win->draw_drawable($wgc, $pixmap, 0, 0, 0, 0, $pixw, $pixh);
}

sub step() {
	draw(0);
	$xx++;
}

my $timer;
my $stopped = 0;
$area->signal_connect("expose-event" => sub {
	draw(1);
	if (!defined $timer) {
		$timer = Glib::Timeout->add(100, sub { $stopped || step(); return 1; });
	}
});
$area->set_flags('can-focus');
# $area->add_events('key-press-mask');
$area->signal_connect('key-press-event' => sub {
	my ($w, $evt) = @_;
	my $k = Gtk2::Gdk::keyval_name(0, $evt->keyval);
	print "Pressed key $k\n";
	if ($k eq "Escape") {
		Gtk2->main_quit;
	} elsif ($k eq "space") {
		$stopped = !$stopped;
	}
});

my $window = Gtk2::Window->new ('toplevel');
$window->signal_connect ("delete-event" => sub { Gtk2->main_quit });
$window->set_title("Brum");
$window->set_wmclass("anim", "Anim");
$window->set_default_size(640, 480);
$window->add ($area);
$window->show_all;
#$window->fullscreen;

Gtk2->main;
