aboutsummaryrefslogtreecommitdiff
path: root/wpdf
blob: a906c67de95e9bdb9a22990f22836c037b98c4d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/perl

# wpdf -- view, watch and remake pdf based on Makefile

use strict;
use warnings;

my $alive;        # number of children alive
my %deptarget;    # dependency => target
my $parent = $$;  # pid of parent

$SIG{USR1} = sub { kill 'HUP', 0 if not --$alive };
$SIG{HUP} = sub { exit 0 };

# collect dependencies for given pdf files
for my $target (@ARGV) {
	if ($target =~ /\.pdf$/) {
		(my $basename = $target) =~ s/\.pdf$//;
		open my $f, '<', 'Makefile'
			or die "could not open Makefile: $!\n";
		while (<$f>) {
			# explicit
			if (/^\Q$target\E:\s*(.*)/) {
				$deptarget{$_} = $target for split /\s/, $1;
				last;
			}
			# implicit
			if (/^\.([^ .]+)\.pdf\s*:\s*(.*)/) {
				$deptarget{"$basename.$1"} = $target;
				$deptarget{$_} = $target for split /\s/, $2;
				last;
			}
		}
		close $f;
		if (fork == 0) {
			system 'xpdf', '-remote', "wpdf-$target", $target;
			kill 'USR1', $parent;
			exit;
		}
		$alive++;
		next;
	} else {
		warn "skipping $_: not a pdf\n";
	}
}

# make pdf on demand
open my $p, '-|', 'watch', keys %deptarget
	or die "could not start watch: $!\n";
while (<$p>) {
	chomp;
	system('make', "$deptarget{$_}") == 0
		&& system('xpdf', '-remote', "wpdf-$deptarget{$_}", '-reload');
}
close $p;
exit($? != 0);