summaryrefslogtreecommitdiff
path: root/lib/gcstar/GCItemsLists/GCImageListComponents.pm
blob: aa2bf2bea4ff0118be77e03ec9bed924b2b9f1a7 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
package GCImageListComponents;

###################################################
#
#  Copyright 2005-2011 Christian Jodar
#
#  This file is part of GCstar.
#
#  GCstar is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  GCstar is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with GCstar; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
###################################################

use strict;

{
    package GCImageListItem;
    
    use GCUtils;
    use GCStyle;
    use base "Gtk2::EventBox";
    use File::Temp qw/ tempfile /;
    
    @GCImageListItem::ISA = ('Gtk2::EventBox');
    
    sub new
    {
        my ($proto, $container, $info) = @_;
        my $class = ref($proto) || $proto;
        my $self  = $class->SUPER::new;
        bless ($self, $class);
        
        # Some information that we'll need later
        $self->{info} = $info;
        $self->{container} = $container;
        $self->{style} = $container->{style};
        $self->{tooltips} = $container->{tooltips};
        $self->{file} = $container->{parent}->{options}->file;
        $self->{collectionDir} = $container->{collectionDir};
        $self->{model} = $container->{parent}->{model};
        $self->{imageCache} = $container->{imageCache};
        $self->{dataManager} = $container->{parent}->{items};
        
        $self->can_focus(1);
        my $image = new Gtk2::Image;
        $self->add($image);
        $self->refreshInfo($info);
        $self->set_size_request($container->{style}->{vboxWidth}, $container->{style}->{vboxHeight});
        $self->show_all;
        
        return $self;
    }
    
    sub setInfo
    {
        my ($self, $info) = @_;

        $self->{info} = $info;
    }
    
    sub refreshInfo
    {
        my ($self, $info, $cacheRefresh) = @_;

        $self->setInfo($info);

        $self->refreshPopup;

        delete $self->{zoomedPixbufCache};

        {
            my $pixbuf = $self->createPixbuf($info, $cacheRefresh);
            if (! $self->{style}->{withImage})
            {
                $self->modify_bg('normal', $self->{style}->{inactiveBg});
            }
            $self->{previousPixbuf} = $pixbuf->copy;
            $self->child->set_from_pixbuf($pixbuf);
        }        
        if ($self->{selected})
        {
            $self->{selected} = 0;
            $self->highlight;
            $self->{selected} = 1;
        }
    }
    
    sub refreshPopup
    {
        my $self = shift;
        # Old versions of Gtk2 don't support set_tooltip_markup
        eval {
            $self->set_tooltip_markup($self->{dataManager}->getSummary($self->{info}->{idx}));
        };
        if ($@)
        {
            print "$@\n";
            # So we do it the old way for them
            $self->{tooltips}->set_tip($self, $self->{info}->{title}, '');
        }
    }
    
    sub savePicture
    {
        my $self = shift;
        $self->{previousPixbuf} = $self->child->get_pixbuf->copy
           if $self->child;
    }
    
    sub restorePicture
    {
        my $self = shift;
        $self->child->set_from_pixbuf($self->{previousPixbuf})
            if $self->{previousPixbuf} && $self->child;
    }
    
    sub startZoomAnimation
    {
        my $self = shift;
        $self->{currentZoom} = 1.01;
        my $pixbuf = $self->createPixbuf($self->{info}, 0, 1.01);
        $self->child->set_from_pixbuf($pixbuf);
        $self->{zoomTimeout} = Glib::Timeout->add(20 , sub {
            my $widget = shift;
            $widget->{currentZoom} += 0.02;
            if ($widget->{currentZoom} > 1.06)
            {
                $widget->{zoomTimeout} = undef;
                return 0;
            }
            my $pixbuf = $widget->createPixbuf($self->{info}, 0, $widget->{currentZoom});
            $widget->child->set_from_pixbuf($pixbuf)
                if $widget->child;
            return 1;
        }, $self);        
    }
    
    sub stopZoomAnimation
    {
        my $self = shift;
        Glib::Source->remove($self->{zoomTimeout})
            if $self->{zoomTimeout};
    }
    
    # This method sets all the event callbacks
    sub prepareHandlers
    {
        my ($self, $idx, $info) = @_;
        $self->{idx} = $idx;
        $self->{info} = $info;
        
        $self->signal_handler_disconnect($self->{mouseHandler})
            if $self->{mouseHandler};
        $self->{mouseHandler} = $self->signal_connect('button_press_event' => sub {
            my ($widget, $event) = @_;

            if (($event->type ne '2button-press') && !(($event->button eq 3) && ($widget->{selected})))
            {
                my $state = $event->get_state;
                my $keepPrevious = 0;
                if ($state =~ /control-mask/)
                {
                    $widget->{container}->select($widget->{idx}, 0, 1);
                }
                elsif ($state =~ /shift-mask/)
                {
                    $widget->{container}->restorePrevious;
                    $widget->{container}->selectMany($widget->{idx});
                }
                else
                {
                    $widget->{container}->select($widget->{idx});
                }
                $widget->{container}->setPreviousSelectedDisplayed($widget->{idx});
        
                #$self->{parent}->display($widget->{idx}) unless $event->type eq '2button-press';
                $widget->{container}->displayDetails(0, keys %{$widget->{container}->{selectedIndexes}});
            }
            
            $widget->{container}->displayDetails(1, $widget->{idx}) if $event->type eq '2button-press';
            $widget->{container}->showPopupMenu($event->button, $event->time) if ($event->button eq 3);
            $widget->grab_focus;
        });

        if ($self->{style}->{withAnimation})
        {
            $self->signal_handler_disconnect($self->{enterHandler})
                if $self->{enterHandler};
            $self->{enterHandler} = $self->signal_connect('enter_notify_event' => sub {
                my ($widget, $event) = @_;
                if (!$widget->{selected})
                {
                    $widget->startZoomAnimation;
                }
            });
            
            $self->signal_handler_disconnect($self->{leaveHandler})
                if $self->{leaveHandler};
            $self->{leaveHandler} = $self->signal_connect('leave_notify_event' => sub {
                my ($widget, $event) = @_;
                if (!$widget->{selected})
                {
                    $widget->stopZoomAnimation;
                    $widget->restorePicture;
                }
            });
        }
        

        $self->signal_handler_disconnect($self->{keyHandler})
            if $self->{keyHandler};

        $self->{keyHandler} = $self->signal_connect('key-press-event' => sub {
            my ($widget, $event) = @_;
            my $displayed = $self->{container}->convertIdxToDisplayed($widget->{idx});
            my $key = Gtk2::Gdk->keyval_name($event->keyval);
            if ($key eq 'Delete')
            {
                $widget->{container}->{parent}->deleteCurrentItem;
                return 1;
            }
            if (($key eq 'Return') || ($key eq 'space'))
            {
                $widget->{container}->displayDetails(1, $widget->{idx});
                return 1;
            }
            my $unicode = Gtk2::Gdk->keyval_to_unicode($event->keyval);
            if ($unicode)
            {
                $self->{container}->showSearch(pack('U',$unicode));
            }
            else
            {
                my $columns = $widget->{container}->getColumnsNumber;
                
                ($key eq 'Right')      ? $displayed++ :
                ($key eq 'Left')       ? $displayed-- :
                ($key eq 'Down')       ? $displayed += $columns : 
                ($key eq 'Up')         ? $displayed -= $columns :
                ($key eq 'Page_Down')  ? $displayed += ($widget->{style}->{pageCount} * $columns):
                ($key eq 'Page_Up')    ? $displayed -= ($widget->{style}->{pageCount} * $columns):
                ($key eq 'Home')       ? $displayed = 0 :
                ($key eq 'End')        ? $displayed = $widget->{container}->getNbItems - 1 :
                                         return 1;

                return 1 if ($displayed < 0) || ($displayed >= $widget->{container}->getNbItems);
                my $column = $displayed % $columns;                
                my $valueIdx = $widget->{container}->convertDisplayedToIdx($displayed);
#                my $keepPrevious = 0;
                my $state = $event->get_state;
                if ($state =~ /control-mask/)
                {
                    $widget->{container}->select($valueIdx, 0, 1);
                    $widget->{container}->unsetPreviousSelectedDisplayed;
                }
                elsif ($state =~ /shift-mask/)
                {
                    $widget->{container}->setPreviousSelectedDisplayed($widget->{idx});
                    $widget->{container}->restorePrevious;
                    $widget->{container}->selectMany($valueIdx);
                }
                else
                {
                    $widget->{container}->select($valueIdx);
                    $widget->{container}->unsetPreviousSelectedDisplayed;
                }
                $widget->{container}->displayDetails(0, $valueIdx);
                $widget->{container}->grab_focus;
                $widget->{container}->showCurrent unless (($key eq 'Left')  && ($column != ($columns - 1)))
                                       || (($key eq 'Right') && ($column != 0));
            }
            return 1;
            
        });
        
    }
    
    sub highlight
    {
        my ($self, $keepPrevious) = @_;
        return if $self->{selected};
        $self->{selected} = 1;
        if (! $self->{style}->{withImage})
        {
            $self->modify_bg('normal', $self->{style}->{activeBg});
        }
#        $self->savePicture
#            unless $keepPrevious;
        
        my $pixbuf = $self->createPixbuf($self->{info}, 0, 1.1);
        
        $pixbuf->saturate_and_pixelate($pixbuf, 1.5, 0);
        $pixbuf = $pixbuf->composite_color_simple ($pixbuf->get_width, $pixbuf->get_height, 'nearest',220, 128, $self->{style}->{activeBgValue}, $self->{style}->{activeBgValue});
        $self->child->set_from_pixbuf($pixbuf);
    }
    
    sub unhighlight
    {
        my ($self) = @_;

        $self->modify_bg('normal', $self->{style}->{inactiveBg})
            if (! $self->{style}->{withImage});
        $self->restorePicture;
        $self->{selected} = 0;
    }
    
    sub createPixbuf
    {
        my ($self, $info, $cacheRefresh, $zoom) = @_;
        
        my $displayedImage = $info->{picture};
        my $pixbuf = undef;
        
        my $borrower = $info->{borrower};
        my $favourite = $info->{favourite};
        
        # Item has a picture assigned
        if ($cacheRefresh)
        {
            $self->{imageCache}->forceCacheUpdateForNextUse;
        }
        
        if ($zoom)
        {
            if (! exists $self->{zoomedPixbufCache}->{$zoom})
            {
                $self->{zoomedPixbufCache}->{$zoom} = $self->{imageCache}->getPixbuf($info, $zoom);
            }
            $pixbuf = $self->{zoomedPixbufCache}->{$zoom};
        }
        else
        {
            $pixbuf = $self->{imageCache}->getPixbuf($info, $zoom);
        }

        my $width;
        my $height;
        my $boxWidth = $self->{style}->{imgWidth};
        my $boxHeight = $self->{style}->{imgHeight};

        my $overlay;
        my $imgWidth;
        my $imgHeight;
        my $targetOverlayHeight;
        my $targetOverlayWidth;
        my $pixbufTempHeight;
        my $pixbufTempWidth;
        my $alpha = 1;
        if ($self->{style}->{useOverlays})
        {
            # Need to call this to get the overlay padding        
            ($imgWidth, $imgHeight, $overlay) = $self->{imageCache}->getDestinationImgSize($pixbuf->get_width,
                                                                                      $pixbuf->get_height);                    
        }
        $width = $pixbuf->get_width;
        $height = $pixbuf->get_height;
        
        # Do the composition

        if ($self->{style}->{useOverlays})
        {
            if ($self->{style}->{withImage})
            {
                # Using background, so center accordingly
                my $offsetX = (($self->{style}->{offsetX} / 2) * $self->{style}->{factor}) + (($boxWidth - ($width + $overlay->{paddingLeft} + $overlay->{paddingRight})) / 2);
                my $offsetY = 15 * $self->{style}->{factor} + ($boxHeight - ($height + $overlay->{paddingTop} + $overlay->{paddingBottom}));

                # Make an empty pixbuf to work within
                my $tempPixbuf =Gtk2::Gdk::Pixbuf->new('rgb', 1, 8,
                                                $self->{style}->{backgroundPixbuf}->get_width,
                                                $self->{style}->{backgroundPixbuf}->get_height);
                $tempPixbuf->fill(0x00000000);

                # Place cover in pixbuf
                $pixbuf->composite($tempPixbuf,
                                      $offsetX + $overlay->{paddingLeft}, $offsetY + $overlay->{paddingTop}, 
                                      $width , $height,
                                      $offsetX + $overlay->{paddingLeft}, $offsetY + $overlay->{paddingTop}, 
                                      1, 1, 
                                      'nearest', 255);
                $pixbuf = $tempPixbuf;
 
                # Composite overlay picture
                $self->{style}->{overlayPixbuf}->composite($pixbuf,
                                                  $offsetX, $offsetY,
                                                  $width + $overlay->{paddingLeft} + $overlay->{paddingRight},
                                                  $height + $overlay->{paddingTop} + $overlay->{paddingBottom},
                                                  $offsetX, $offsetY,
                                                  ($width + $overlay->{paddingLeft} + $overlay->{paddingRight}) / $self->{style}->{overlayPixbuf}->get_width,
                                                  ($height + $overlay->{paddingTop} + $overlay->{paddingBottom}) / $self->{style}->{overlayPixbuf}->get_height, 
                                                  'nearest', 255);

                # Overlay borrower image if required
                if ($borrower && ($borrower ne 'none'))
                {
                   # De-saturate borrowed items
                   $pixbuf->saturate_and_pixelate($pixbuf, .1, 0);
                   $self->{style}->{lendPixbuf}->composite($pixbuf,
                                                  $pixbuf->get_width - $self->{style}->{lendPixbuf}->get_width - $offsetX,
                                                  $offsetY + $height + $overlay->{paddingTop} + $overlay->{paddingBottom} - $self->{style}->{lendPixbuf}->get_height,
                                                  $self->{style}->{lendPixbuf}->get_width, $self->{style}->{lendPixbuf}->get_height,
                                                  $pixbuf->get_width - $self->{style}->{lendPixbuf}->get_width - $offsetX,
                                                  $offsetY + $height + $overlay->{paddingTop} + $overlay->{paddingBottom} - $self->{style}->{lendPixbuf}->get_height,
                                                  1, 1, 
                                                  'nearest', 255);
                }

                # Overlay favourite image if required
                if ($favourite)
                {
                   $self->{style}->{favPixbuf}->composite($pixbuf,
                                                  $pixbuf->get_width - $self->{style}->{favPixbuf}->get_width - $offsetX,
                                                  $offsetY,
                                                  $self->{style}->{favPixbuf}->get_width, $self->{style}->{favPixbuf}->get_height,
                                                  $pixbuf->get_width - $self->{style}->{favPixbuf}->get_width - $offsetX,
                                                  $offsetY,
                                                  1, 1, 
                                                  'nearest', 255);
                }

                # Create and apply reflection if required
                if ($self->{style}->{withReflect})
                {
                    my $reflect;
                    $reflect = $pixbuf->flip(0);
                    $reflect->composite(
                        $pixbuf,
                        0, 2 * ($offsetY + $height + $overlay->{paddingTop} + $overlay->{paddingBottom}) - $pixbuf->get_height,
                        $pixbuf->get_width,
                        2 * ($pixbuf->get_height - $height - $offsetY - $overlay->{paddingTop} - $overlay->{paddingBottom}) - (10 * $self->{style}->{factor}),
                        0, 2 * ($offsetY + $height + $overlay->{paddingTop} + $overlay->{paddingBottom}) - $pixbuf->get_height,
                        1, 1,
                        'nearest', 100
                    );

                    # Apply foreground fading
                    $self->{style}->{foregroundPixbuf}->composite(
                        $pixbuf,
                        0, 0,
                        $pixbuf->get_width, $pixbuf->get_height,
                        0, 0,
                        1, 1,
                        'nearest', 255
                    );
                }

                # Heft created pixbuf onto background
                my $bgPixbuf = $self->{style}->{backgroundPixbuf}->copy;
                $pixbuf->composite($bgPixbuf,
                                      0,0,
                                      $pixbuf->get_width , $pixbuf->get_height,
                                      0,0,
                                      1, 1, 
                                      'nearest', 255);
                $pixbuf = $bgPixbuf;

            }
            else
            {
                # Not using background, so we need to make an empty pixbuf which is right size for overlay first
                my $tempPixbuf =Gtk2::Gdk::Pixbuf->new('rgb', 1, 8,
                                                $width + $overlay->{paddingLeft} + $overlay->{paddingRight},
                                                $height + $overlay->{paddingTop} + $overlay->{paddingBottom});
                $tempPixbuf->fill(0x00000000);
                            
                # Now, place list image inside empty pixbuf
                $pixbuf->composite($tempPixbuf,
                                      $overlay->{paddingLeft}, $overlay->{paddingTop}, 
                                      $width , $height,
                                      $overlay->{paddingLeft}, $overlay->{paddingTop}, 
                                      1, 1, 
                                      'nearest', 255 * $alpha);
                $pixbuf = $tempPixbuf;

                # Place overlay on top of pixbuf
                $self->{style}->{overlayPixbuf}->composite($pixbuf,
                                                  0, 0,
                                                  $width + $overlay->{paddingLeft} + $overlay->{paddingRight},
                                                  $height + $overlay->{paddingTop} + $overlay->{paddingBottom},
                                                  0, 0,
                                                  ($width + $overlay->{paddingLeft} + $overlay->{paddingRight}) / $self->{style}->{overlayPixbuf}->get_width,
                                                  ($height + $overlay->{paddingTop} + $overlay->{paddingBottom}) / $self->{style}->{overlayPixbuf}->get_height, 
                                                  'nearest', 255 * $alpha);

                # Overlay borrower image if required
                if ($borrower && ($borrower ne 'none'))
                {
                   # De-saturate borrowed items
                   $pixbuf->saturate_and_pixelate($pixbuf, .1, 0);

                   $self->{style}->{lendPixbuf}->composite($pixbuf,
                                                  $pixbuf->get_width - $self->{style}->{lendPixbuf}->get_width,
                                                  $pixbuf->get_height - $self->{style}->{lendPixbuf}->get_height,
                                                  $self->{style}->{lendPixbuf}->get_width, $self->{style}->{lendPixbuf}->get_height,
                                                  $pixbuf->get_width - $self->{style}->{lendPixbuf}->get_width,
                                                  $pixbuf->get_height - $self->{style}->{lendPixbuf}->get_height,
                                                  1, 1, 
                                                  'nearest', 255);
                }

                # Overlay favourite image if required
                if ($favourite)
                {
                   $self->{style}->{favPixbuf}->composite($pixbuf,
                                                  $pixbuf->get_width - $self->{style}->{favPixbuf}->get_width,
                                                  0,
                                                  $self->{style}->{favPixbuf}->get_width, $self->{style}->{favPixbuf}->get_height,
                                                  $pixbuf->get_width - $self->{style}->{favPixbuf}->get_width,
                                                  0,
                                                  1, 1, 
                                                  'nearest', 255);
                }

            }
        }
        else
        {
            # No overlays, nice and simple

            # Overlay borrower image if required
            if ($borrower && ($borrower ne 'none'))
            {
               # De-saturate borrowed items
               $pixbuf->saturate_and_pixelate($pixbuf, .1, 0);
               $self->{style}->{lendPixbuf}->composite($pixbuf,
                                              $width - $self->{style}->{lendPixbuf}->get_width - $self->{style}->{factor},
                                              $height - $self->{style}->{lendPixbuf}->get_height - $self->{style}->{factor},
                                              $self->{style}->{lendPixbuf}->get_width, $self->{style}->{lendPixbuf}->get_height,
                                              $width - $self->{style}->{lendPixbuf}->get_width - $self->{style}->{factor},
                                              $height - $self->{style}->{lendPixbuf}->get_height - $self->{style}->{factor},
                                              1, 1, 
                                              'nearest', 255);
            }

            # Overlay favourite image if required
            if ($favourite)
            {
               $self->{style}->{favPixbuf}->composite($pixbuf,
                                              $width - $self->{style}->{favPixbuf}->get_width - $self->{style}->{factor},
                                              $self->{style}->{factor},
                                              $self->{style}->{favPixbuf}->get_width, $self->{style}->{favPixbuf}->get_height,
                                              $width - $self->{style}->{favPixbuf}->get_width - $self->{style}->{factor},
                                              $self->{style}->{factor},
                                              1, 1, 
                                              'nearest', 255);
            }

            my $reflect;
            $reflect = $pixbuf->flip(0)
                if $self->{style}->{withReflect};

            my $offsetX = (($self->{style}->{offsetX} / 2) * $self->{style}->{factor}) + (($boxWidth - $width) / 2);
            my $offsetY = 15 * $self->{style}->{factor} + ($boxHeight - $height);
            if ($self->{style}->{withImage})
            {
                my $bgPixbuf = $self->{style}->{backgroundPixbuf}->copy;
                $pixbuf->composite($bgPixbuf,
                                   $offsetX, $offsetY, 
                                   $width, $height,
                                   $offsetX, $offsetY,
                                   1, 1, 
                                   'nearest', 255);
                $pixbuf = $bgPixbuf;
            }

            if ($self->{style}->{withReflect})
            {
                $reflect->composite(
                    $pixbuf,
                    $offsetX, $height + $offsetY,
                    $width, $pixbuf->get_height - $height - $offsetY - (10 * $self->{style}->{factor}),
                    $offsetX, $height + $offsetY,
                    1, 1,
                    'nearest', 100
                );

                # Apply foreground fading
                $self->{style}->{foregroundPixbuf}->composite(
                    $pixbuf,
                    0, 0,
                    $pixbuf->get_width, $pixbuf->get_height,
                    0, 0,
                    1, 1,
                    'nearest', 255
                );
            }
        }
        return $pixbuf;
    }
    

    
}

{
    package GCImageCache;
    
    use File::Path;
    use File::Copy;
    use List::Util qw/min/;
    
    sub new
    {
        my ($proto, $imagesDir, $imageSize, $style, $defaultImage) = @_;
        my $class = ref($proto) || $proto;
        my $self  = {
            imagesDir => $imagesDir,
            imageSize => $imageSize,
            style => $style,
            cacheDir => $imagesDir.'/.cache/',
            oldCacheDir => $imagesDir,
            defaultImage => $defaultImage,
            forceUpdate => 0,
        };
        # Make sure destination directory exists
        if ( ! -d $self->{cacheDir})
        {
            mkpath $self->{cacheDir};
        }
        bless ($self, $class);
        
        $self->clearOldCache;
        
        return $self;
    }
    
    # This method removes images cached by previous versions
    sub clearOldCache
    {
        my $self = shift;
        my $trashDir = $self->{imagesDir}.'.trash';
        mkpath $trashDir;
        foreach (glob $self->{oldCacheDir}.'/*')
        {
            if (/\.cache\.[0-4](\.|$)/)
            {
                move $_, $trashDir;
            }
        }
    }
    
    sub forceCacheUpdateForNextUse
    {
        my ($self) = @_;
        $self->{forceUpdate} = 1;
    }
    
    sub getPixbuf
    {
        my ($self, $info, $zoom) = @_;
        my $fileName;
        my $pixbuf = undef;
        if (!$zoom)
        {
            $fileName = $self->getCachedFileName($info);
            if ($self->{forceUpdate} || (! -e $fileName))
            {
                $self->createImageCache($info);
            }
            $self->{forceUpdate} = 0;
            eval {
                $pixbuf = Gtk2::Gdk::Pixbuf->new_from_file($fileName);
            };
        }
        else
        {
            # When a zoom is requested, we have to generate the picture
            $fileName = $self->getCachedFileName($info);
            # Get picture size from cached file to avoid re-computing everything
            my ($picFormat, $picWidth, $picHeight) = Gtk2::Gdk::Pixbuf->get_file_info($fileName);
            # Then open the original file
            my $origFileName = $info->{picture};
            if (! -f $origFileName)
            {
                $origFileName = $self->{defaultImage};
            }
            if (!$self->{style}->{useOverlays})
            {
                $zoom -= 0.01;
            }
            
            eval {
                $pixbuf = Gtk2::Gdk::Pixbuf->new_from_file($origFileName);
                my $newWidth = int($picWidth * $zoom);
                my $newHeight = int($picHeight * $zoom);
                $pixbuf = GCUtils::scaleMaxPixbuf($pixbuf, $newWidth, $newHeight, 1, 0);            
            };
        }
            
        return $pixbuf;
    }
    
    sub getCachedFileName
    {
        my ($self, $info, $size) = @_;
        
        my $gcsautoid = $info->{autoid};
        my $title = $info->{title};
        
        $title =~ s/[^a-zA-Z0-9]*//g;
        my $cacheFilename = $self->{cacheDir};
        if ($info->{picture})
        {
            $cacheFilename .= $gcsautoid
                             ."."
                             .$title;
        }
        else
        {
            $cacheFilename .= 'GCSDefaultImage';
        }
        $cacheFilename .= (defined $size ? $size : $self->{imageSize});
        $cacheFilename .= ".overlay"
            if $self->{style}->{useOverlays};

        return $cacheFilename;
    }
    
    # Resizes artwork to required sizes and saves copies of the images, for fast loading
    sub createImageCache
    {
        my ($self, $info) = @_;

        my $srcImage = $info->{picture};
        if (! -f $srcImage)
        {
            $srcImage = $self->{defaultImage};
            $info->{picture} = "";
        }

        # Load in the original source image
        my $origPixbuf = Gtk2::Gdk::Pixbuf->new_from_file($srcImage);
        
        my $gcsautoid = $info->{autoid};
        my $title = $info->{title};
        $title =~ s/[^a-zA-Z0-9]*//g;
        # Get original picture format
        my ($picFormat, $picWidth, $picHeight) = Gtk2::Gdk::Pixbuf->get_file_info($srcImage);

        # Loop through possible sizes
        for (my $size = 0; $size < 5; $size++) {
            my $imgWidth;
            my $imgHeight;
            my $overlay;
            
            my $cacheFilename = $self->getCachedFileName($info, $size);

            # Get size for cached image
            ($imgWidth, $imgHeight, $overlay) = $self->getDestinationImgSize($picWidth,
                                                                             $picHeight,
                                                                             $size);
            
            # Scale pixbuf and save
            my $scaledPixbuf = GCUtils::scaleMaxPixbuf($origPixbuf, $imgWidth, $imgHeight, 0, 0);
            if ($picFormat->{name} eq 'jpeg')
            {
                $scaledPixbuf->save ($cacheFilename, 'jpeg', quality => '99');        
            }
            else
            {
                $scaledPixbuf->save ($cacheFilename, 'png');                    
            }
        }
    }

    # Calculates height and width of list image
    sub getDestinationImgSize
    {
        my ($self, $origWidth, $origHeight, $size) = @_;
        
        $size = $self->{imageSize}
            if (!defined $size);
        
        my $imgWidth;
        my $imgHeight;
        my $overlay;
        
        # No overlays
        $imgWidth = $self->{style}->{imgWidth} / $self->{style}->{factor};
        $imgHeight = $self->{style}->{imgHeight} / $self->{style}->{factor};
                               
        if ($self->{style}->{useOverlays})
        {
            # Overlays
            
            # Calculate size of list image with proportional size of overlay padding added
            my $pixbufTempHeight = (($self->{style}->{overlayPaddingTop} + $self->{style}->{overlayPaddingBottom})/$self->{style}->{overlayPixbuf}->get_height + 1) * $origHeight;
            my $pixbufTempWidth = (($self->{style}->{overlayPaddingLeft} + $self->{style}->{overlayPaddingRight})/$self->{style}->{overlayPixbuf}->get_width + 1) * $origWidth;

            # Find out target size of overlay, keeping the same ratio as the size calculated above (ie, list image + relative padding)
            my $ratio = $pixbufTempHeight / $pixbufTempWidth;
            my $targetOverlayHeight;
            my $targetOverlayWidth;
            if (($pixbufTempWidth > $imgWidth) || ($pixbufTempHeight > $imgHeight))
            {
                if (($pixbufTempWidth * $imgHeight/$pixbufTempHeight) < $imgHeight )
                {
                    $targetOverlayHeight = $imgHeight;
                    $targetOverlayWidth = int($imgHeight / $ratio);
                }
                else
                {
                    $targetOverlayHeight = int( $imgWidth * $ratio);
                    $targetOverlayWidth =  $imgWidth;
                }
            }
            else
            {
                # Special case when image is small enough and doesn't need to be resized
                $targetOverlayHeight = $pixbufTempHeight;
                $targetOverlayWidth = $pixbufTempWidth;
            }

            # Calculate final offset amounts for target size of overlay
            $overlay->{paddingLeft} = int($self->{style}->{overlayPaddingLeft} * $targetOverlayWidth / $self->{style}->{overlayPixbuf}->get_width);
            $overlay->{paddingRight} = int($self->{style}->{overlayPaddingRight} * $targetOverlayWidth / $self->{style}->{overlayPixbuf}->get_width);
            $overlay->{paddingTop} = int($self->{style}->{overlayPaddingTop} * $targetOverlayHeight / $self->{style}->{overlayPixbuf}->get_height);
            $overlay->{paddingBottom} = int($self->{style}->{overlayPaddingBottom} * $targetOverlayHeight / $self->{style}->{overlayPixbuf}->get_height);

            $imgWidth = $imgWidth - $overlay->{paddingLeft} - $overlay->{paddingRight};
            $imgHeight = $imgHeight - $overlay->{paddingTop} - $overlay->{paddingBottom};
        }

        my $factor = ($size == 0) ? 0.5
                        : ($size == 1) ? 0.8
                        : ($size == 3) ? 1.5
                        : ($size == 4) ? 2
                        : 1;                        
        $imgWidth *= $factor;
        $imgHeight *= $factor;
        
        return ($imgWidth, $imgHeight, $overlay);
    }
    
}

1;