aboutsummaryrefslogtreecommitdiff
path: root/src/dialogs.rs
blob: 45956abc4a6929a8e0135da9df36ad9321f0e054 (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
// Map, wardley map editor for linux
// Copyright (C) 2026 Rubén Beltrán del Río

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program 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 Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! Dialog helper functions for file operations and error display.

use std::path::PathBuf;

use gtk::prelude::*;
use relm4::gtk::gio;
use relm4::{ComponentSender, adw, gtk};

use crate::AppModel;
use crate::actions::{Action, ImageFormat};
use crate::constants;
use crate::file_registry;
use crate::tr;

/// Creates a file filter for .wmap files in file pickers.
pub fn create_file_filter() -> gtk::FileFilter {
    let filter = gtk::FileFilter::new();
    filter.add_pattern(&format!("*.{}", constants::FILE_EXTENSION));
    filter.add_mime_type(constants::MIME_TYPE);
    filter.set_name(Some(&tr!("Wardley Map Files")));
    filter
}

/// Shows an error dialog with the given title and message.
pub fn show_error(window: &adw::Window, title: &str, message: &str) {
    let dialog = gtk::AlertDialog::builder()
        .modal(true)
        .buttons([&tr!("Cancel"), "Ok"])
        .message(title)
        .detail(message)
        .build();
    dialog.show(Some(window));
}

/// Shows a file open dialog and handles the response.
pub fn show_open_dialog(
    window: &adw::Window,
    is_empty_document: bool,
    sender: ComponentSender<AppModel>,
) {
    let dialog = gtk::FileDialog::builder()
        .title(tr!("Open Map"))
        .modal(true)
        .build();

    let filter = create_file_filter();
    let filters = gtk::gio::ListStore::new::<gtk::FileFilter>();
    filters.append(&filter);
    dialog.set_filters(Some(&filters));

    let window_clone = window.clone();
    gtk::glib::spawn_future_local(async move {
        if let Ok(file) = dialog.open_future(Some(&window_clone)).await
            && let Some(path) = file.path()
        {
            // Check if file is already open - if so, focus that window
            if let Some(existing_window) = file_registry::find_window_for_file(&path) {
                existing_window.present();
                return;
            }

            if is_empty_document {
                sender.input(Action::LoadFile(path));
            } else {
                AppModel::open_new_window(Some(path), None);
            }
        }
    });
}

/// Shows a file save dialog and handles the response.
pub fn show_save_dialog(
    window: &adw::Window,
    current_file: Option<&PathBuf>,
    close_after: bool,
    sender: ComponentSender<AppModel>,
) {
    let mut dialog_builder = gtk::FileDialog::builder()
        .title(tr!("Save Map As"))
        .modal(true);

    let filter = create_file_filter();
    let filters = gtk::gio::ListStore::new::<gtk::FileFilter>();
    filters.append(&filter);
    dialog_builder = dialog_builder.filters(&filters);

    let default_filename = "map.wmap";
    if let Some(current_path) = current_file {
        if let Some(parent) = current_path.parent() {
            let folder = gtk::gio::File::for_path(parent);
            dialog_builder = dialog_builder.initial_folder(&folder);
        }
        if let Some(filename) = current_path.file_name() {
            dialog_builder =
                dialog_builder.initial_name(filename.to_str().unwrap_or(default_filename));
        }
    } else {
        dialog_builder = dialog_builder.initial_name(default_filename);
    }

    let dialog = dialog_builder.build();
    let window_clone = window.clone();
    gtk::glib::spawn_future_local(async move {
        if let Ok(file) = dialog.save_future(Some(&window_clone)).await
            && let Some(path) = file.path()
        {
            sender.input(Action::SaveToFile { path, close_after });
        }
    });
}

/// Shows a dialog asking whether to save unsaved changes before closing.
pub fn show_unsaved_changes_dialog(
    window: &adw::Window,
    current_file: Option<PathBuf>,
    sender: ComponentSender<AppModel>,
) {
    let dialog = gtk::AlertDialog::builder()
        .modal(true)
        .message(tr!("Unsaved Changes"))
        .detail(tr!("Save changes before closing?"))
        .buttons([tr!("Don't save"), tr!("Cancel"), tr!("Save")])
        .cancel_button(1)
        .default_button(2)
        .build();

    //dialog.show(Some(window));
    let cancellable = gio::Cancellable::current();
    let window_clone = window.clone();
    dialog.choose(
        Some(window),
        cancellable.as_ref(),
        move |answer| match answer {
            Ok(0) => {
                if let Some(ref path) = current_file {
                    file_registry::unregister_file(path);
                }
                window_clone.destroy();
            }
            Ok(2) => {
                if current_file.is_some() {
                    sender.input(Action::Save { close_after: true });
                } else {
                    sender.input(Action::SaveAs { close_after: true });
                }
            }
            _ => {}
        },
    );
}

/// Creates a file filter for an image format.
fn create_image_filter(format: ImageFormat) -> gtk::FileFilter {
    let filter = gtk::FileFilter::new();
    filter.add_pattern(&format!("*.{}", format.extension()));
    filter.add_mime_type(format.mime_type());
    let name = match format {
        ImageFormat::Png => tr!("PNG Image"),
        ImageFormat::Svg => tr!("SVG Image"),
    };
    filter.set_name(Some(&name));
    filter
}

/// Shows an export image dialog and handles the response.
pub fn show_export_dialog(
    window: &adw::Window,
    current_file: Option<&PathBuf>,
    sender: ComponentSender<AppModel>,
) {
    let png_filter = create_image_filter(ImageFormat::Png);
    let svg_filter = create_image_filter(ImageFormat::Svg);

    let filters = gtk::gio::ListStore::new::<gtk::FileFilter>();
    filters.append(&png_filter);
    filters.append(&svg_filter);

    let mut dialog_builder = gtk::FileDialog::builder()
        .title(tr!("Export Map as Image"))
        .modal(true)
        .filters(&filters)
        .default_filter(&png_filter);

    // Set default filename based on current file
    let base_name = current_file
        .as_ref()
        .and_then(|p| p.file_stem())
        .and_then(|s| s.to_str())
        .unwrap_or("map")
        .to_string();

    if let Some(current_path) = current_file
        && let Some(parent) = current_path.parent()
    {
        let folder = gtk::gio::File::for_path(parent);
        dialog_builder = dialog_builder.initial_folder(&folder);
    }

    dialog_builder = dialog_builder.initial_name(format!("{base_name}.png"));

    let dialog = dialog_builder.build();
    let window_clone = window.clone();
    gtk::glib::spawn_future_local(async move {
        if let Ok(file) = dialog.save_future(Some(&window_clone)).await
            && let Some(path) = file.path()
        {
            // Determine format from file extension
            let format = if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                match ext.to_lowercase().as_str() {
                    "svg" => ImageFormat::Svg,
                    _ => ImageFormat::Png,
                }
            } else {
                ImageFormat::Png
            };

            // Ensure correct extension
            let path = if path.extension().is_none() {
                path.with_extension(format.extension())
            } else {
                path
            };

            sender.input(Action::ExportToFile { path, format });
        }
    });
}