aboutsummaryrefslogtreecommitdiff
path: root/main/src/ui/util/preview_file_chooser_native.vala
blob: 6473cde19b6b7595380c4934743f9b0c27fd5ec1 (plain) (blame)
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
using Gdk;
using Gtk;

using Dino.Entities;

namespace Dino.Ui {

public class PreviewFileChooserNative : Object {
    private const int PREVIEW_SIZE = 180;
    private const int PREVIEW_PADDING = 5;

    private Gtk.FileChooserNative? chooser = null;
    private Image preview_image = new Image();

    public PreviewFileChooserNative(string? title, Gtk.Window? parent, FileChooserAction action, string? accept_label, string? cancel_label) {
        chooser = new FileChooserNative(title, parent, action, accept_label, cancel_label);

        chooser.set_preview_widget(this.preview_image);
        chooser.use_preview_label = false;
        chooser.preview_widget_active = false;

        chooser.update_preview.connect(on_update_preview);
    }

    public void add_filter(owned Gtk.FileFilter filter) {
        chooser.add_filter(filter);
    }

    public SList<File> get_files() {
        return chooser.get_files();
    }

    public int run() {
        return chooser.run();
    }

    public string? get_filename() {
        return chooser.get_filename();
    }

    private void on_update_preview() {
        Pixbuf preview_pixbuf = get_preview_pixbuf();
        if (preview_pixbuf != null) {
            int extra_space = PREVIEW_SIZE - preview_pixbuf.width;
            int smaller_half = extra_space/2;
            int larger_half = extra_space - smaller_half;

            preview_image.set_margin_start(PREVIEW_PADDING + smaller_half);
            preview_image.set_margin_end(PREVIEW_PADDING + larger_half);

            preview_image.set_from_pixbuf(preview_pixbuf);
            chooser.preview_widget_active = true;
        } else {
            chooser.preview_widget_active = false;
        }
    }

    private Pixbuf? get_preview_pixbuf() {
        string? filename = chooser.get_preview_filename();
        if (filename == null) {
            return null;
        }

        int width = 0;
        int height = 0;
        Gdk.PixbufFormat? format = Gdk.Pixbuf.get_file_info(filename, out width, out height);
        if (format == null) {
            return null;
        }

        try {
            Gdk.Pixbuf pixbuf = new Gdk.Pixbuf.from_file_at_scale(filename, PREVIEW_SIZE, PREVIEW_SIZE, true);
            pixbuf = pixbuf.apply_embedded_orientation();
            return pixbuf;
        } catch (Error e) {
            return null;
        }
    }

}

}