#!/usr/bin/perl
# Simple rotoscope drawing tool
# Display image sequence, draw freehand on transparent overlay, save overlay as PNG in drawings/
# Left/Right or buttons: prev/next image (loads existing drawing if present)
# S or Save button: save/update overlay PNG
# N or Clear button: clear overlay
# D or Delete button: delete existing drawing file and clear overlay
# Load new: reload a different directory
# Mouse: draw freehand (adds to existing lines)

use strict;
use warnings;
use Tk;
use Tk::PNG;
use Tk::JPEG;
use Image::Imlib2;
use File::Temp qw(tempfile);
use File::Path qw(make_path);
use Cwd qw(getcwd abs_path);
use File::Spec;

# --- Defaults ---
my $img_dir    = getcwd();
my $canvas_w   = 800;
my $canvas_h   = 600;
my $line_width = 3;
my $line_color = '#FF0000';

my $font = ['Helvetica', 16];

# Globals for drawing session
my (@images, $index, $mw, $bg_photo, $overlay, $canvas, $status);
my ($drawing, $prev_x, $prev_y) = (0, undef, undef);
my $eraser_mode = 0;
my ($bf, $eraser_btn);
my $blank_erase;
my $setup;

# ---------- Setup window (stays open) ----------
my @dir_stack = (getcwd());
my $selected_dir = $dir_stack[-1];
my @contents;

$setup = MainWindow->new;
$setup->title('Rotoscope Draw - Setup');
$setup->geometry('950x900');   # taller

$setup->Label(-text => 'Browse to image directory', -font => ['Helvetica', 18])->pack(-pady => 8);

my $message_box = $setup->Entry(-font => $font, -width => 70)->pack(-fill => 'x', -padx => 10, -pady => 4);
$message_box->insert(0, "Selected directory: $selected_dir");

my $listbox = $setup->Scrolled('Listbox',
    -font => $font,
    -scrollbars => 'se',
    -width => 50,      # columns (characters)
    -height => 15,     # rows
    -selectmode => 'browse',
)->pack(-fill => 'both', -expand => 1, -padx => 10, -pady => 5);

sub refresh_listbox {
    my $dir = $dir_stack[-1];
    $listbox->delete(0, 'end');
    opendir(my $dh, $dir) or return;
    @contents = readdir($dh);
    closedir $dh;
    @contents = sort { lc($a) cmp lc($b) } @contents;
    foreach my $item (@contents) {
        next if $item =~ /^\./;
        my $path = File::Spec->catfile($dir, $item);
        if (-d $path) {
            $listbox->insert('end', $item);
            $listbox->itemconfigure('end', -foreground => 'blue');
        } elsif ($item =~ /\.(?:png|jpe?g)$/i) {
            $listbox->insert('end', $item);
        }
    }
}

sub select_item {
    my $selection = $listbox->get('active');
    return unless defined $selection;
    my $path = File::Spec->catfile($dir_stack[-1], $selection);
    if (-d $path) {
        push @dir_stack, $path;
        $selected_dir = $path;
        $message_box->delete(0, 'end');
        $message_box->insert(0, "Selected directory: $selected_dir");
        refresh_listbox();
    }
}

sub GO_UP {
    pop @dir_stack if @dir_stack > 1;
    $selected_dir = $dir_stack[-1];
    $message_box->delete(0, 'end');
    $message_box->insert(0, "Selected directory: $selected_dir");
    refresh_listbox();
}

refresh_listbox();
$listbox->bind('<Double-Button-1>' => \&select_item);
$listbox->bind('<Return>' => \&select_item);

my $btn_frame = $setup->Frame->pack(-pady => 6);
$btn_frame->Button(-text => 'Up', -font => $font, -command => \&GO_UP)->pack(-side => 'left', -padx => 5);

# Settings (live)
my $sf = $setup->Frame->pack(-fill => 'x', -padx => 10, -pady => 8);
$sf->Label(-text => 'Canvas width:', -font => $font)->grid(-row => 0, -column => 0, -sticky => 'w');
$sf->Entry(-textvariable => \$canvas_w, -font => $font, -width => 8)->grid(-row => 0, -column => 1, -padx => 4);
$sf->Label(-text => 'Canvas height:', -font => $font)->grid(-row => 0, -column => 2, -sticky => 'w', -padx => 10);
$sf->Entry(-textvariable => \$canvas_h, -font => $font, -width => 8)->grid(-row => 0, -column => 3);

$sf->Label(-text => 'Line width:', -font => $font)->grid(-row => 1, -column => 0, -sticky => 'w');
$sf->Entry(-textvariable => \$line_width, -font => $font, -width => 8)->grid(-row => 1, -column => 1, -padx => 4);
$sf->Label(-text => 'Line colour:', -font => $font)->grid(-row => 1, -column => 2, -sticky => 'w', -padx => 10);
$sf->Entry(-textvariable => \$line_color, -font => $font, -width => 12)->grid(-row => 1, -column => 3);

$setup->Button(-text => 'Start / Load directory', -font => $font, -command => \&load_directory)->pack(-pady => 8);
$setup->Button(-text => 'Load new (clear & reload)', -font => $font, -command => \&load_directory)->pack(-pady => 4);

# ---------- Drawing window helpers ----------
sub drawing_file {
    my $base = $images[$index];
    $base =~ s/\.[^.]+$//;
    my $draw_dir = File::Spec->catdir($img_dir, 'drawings');
    return File::Spec->catfile($draw_dir, "${base}_lines.png");
}

sub load_overlay_if_exists {
    $overlay->blank;
    my $df = drawing_file();
    if (-f $df) {
        eval { $overlay->read($df, -format => 'png'); };
        print "Loaded existing drawing: $df\n" unless $@;
    }
}

sub load_and_scale {
    return unless @images && $mw;
    my $file = File::Spec->catfile($img_dir, $images[$index]);
    my $im = Image::Imlib2->load($file) or die "Cannot load $file: $!";
    my $scaled = $im->create_scaled_image($canvas_w, $canvas_h);

    my ($fh, $tmp) = tempfile(SUFFIX => '.png', UNLINK => 1);
    $scaled->save($tmp);
    close $fh;

    # Force clean background: delete old photo item and recreate Photo
    $canvas->delete('all');
    $bg_photo->delete if $bg_photo;   # free old
    $bg_photo = $mw->Photo(-file => $tmp);

    load_overlay_if_exists();   # blanks then loads drawing if any

    $canvas->createImage(0, 0, -image => $bg_photo, -anchor => 'nw', -tags => 'bg');
    $canvas->createImage(0, 0, -image => $overlay,  -anchor => 'nw', -tags => 'overlay');
    $canvas->configure(-width => $canvas_w, -height => $canvas_h);
    $canvas->update;
    update_status();
}

sub update_status {
    my $df = drawing_file();
    my $has = (-f $df) ? ' [has drawing]' : '';
    my $mode = $eraser_mode ? '  ERASER' : '';
    $status->configure(-text => sprintf('Image %d/%d: %s%s%s   Width:%d  Colour:%s',
        $index + 1, scalar(@images), $images[$index], $has, $mode, $line_width, $line_color));
    $mw->title("Rotoscope Draw - $images[$index]") if $mw;
}

sub save_overlay {
    return unless @images;
    my $draw_dir = File::Spec->catdir($img_dir, 'drawings');
    make_path($draw_dir) unless -d $draw_dir;
    my $out = drawing_file();
    $overlay->write($out, -format => 'png');
    print "Saved overlay: $out\n";
    update_status();
}

sub clear_overlay {
    $overlay->blank;
    $canvas->delete('overlay');
    $canvas->createImage(0, 0, -image => $overlay, -anchor => 'nw', -tags => 'overlay');
    print "Overlay cleared\n";
}

sub delete_drawing {
    my $df = drawing_file();
    if (-f $df) {
        unlink $df or warn "Cannot delete $df: $!";
        print "Deleted $df\n";
    }
    clear_overlay();
    update_status();
}

sub load_directory {
    $img_dir = abs_path($selected_dir) || $selected_dir;
    unless (-d $img_dir) {
        print "Directory not found: $img_dir\n";
        return;
    }
    opendir(my $dh, $img_dir) or do { print "Cannot open $img_dir: $!\n"; return; };
    @images = sort grep { /\.(?:jpe?g|png)$/i } readdir($dh);
    closedir $dh;
    unless (@images) {
        print "No images in $img_dir\n";
        return;
    }
    $index = 0;

    unless ($mw) {
        # Create drawing window the first time
        $mw = MainWindow->new;
        $mw->title('Rotoscope Draw');
        $mw->resizable(0, 0);
        $mw->geometry(sprintf('%dx%d', $canvas_w + 20, $canvas_h + 80));
        $bg_photo = $mw->Photo;
        $overlay  = $mw->Photo(-width => $canvas_w, -height => $canvas_h);
        $overlay->blank;

        $canvas = $mw->Canvas(
            -width      => $canvas_w,
            -height     => $canvas_h,
            -background => 'white',
        )->pack(-expand => 0, -fill => 'none');

        $status = $mw->Label(-text => '', -anchor => 'w', -font => $font)->pack(-fill => 'x');

        # Action buttons on drawing window
         $bf = $mw->Frame->pack(-fill => 'x', -pady => 4);
        $bf->Button(-text => 'Prev',  -font => $font, -command => \&prev_image)->pack(-side => 'left', -padx => 3);
        $bf->Button(-text => 'Next',  -font => $font, -command => \&next_image)->pack(-side => 'left', -padx => 3);
        $bf->Button(-text => 'Save',  -font => $font, -command => \&save_overlay)->pack(-side => 'left', -padx => 3);
        $bf->Button(-text => 'Clear', -font => $font, -command => \&clear_overlay)->pack(-side => 'left', -padx => 3);
        $bf->Button(-text => 'Delete drawing', -font => $font, -command => \&delete_drawing)->pack(-side => 'left', -padx => 3);
         $eraser_btn = $bf->Button(-text => 'Eraser', -font => $font, -command => \&toggle_eraser);
        $eraser_btn->pack(-side => 'left', -padx => 3);

        # Mouse bindings
        $canvas->CanvasBind('<Button-1>' => [sub {
            my ($c, $x, $y) = @_;
            $x = $c->canvasx($x);
            $y = $c->canvasy($y);
            $drawing = 1;
            ($prev_x, $prev_y) = ($x, $y);
            draw_segment($x, $y, $x, $y);
        }, Ev('x'), Ev('y')]);

        $canvas->CanvasBind('<B1-Motion>' => [sub {
            return unless $drawing;
            my ($c, $x, $y) = @_;
            $x = $c->canvasx($x);
            $y = $c->canvasy($y);
            draw_segment($prev_x, $prev_y, $x, $y);
            ($prev_x, $prev_y) = ($x, $y);
        }, Ev('x'), Ev('y')]);

        $canvas->CanvasBind('<ButtonRelease-1>' => sub { $drawing = 0; });

        # Key bindings
        $mw->bind('<Right>' => \&next_image);
        $mw->bind('<Left>'  => \&prev_image);
        $mw->bind('<KeyPress-s>' => \&save_overlay);
        $mw->bind('<KeyPress-n>' => \&clear_overlay);
        $mw->bind('<KeyPress-d>' => \&delete_drawing);
        $mw->bind('<KeyPress-e>' => \&toggle_eraser);
    } else {
        # Resize canvas/photos if size changed
        $canvas->configure(-width => $canvas_w, -height => $canvas_h);
        $overlay->blank;
        # Note: Photo size is fixed at creation; for simplicity we keep original size
        # or recreate if needed. For now assume size set before first Start.
    }

    load_and_scale();
}

sub next_image {
    return if $index >= $#images;
    $index++;
    load_and_scale();
}

sub prev_image {
    return if $index <= 0;
    $index--;
    load_and_scale();
}

sub toggle_eraser {
    $eraser_mode = !$eraser_mode;
    print $eraser_mode ? "Eraser ON\n" : "Eraser OFF\n";
    if ($eraser_btn) {
        $eraser_btn->configure(-background => $eraser_mode ? 'yellow' : $bf->cget('-background'));
    }
    update_status();
}

sub draw_segment {
    my ($x1, $y1, $x2, $y2) = @_;
    return unless defined $x1 && defined $y1 && defined $x2 && defined $y2;
    my $dx = $x2 - $x1;
    my $dy = $y2 - $y1;
    my $steps = int(sqrt($dx*$dx + $dy*$dy)) || 1;
    my $half = int($line_width / 2);
    my $erase_half = $eraser_mode ? ($half * 3 + 6) : $half;  # larger eraser
    for my $i (0 .. $steps) {
        my $x = int($x1 + $dx * $i / $steps);
        my $y = int($y1 + $dy * $i / $steps);
        next if $x < 0 || $y < 0 || $x >= $canvas_w || $y >= $canvas_h;
        my ($x1e, $y1e, $x2e, $y2e) = ($x - $erase_half, $y - $erase_half, $x + $erase_half + 1, $y + $erase_half + 1);
        # Clamp to canvas so the Photo never grows
        $x1e = 0 if $x1e < 0;
        $y1e = 0 if $y1e < 0;
        $x2e = $canvas_w if $x2e > $canvas_w;
        $y2e = $canvas_h if $y2e > $canvas_h;
        next if $x2e <= $x1e || $y2e <= $y1e;

        if ($eraser_mode) {
            # Use a small reusable blank (created once) and copy only the needed region
            unless ($blank_erase) {
                $blank_erase = $mw->Photo(-width => 64, -height => 64);
                $blank_erase->blank;
            }
            $overlay->copy($blank_erase,
                -from => (0, 0, $x2e-$x1e, $y2e-$y1e),
                -to   => ($x1e, $y1e),
                -compositingrule => 'set');
            # Force overlay back to canvas size in case it grew
            if ($overlay->width != $canvas_w || $overlay->height != $canvas_h) {
                my $fixed = $mw->Photo(-width => $canvas_w, -height => $canvas_h);
                $fixed->copy($overlay, -compositingrule => 'set');
                $overlay->blank;
                $overlay->copy($fixed, -compositingrule => 'set');
                $fixed->delete;
            }
        } else {
            $overlay->put($line_color, -to => ($x1e, $y1e, $x2e, $y2e));
        }
    }
}

MainLoop;
