mason/.perl-lib/TrivGal.pm: Use GraphicsMagick rather than Imlib2.
[tgal] / mason / .perl-lib / TrivGal.pm
1 ### -*-cperl-*-
2 ###
3 ### Main output for Trivial Gallery.
4 ###
5 ### (c) 2021 Mark Wooding
6 ###
7
8 ###----- Licensing notice ---------------------------------------------------
9 ###
10 ### This file is part of Trivial Gallery.
11 ###
12 ### Trivial Gallery is free software: you can redistribute it and/or modify
13 ### it under the terms of the GNU Affero General Public License as
14 ### published by the Free Software Foundation; either version 3 of the
15 ### License, or (at your option) any later version.
16 ###
17 ### Trivial Gallery is distributed in the hope that it will be useful, but
18 ### WITHOUT ANY WARRANTY; without even the implied warranty of
19 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 ### Affero General Public License for more details.
21 ###
22 ### You should have received a copy of the GNU Affero General Public
23 ### License along with Trivial Gallery. If not, see
24 ### <https://www.gnu.org/licenses/>.
25
26 package TrivGal;
27
28 use autodie qw{:all};
29
30 use Errno;
31 use Exporter qw{import};
32 use File::stat;
33 use Graphics::Magick;
34 use Image::ExifTool qw{};
35 use Image::Size qw{};
36 use User::pwent;
37 use POSIX;
38
39 our @EXPORT;
40 sub export (@) { push @EXPORT, @_; }
41
42 ###--------------------------------------------------------------------------
43 ### Internal utilities.
44
45 sub read_or_set ($\$@) {
46 my ($me, $ref, @args) = @_;
47 if (@args == 0) { return $$ref; }
48 elsif (@args == 1) { $$ref = $args[0]; return $me; }
49 elsif (@args > 1) { die "too many arguments"; }
50 }
51
52 ###--------------------------------------------------------------------------
53 ### Random utilities.
54
55 export qw{join_paths};
56 sub join_paths (@) {
57 my @p = @_;
58 my $p = "";
59 ELT: for my $e (@p) {
60 $e =~ s#^/{2,}#/#;
61 $e =~ s#([^/])/+$#$1#;
62 if ($e eq "") { next ELT; }
63 elsif ($p eq "" || $e =~ m#^/#) { $p = $e; }
64 else { $p = "$p/$e"; }
65 }
66 return $p;
67 }
68
69 export qw{split_path};
70 sub split_path ($) {
71 my ($path) = @_;
72
73 my ($dir, $base, $ext) =
74 $path =~ m#^ (?: (.*) /)?
75 (?: ([^/]*) \.)?
76 ([^./]*) $#x;
77 if (defined $base) { $ext = ".$ext"; }
78 else { $base = $ext; $ext = ""; }
79 return ($dir, $base, $ext);
80 }
81
82 export qw{urlencode};
83 sub urlencode ($) {
84 my ($u) = @_;
85 $u =~ s#([^0-9a-zA-Z_./~-])#sprintf "%%%02x", ord $1#eg;
86 return $u;
87 }
88
89 export qw{urldecode};
90 sub urldecode ($) {
91 my ($u) = @_;
92 $u =~ s#\%([0-9a-fA-F]{2})#chr hex $1#eg;
93 return $u;
94 }
95
96 ###--------------------------------------------------------------------------
97 ### Image types.
98
99 our %TYPE;
100
101 package TrivGal::ImageType {
102 sub new ($$) {
103 my ($cls, $ext) = @_;
104 return $TYPE{$ext} = bless { ext => $ext }, $cls;
105 }
106 sub ext ($) {
107 my ($me, @args) = @_;
108 return $me->{ext};
109 }
110 sub mimetype ($@) {
111 my ($me, @args) = @_;
112 return TrivGal::read_or_set $me, $me->{mimetype}, @args;
113 }
114 sub imlibfmt ($@) {
115 my ($me, @args) = @_;
116 return TrivGal::read_or_set $me, $me->{imlibfmt}, @args;
117 }
118 }
119
120 TrivGal::ImageType->new(".jpg")->mimetype("image/jpeg")->imlibfmt("jpeg");
121 TrivGal::ImageType->new(".png")->mimetype("image/png")->imlibfmt("png");
122
123 ###--------------------------------------------------------------------------
124 ### Configuration.
125
126 export qw{$SCOPE $SUFFIX};
127 our $SCOPE //= $::SCOPE;
128 our $SUFFIX //= $::SUFFIX;
129
130 export qw{$IMGROOT $CACHE $TMP};
131 our $IMGROOT //= "$ENV{HOME}/publish/$SCOPE-html$SUFFIX/tgal-images";
132 our $CACHE //=
133 ($ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache") .
134 "/tgal/$SCOPE$SUFFIX";
135 our $TMP //= "$CACHE/tmp";
136
137 export qw{$ROOTURL $IMGURL $CACHEURL $STATICURL $SCRIPTURL};
138 my $user = getpwuid($>)->name;
139 our $ROOTURL //= "/~$user";
140 our $IMGURL //= "$ROOTURL/tgal-images";
141 our $CACHEURL //= "$ROOTURL/tgal-cache";
142 our $STATICURL //= "$ROOTURL/tgal-static";
143 our $SCRIPTURL;
144
145 export qw{$SRCURL};
146 our $SRCURL = "https://git.distorted.org.uk/~mdw/tgal/";
147
148 export qw{%SIZE};
149 our %SIZE = (smallthumb => 96,
150 medthumb => 144,
151 bigthumb => 216,
152 tiny => 320,
153 small => 480,
154 embed => 720,
155 medium => 1080,
156 big => 1600,
157 large => 2400,
158 huge => 3600,
159 vast => 5400,
160 immense => 8100);
161
162 export qw{init};
163 my $initp = 0;
164 sub init () {
165 my $m = HTML::Mason::Request->instance;
166 my $r = $m->cgi_request;
167
168 $m->interp->set_escape(u => sub { my ($r) = @_; $$r = urlencode $$r; });
169
170 return unless !$initp;
171
172 $SCRIPTURL //= $r->subprocess_env("SCRIPT_NAME");
173 $initp = 1;
174 }
175
176 ###--------------------------------------------------------------------------
177 ### Temporary files.
178
179 export qw{clean_temp_files};
180 sub clean_temp_files () {
181 my $d;
182
183 eval { opendir $d, $TMP; };
184 if ($@) {
185 if ($@->isa("autodie::exception") && $@->errno == ENOENT) { return; }
186 else { die $@; }
187 }
188 my $now = time;
189 FILE: while (my $name = readdir $d) {
190 next FILE unless $name =~ /^t(\d+)\-/;
191 my $pid = $1;
192 next FILE if kill 0, $pid;
193 my $f = "$TMP/$name";
194 my $st = stat $name;
195 next FILE if $now - $st->mtime() < 300;
196 unlink $f;
197 }
198 closedir $d;
199 }
200
201 ###--------------------------------------------------------------------------
202 ### Scaled images.
203
204 my %ORIENT =
205 (1 => [0, 0],
206 2 => [0, 1],
207 3 => [2, 0],
208 4 => [2, 1],
209 5 => [3, 1],
210 6 => [1, 0],
211 7 => [1, 1],
212 8 => [3, 0]);
213
214 package TrivGal::Image {
215 use File::Path qw{make_path};
216 use File::stat;
217
218 sub new ($$) {
219 my ($cls, $path) = @_;
220 my $imgpath = "$IMGROOT/$path";
221 my $st = stat $imgpath or die "no image `$path'";
222 return bless {
223 path => $path, imgpath => $imgpath,
224 mtime => $st->mtime,
225 img => undef,
226 rot => undef, flip => undef,
227 wd => undef, ht => undef,
228 _wd => undef, _ht => undef,
229 sz => undef
230 }, $cls;
231 }
232
233 sub _getsz ($) {
234 my ($me) = @_;
235 return if defined $me->{_wd};
236
237 my ($wd, $ht, $err) = Image::Size::imgsize $me->{imgpath};
238 defined $wd or die "failed to read size of `$me->{path}': $err";
239 my $sz = $wd; if ($sz < $ht) { $sz = $ht; }
240 @$me{"_wd", "_ht", "sz"} = ($wd, $ht, $sz);
241 }
242
243 sub _getexif ($) {
244 my ($me) = @_;
245 return if defined $me->{wd};
246
247 $me->_getsz;
248 my $exif = new Image::ExifTool; $exif->ExtractInfo($me->{imgpath});
249 my $orient = $exif->GetValue("Orientation", "ValueConv");
250 my ($wd, $ht) = @$me{"_wd", "_ht"};
251 my ($rot, $flip);
252 if (defined $orient) { ($rot, $flip) = $ORIENT{$orient}->@*; }
253 else { ($rot, $flip) = (0, 0); }
254 if ($rot%2) { ($wd, $ht) = ($ht, $wd); }
255 @$me{"rot", "flip", "wd", "ht"} = ($rot, $flip, $wd, $ht);
256 }
257
258 sub sz ($) { my ($me) = @_; $me->_getsz; return $me->{sz}; }
259 sub wd ($) { my ($me) = @_; $me->_getexif; return $me->{wd}; }
260 sub ht ($) { my ($me) = @_; $me->_getexif; return $me->{ht}; }
261
262 sub _check_gm ($) {
263 my ($rc) = @_;
264 "$rc" and die "failed to hack `$me->{img}': $rc";
265 }
266
267 sub scale ($$;$) {
268 my ($me, $scale, $forcep) = @_;
269 my $m = HTML::Mason::Request->instance;
270
271 my $path = $me->{path};
272 my $sz = $SIZE{$scale} or die "unknown scale `$scale'";
273 my $url;
274
275 if ($me->sz <= $sz)
276 { $url = $m->interp->apply_escapes("$IMGURL/$path", "u"); }
277 else {
278 my $tail = "scale.$sz/$path";
279 my $thumb = "$CACHE/$tail";
280 my $thumburl = $m->interp->apply_escapes("$CACHEURL/$tail", "u");
281
282 my $st = stat $thumb;
283 if ($st && $st->mtime > $me->{mtime})
284 { $url = $thumburl; }
285 elsif (!$forcep) {
286 $url =
287 $m->interp->apply_escapes("$SCRIPTURL/$path", "u") .
288 "?scale=$scale";
289 } else {
290 my $img = $me->{img};
291 unless (defined $img) {
292 $img = $me->{img} = Graphics::Magick->new;
293 _check_gm $img->Read($me->{imgpath});
294 }
295
296 my ($dir, undef, $ext) = TrivGal::split_path $thumb;
297 $img = $img->Clone;
298 my $new = "$TMP/t$$-thumb$ext";
299 _check_gm $img->Resize(geometry => $sz);
300 make_path $TMP, { mode => 0771 };
301 _check_gm $img->Write($new);
302 make_path $dir, { mode => 0771 };
303 rename $new, $thumb;
304 $url = $thumburl;
305 }
306 }
307
308 return $url;
309 }
310 }
311
312 ###--------------------------------------------------------------------------
313 ### Directory listings.
314
315 package TrivGal::Item {
316 sub new ($$) {
317 my ($cls, $name) = @_;
318 return bless { name => $name }, $cls;
319 }
320 sub name ($@) {
321 my ($me, @args) = @_;
322 return TrivGal::read_or_set $me, $me->{name}, @args;
323 }
324 sub comment ($@) {
325 my ($me, @args) = @_;
326 return TrivGal::read_or_set $me, $me->{comment}, @args;
327 }
328 }
329
330 export qw{listdir};
331 sub listdir ($) {
332 my ($path) = @_;
333 my (@d, @f);
334 my $ix = undef;
335
336 $path =~ s#/$##;
337 if (-f "$path/.tgal.index") {
338 open my $f, "<", "$path/.tgal.index";
339 my $item = undef;
340 my $comment = undef;
341 LINE: while (<$f>) {
342 chomp;
343 next LINE if /^\s*(\#|$)/;
344 if (s/^\s+//) {
345 die "no item" unless $item;
346 $comment = defined $comment ? $comment . "\n" . $_ : $_;
347 } else {
348 if ($item && $comment) { $item->comment($comment); }
349 my ($flags, $name, $c) =
350 /^ (?: ([-!]+) \s+)? # flags
351 (\S+) \s* # filename
352 (\S | \S.*\S )? # start of the comment
353 \s*
354 $/x;
355 my $indexp = $flags =~ /!/;
356 my $hidep = $flags =~ /-/;
357 $name = urldecode $name;
358 my $list;
359 $item = TrivGal::Item->new($name);
360 if ($name =~ m#/$#) {
361 $list = \@d;
362 die "can't index a folder" if $indexp;
363 } else {
364 $list = \@f;
365 my (undef, undef, $ext) = split_path $name;
366 die "unknown image type" unless $TYPE{lc $ext};
367 if ($indexp) {
368 die "two index images" if defined $ix;
369 $ix = $item;
370 }
371 }
372 $comment = $c;
373 push @$list, $item unless $hidep;
374 }
375 }
376 if ($item && $comment) { $item->comment($comment); }
377 close $f;
378 } else {
379 my $st = stat $path;
380 unless ($st->mode&0004) { return ([], [], undef); }
381
382 opendir $d, $path;
383 my @e = readdir $d;
384 closedir $d;
385
386 ENT: for my $e (sort @e) {
387 my (undef, undef, $ext) = split_path $e;
388 my $dotp = $e =~ /^\./;
389 my $st = stat "$path/$e";
390 my $list = undef;
391 if ($dotp) { }
392 elsif (-d $st) { $list = \@d; $e .= "/"; }
393 elsif ($TYPE{lc $ext} && -f $st) { $list = \@f; }
394 $list and push @$list, TrivGal::Item->new($e);
395 }
396 $ix = $f[0] if @f;
397 }
398
399 return (\@d, \@f, $ix);
400 }
401
402 export qw{contents};
403 sub contents ($) {
404 my ($file) = @_;
405 my $contents = "";
406 my $f;
407 local $@;
408 eval { open $f, "<", "$file"; };
409 if ($@) {
410 if ($@->isa("autodie::exception") && $@->errno == ENOENT)
411 { return undef; }
412 die $@;
413 }
414 while (sysread $f, $buf, 16384) { $contents .= $buf; }
415 close $f;
416 return $contents;
417 }
418
419 export qw{find_covering_file};
420 sub find_covering_file ($$$) {
421 my ($top, $path, $name) = @_;
422 for (;;) {
423 my $stuff = contents "$top/$path/$name"; return $stuff if defined $stuff;
424 if ($path eq "") { return undef; }
425 if ($path =~ m#^(.*)/[^/]+/?#) { $path = $1; }
426 else { $path = ""; }
427 }
428 }
429
430 ###----- That's all, folks --------------------------------------------------
431
432 clean_temp_files;
433
434 1;