1#!/usr/bin/perl -w
2#
3#  This is a REAL QUICK HACK to add captions to JPG files. We'll replace it
4#  with something more Rico Suave(tm) as time goes one.
5#
6#  Use --force to force the program to process all JPG files regardless of
7#  whether an existing comment exists or not.
8#
9#  Use --oneline to get one line captions, ending when you hit enter.
10#  (won't wait for . at last line to end it)
11#
12#  $Id: autocaption,v 1.7 2006/10/28 16:43:11 jjreynold Exp $
13#  $Name: v2_0 $
14#
15use Getopt::Long;
16use Term::ReadLine;
17use vars qw($opt_force);
18
19$size = '500x400';
20$geom = "${size}+5+5";
21
22my $term = new Term::ReadLine 'imageindex autocaption';
23my $OUT = $term->OUT || \*STDOUT;
24
25&GetOptions('force','oneline') or die ("Invalid flag\n");
26
27if (scalar (@ARGV)) {
28    @files = @ARGV;
29}
30else {
31    while ($name = <*.jpg *.JPG *.jpeg *.JPEG>) {
32	push (@files, $name);
33    }
34}
35
36foreach my $name (@files) {
37    printf $OUT ("Processing $name ...\n");
38    $qname = quotemeta ($name);
39    open (PIPE, "imageindex -caption $qname |") || die;
40    $existing_caption = '';
41    while (<PIPE>) {
42	if (/: "(.*)"\s*$/) {
43	    $existing_caption = $1;
44	}
45    }
46    close (PIPE);
47    if ($existing_caption) {
48	printf $OUT ("Existing caption: \"$existing_caption\"\n");
49	if (! defined ($opt_force)) {
50	    printf $OUT ("Skipping this file. Use -force to re-do captions.\n\n");
51	    next;
52	}
53    }
54    else {
55	printf $OUT ("No existing caption found.\n");
56    }
57    if (!defined($opt_oneline)) {
58	printf $OUT ("Bringing up resized image. Enter a caption with \".\" last line:\n");
59	printf $OUT ("(entering \".\" will re-use any previous caption)\n");
60    } else {
61	printf $OUT ("Bringing up resized image. Enter a caption:\n");
62	printf $OUT ("(blank will re-use any previous caption)\n");
63    }
64    if ($pid = fork) {
65	my $caption = "";
66	my $prompt = "$name: ";
67	while (defined ($_ = $term->readline($prompt)) ) {
68	    warn $@ if $@;
69	    if (defined($opt_oneline)) {
70		$caption .= $_;
71		last;
72	    } elsif ($_ =~ /^\.$/) {
73		last;
74	    } else {
75		$caption .= " $_";
76	    }
77	}
78	chomp($caption);
79	$term->addhistory($caption);
80	$caption = quotemeta ($caption);
81	if (($caption ne '') and ($caption ne '.')) {
82	    printf $OUT ("Executing: imageindex -caption $qname $caption\n");
83	    system ("imageindex -caption $qname $caption");
84	}
85
86	kill 15, $pid;
87
88    }
89    else {
90	exec 'display', '-geometry', $geom, '-resize', $size, $name;
91    }
92
93
94}
95