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
//! Reusable and easily configurable open button dialog component.
//!
//! **[Example implementation](https://github.com/Relm4/Relm4/blob/main/relm4-components/examples/open_button.rs)**
use relm4::factory::{DynamicIndex, FactoryVecDeque};
use relm4::gtk::prelude::*;
use relm4::{
    gtk, Component, ComponentController, ComponentParts, ComponentSender, Controller,
    SimpleComponent,
};

use crate::open_dialog::{OpenDialog, OpenDialogMsg, OpenDialogResponse, OpenDialogSettings};

use std::fs;
use std::path::PathBuf;

mod factory;

use factory::FileListItem;

/// Open button component.
///
/// Creates a button with custom text that can be used to open a file chooser dialog. If a file is
/// chosen, then it will be emitted as an output. The component can also optionally display a
/// popover list of open files if [`OpenButtonSettings::recently_opened_files`] is set to a value.
#[tracker::track]
#[derive(Debug)]
pub struct OpenButton {
    #[do_not_track]
    config: OpenButtonSettings,
    #[do_not_track]
    dialog: Controller<OpenDialog>,
    #[do_not_track]
    recent_files: Option<FactoryVecDeque<FileListItem>>,
    initialized: bool,
    #[do_not_track]
    reset_popover: bool,
}

#[derive(Debug)]
/// Configuration for the open button component
pub struct OpenButtonSettings {
    /// Settings for the open file dialog.
    pub dialog_settings: OpenDialogSettings,
    /// Text of the open button.
    pub text: &'static str,
    /// Path to a file where recent files should be stored.
    /// This list is updated fully automatically.
    pub recently_opened_files: Option<&'static str>,
    /// Maximum amount of recent files to store.
    /// This is only used if a path for storing the recently opened files was set.
    pub max_recent_files: usize,
}

#[doc(hidden)]
#[derive(Debug)]
pub enum OpenButtonMsg {
    Open(PathBuf),
    OpenRecent(DynamicIndex),
    ShowDialog,
    Ignore,
}

/// Widgets of the open button component
#[relm4::component(pub)]
impl SimpleComponent for OpenButton {
    type Init = OpenButtonSettings;
    type Input = OpenButtonMsg;
    type Output = PathBuf;

    view! {
        gtk::Box {
            add_css_class: "linked",
            gtk::Button {
                set_label: model.config.text,
                connect_clicked => OpenButtonMsg::ShowDialog,
            },
            gtk::MenuButton {
                set_visible: model.config.recently_opened_files.is_some(),

                #[wrap(Some)]
                #[name(popover)]
                set_popover = &gtk::Popover {
                    gtk::ScrolledWindow {
                        set_hscrollbar_policy: gtk::PolicyType::Never,
                        set_min_content_width: 100,
                        set_min_content_height: 100,
                        set_min_content_height: 300,

                        #[name(recent_files_list)]
                        gtk::Box {
                            set_orientation: gtk::Orientation::Vertical,
                            set_vexpand: true,
                            set_hexpand: true,
                        }
                    }
                }
            }
        }
    }

    fn update(&mut self, msg: Self::Input, sender: ComponentSender<Self>) {
        self.reset_popover = false;

        match msg {
            OpenButtonMsg::ShowDialog => {
                self.dialog.emit(OpenDialogMsg::Open);
            }
            OpenButtonMsg::Open(path) => {
                sender.output(path.clone()).unwrap();
                self.reset_popover = true;

                if let Some(recent_files) = &mut self.recent_files {
                    let index = recent_files.iter().position(|item| item.path == path);

                    if let Some(index) = index {
                        recent_files.guard().remove(index);
                    }

                    if recent_files.len() < self.config.max_recent_files {
                        recent_files.guard().push_front(path);
                    }

                    let contents = recent_files
                        .iter()
                        .filter_map(|recent_path| {
                            recent_path.path.to_str().map(|s| format!("{s}\n"))
                        })
                        .collect::<String>();

                    let _ = fs::write(self.config.recently_opened_files.unwrap(), contents);
                }
            }
            OpenButtonMsg::OpenRecent(index) => {
                if let Some(item) = self
                    .recent_files
                    .as_ref()
                    .and_then(|recent_files| recent_files.get(index.current_index()))
                {
                    sender.input(OpenButtonMsg::Open(PathBuf::from(&item.path)));
                }
            }
            OpenButtonMsg::Ignore => (),
        }
    }

    fn pre_view() {
        if self.reset_popover {
            popover.popdown();
        }
    }

    fn init(
        settings: Self::Init,
        root: &Self::Root,
        sender: ComponentSender<Self>,
    ) -> ComponentParts<Self> {
        let dialog = OpenDialog::builder()
            .transient_for_native(root)
            .launch(settings.dialog_settings.clone())
            .forward(sender.input_sender(), |response| match response {
                OpenDialogResponse::Accept(path) => OpenButtonMsg::Open(path),
                OpenDialogResponse::Cancel => OpenButtonMsg::Ignore,
            });

        let mut model = Self {
            config: settings,
            dialog,
            initialized: false,
            recent_files: None,
            reset_popover: false,
            tracker: 0,
        };

        let widgets = view_output!();

        if let Some(filename) = model.config.recently_opened_files {
            let mut factory =
                FactoryVecDeque::new(widgets.recent_files_list.clone(), sender.input_sender());

            if let Ok(entries) = fs::read_to_string(filename) {
                let mut guard = factory.guard();
                for entry in entries.lines() {
                    guard.push_back(PathBuf::from(entry));
                }
            }

            model.recent_files = Some(factory);
        }

        ComponentParts { model, widgets }
    }
}