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
//! Dialogs - various built-in dialogs.
//!
//! All of the dialogs (apart from the font chooser) are built using a
//! "builder" style. The named function creates a relevant struct value,
//! and then functions on the relevant TkWIDGET struct alter the
//! default values in that struct, until finally calling `show`
//! will set up and display the dialog.
//!
//! There is only one font chooser dialog instance, and commands are
//! provided to interact with it directly.
//!
//! # Message boxes
//!
//! * also see the Tk [manual](https://www.tcl-lang.org/man/tcl8.6/TkCmd/messageBox.htm)
//!
//! The message-box is used to set up a simple alert, confirmation or
//! information dialog:
//!
//! ```ignore
//! rstk::message_box()
//!   .OPTION(VALUE) // 0 or more
//!   .show();
//! ```
//!
//! 1. `message_box` is called first, to get the TkMessageBox instance.
//! 2. `show` must be called last, to set up and display the dialog.
//! 3. zero or more options are added to the message box.
//!
//! # Chooser dialogs
//!
//! For colours, directories, files and fonts!
//!
//! Each dialog returns an Option type, with value None if cancelled.
//!
//! Tk manual pages:
//!
//! * [chooseColor](https://www.tcl-lang.org/man/tcl8.6/TkCmd/chooseColor.htm)
//! * [chooseDirectory](https://www.tcl-lang.org/man/tcl8.6/TkCmd/chooseDirectory.htm)
//! * [getOpenFile](https://www.tcl-lang.org/man/tcl8.6/TkCmd/getOpenFile.htm) (and getSaveFile)
//! * [fontchooser](https://www.tcl-lang.org/man/tcl8.6/TkCmd/fontchooser.htm)
//!

use super::font;
use super::toplevel;
use super::widget;
use super::wish;

/// Refers to the settings for TkMessageBox.
#[derive(Clone, Debug)]
pub struct TkMessageBox {
    default: Option<String>,
    detail: Option<String>,
    icon: widget::IconImage,
    message: Option<String>,
    parent: Option<String>,
    title: Option<String>,
    type_buttons: widget::DialogType,
}

/// Creates a message box to complete in builder style.
pub fn message_box() -> TkMessageBox {
    TkMessageBox {
        default: None,
        detail: None,
        icon: widget::IconImage::Error,
        message: None,
        parent: None,
        title: None,
        type_buttons: widget::DialogType::Ok,
    }
}

impl TkMessageBox {
    /// Sets name used for default button.
    pub fn default(&mut self, name: &str) -> &mut Self {
        self.default = Some(String::from(name));
        self
    }

    /// Sets submessage to display, below message.
    pub fn detail(&mut self, text: &str) -> &mut Self {
        self.detail = Some(String::from(text));
        self
    }

    /// Sets icon type.
    pub fn icon(&mut self, value: widget::IconImage) -> &mut Self {
        self.icon = value;
        self
    }

    /// Sets message to display.
    pub fn message(&mut self, text: &str) -> &mut Self {
        self.message = Some(String::from(text));
        self
    }

    /// Sets parent widget - dialog is usually shown relative to parent.
    pub fn parent(&mut self, value: &toplevel::TkTopLevel) -> &mut Self {
        self.parent = Some(String::from(&value.id));
        self
    }

    /// Sets title of the dialog window.
    pub fn title(&mut self, text: &str) -> &mut Self {
        self.title = Some(String::from(text));
        self
    }

    /// Sets type of dialog, which specifies its buttons.
    pub fn type_buttons(&mut self, value: widget::DialogType) -> &mut Self {
        self.type_buttons = value;
        self
    }

    /// Once message box is defined, this function will finally show it.
    ///
    /// Returns a string for the name of the button pressed.
    ///
    pub fn show(&self) -> String {
        let mut msg = String::from("puts [tk_messageBox ");

        if let Some(default) = &self.default {
            msg.push_str(&format!("-default {{{}}} ", default));
        }

        if let Some(detail) = &self.detail {
            msg.push_str(&format!("-detail {{{}}} ", detail));
        }

        msg.push_str(&format!("-icon {} ", self.icon));

        if let Some(message) = &self.message {
            msg.push_str(&format!("-message {{{}}} ", message));
        }

        if let Some(parent) = &self.parent {
            msg.push_str(&format!("-parent {} ", parent));
        }

        if let Some(title) = &self.title {
            msg.push_str(&format!("-title {{{}}} ", title));
        }

        msg.push_str(&format!("-type {} ", self.type_buttons));
        msg.push_str("] ; flush stdout");

        wish::ask_wish(&msg)
    }
}

/// Refers to the settings for TkColourChooser.
#[derive(Clone, Debug)]
pub struct TkColourChooser {
    parent: Option<String>,
    title: Option<String>,
    initial: Option<String>,
}

/// Creates a colour-chooser to complete in builder style.
pub fn colour_chooser() -> TkColourChooser {
    TkColourChooser {
        parent: None,
        title: None,
        initial: None,
    }
}

impl TkColourChooser {
    /// Sets parent widget - dialog is usually shown relative to parent.
    pub fn parent(&mut self, value: &toplevel::TkTopLevel) -> &mut Self {
        self.parent = Some(String::from(&value.id));
        self
    }

    /// Sets title of the dialog window.
    pub fn title(&mut self, text: &str) -> &mut Self {
        self.title = Some(String::from(text));
        self
    }

    /// Sets initial color of chooser.
    pub fn initial_color(&mut self, value: &str) -> &mut Self {
        self.initial_colour(value)
    }

    /// Sets initial colour of chooser.
    pub fn initial_colour(&mut self, value: &str) -> &mut Self {
        self.initial = Some(String::from(value));
        self
    }

    /// Once dialog is defined, this function will finally show it.
    ///
    /// Returns an option:
    ///
    /// * `Some(string)` - for the chosen colour, or
    /// * `None` - if cancel pressed.
    ///
    pub fn show(&self) -> Option<String> {
        let mut msg = String::from("puts [tk_chooseColor ");

        if let Some(parent) = &self.parent {
            msg.push_str(&format!("-parent {} ", parent));
        }

        if let Some(title) = &self.title {
            msg.push_str(&format!("-title {{{}}} ", title));
        }

        if let Some(initial) = &self.initial {
            msg.push_str(&format!("-initialcolor {{{}}} ", initial));
        }

        msg.push_str("] ; flush stdout");

        let result = wish::ask_wish(&msg);
        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }
}

/// Refers to the settings for TkDirectoryChooser.
#[derive(Clone, Debug)]
pub struct TkDirectoryChooser {
    parent: Option<String>,
    title: Option<String>,
    initial: Option<String>,
    must_exist: bool,
}

/// Creates a directory-chooser to complete in builder style.
pub fn directory_chooser() -> TkDirectoryChooser {
    TkDirectoryChooser {
        parent: None,
        title: None,
        initial: None,
        must_exist: false,
    }
}

impl TkDirectoryChooser {
    /// Sets parent widget - dialog is usually shown relative to parent.
    pub fn parent(&mut self, value: &toplevel::TkTopLevel) -> &mut Self {
        self.parent = Some(String::from(&value.id));
        self
    }

    /// Sets title of the dialog window.
    pub fn title(&mut self, text: &str) -> &mut Self {
        self.title = Some(String::from(text));
        self
    }

    /// Sets initial directory of chooser.
    pub fn initial_directory(&mut self, value: &str) -> &mut Self {
        self.initial = Some(String::from(value));
        self
    }

    /// Specify if directory must exist.
    pub fn must_exist(&mut self, value: bool) -> &mut Self {
        self.must_exist = value;
        self
    }

    /// Once dialog is defined, this function will finally show it.
    ///
    /// Returns an option:
    ///
    /// * `Some(string)` - for the chosen directory, or
    /// * `None` - if cancel pressed.
    ///
    pub fn show(&self) -> Option<String> {
        let mut msg = String::from("puts [tk_chooseDirectory ");

        if let Some(parent) = &self.parent {
            msg.push_str(&format!("-parent {} ", parent));
        }

        if let Some(title) = &self.title {
            msg.push_str(&format!("-title {{{}}} ", title));
        }

        if let Some(initial) = &self.initial {
            msg.push_str(&format!("-initialdir {{{}}} ", initial));
        }

        if self.must_exist {
            // default is false, so only change for true
            msg.push_str("-mustexist 1 ");
        }

        msg.push_str("] ; flush stdout");

        let result = wish::ask_wish(&msg);
        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }
}

/// Refers to the settings for TkOpenFileChooser.
#[derive(Clone, Debug)]
pub struct TkOpenFileChooser {
    parent: Option<String>,
    title: Option<String>,
    file_types: Option<Vec<(String, String)>>,
    initial_directory: Option<String>,
    initial_filename: Option<String>,
}

/// Creates an open-file dialog to complete in builder style.
pub fn open_file_chooser() -> TkOpenFileChooser {
    TkOpenFileChooser {
        parent: None,
        title: None,
        file_types: None,
        initial_directory: None,
        initial_filename: None,
    }
}

impl TkOpenFileChooser {
    /// Sets parent widget - dialog is usually shown relative to parent.
    pub fn parent(&mut self, value: &toplevel::TkTopLevel) -> &mut Self {
        self.parent = Some(String::from(&value.id));
        self
    }

    /// Sets title of the dialog window.
    pub fn title(&mut self, text: &str) -> &mut Self {
        self.title = Some(String::from(text));
        self
    }

    /// Sets list of file types.
    ///
    /// File types are passed as a list of pairs, e.g.:
    ///
    ///```ignore
    /// let file_types = [("C++", ".cpp"), ("Rust", ".rs"), ("Any", "*")];
    /// dialog.file_types(&file_types);
    ///```
    pub fn file_types(&mut self, file_types: &[(&str, &str)]) -> &mut Self {
        let mut types: Vec<(String, String)> = vec![];
        for (txt, pat) in file_types {
            types.push((String::from(*txt), String::from(*pat)));
        }
        self.file_types = Some(types);

        self
    }

    /// Sets initial directory of chooser.
    pub fn initial_directory(&mut self, value: &str) -> &mut Self {
        self.initial_directory = Some(String::from(value));
        self
    }

    /// Sets initial filename of chooser.
    pub fn initial_filename(&mut self, value: &str) -> &mut Self {
        self.initial_filename = Some(String::from(value));
        self
    }

    /// Once dialog is defined, this function will finally show it.
    ///
    /// Returns an option:
    ///
    /// * `Some(string)` - for the chosen filename, or
    /// * `None` - if cancel pressed.
    ///
    pub fn show(&self) -> Option<String> {
        let mut msg = String::from("puts [tk_getOpenFile ");

        if let Some(parent) = &self.parent {
            msg.push_str(&format!("-parent {} ", parent));
        }

        if let Some(title) = &self.title {
            msg.push_str(&format!("-title {{{}}} ", title));
        }

        if let Some(types) = &self.file_types {
            if !types.is_empty() {
                msg.push_str("-filetypes {");

                for (txt, pat) in types {
                    msg.push_str(&format!("{{{{{}}} {{{}}}}} ", *txt, *pat));
                }

                msg.push_str("} ");
            }
        }

        if let Some(initial) = &self.initial_directory {
            msg.push_str(&format!("-initialdir {{{}}} ", initial));
        }

        if let Some(initial) = &self.initial_filename {
            msg.push_str(&format!("-initialfile {{{}}} ", initial));
        }

        msg.push_str("] ; flush stdout");

        let result = wish::ask_wish(&msg);
        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }
}

/// Refers to the settings for TkSaveFileChooser.
#[derive(Clone, Debug)]
pub struct TkSaveFileChooser {
    parent: Option<String>,
    title: Option<String>,
    confirm_overwrite: bool,
    file_types: Option<Vec<(String, String)>>,
    initial_directory: Option<String>,
    initial_filename: Option<String>,
}

/// Creates a save-file dialog to complete in builder style.
pub fn save_file_chooser() -> TkSaveFileChooser {
    TkSaveFileChooser {
        parent: None,
        title: None,
        confirm_overwrite: true,
        file_types: None,
        initial_directory: None,
        initial_filename: None,
    }
}

impl TkSaveFileChooser {
    /// Sets parent widget - dialog is usually shown relative to parent.
    pub fn parent(&mut self, value: &toplevel::TkTopLevel) -> &mut Self {
        self.parent = Some(String::from(&value.id));
        self
    }

    /// Sets title of the dialog window.
    pub fn title(&mut self, text: &str) -> &mut Self {
        self.title = Some(String::from(text));
        self
    }

    /// Set (by default) to show a warning dialog if user attempts to
    /// select an existing filename. Call this to unset and remove the
    /// warning.
    pub fn confirm_overwrite(&mut self, value: bool) -> &mut Self {
        self.confirm_overwrite = value;
        self
    }

    /// Sets list of file types.
    ///
    /// File types are passed as a list of pairs, e.g.:
    ///
    ///```ignore
    /// let file_types = [("C++", ".cpp"), ("Rust", ".rs"), ("Any", "*")];
    /// dialog.file_types(&file_types);
    ///```
    pub fn file_types(&mut self, file_types: &[(&str, &str)]) -> &mut Self {
        let mut types: Vec<(String, String)> = vec![];
        for (txt, pat) in file_types {
            types.push((String::from(*txt), String::from(*pat)));
        }
        self.file_types = Some(types);

        self
    }

    /// Sets initial directory of chooser.
    pub fn initial_directory(&mut self, value: &str) -> &mut Self {
        self.initial_directory = Some(String::from(value));
        self
    }

    /// Sets initial filename of chooser.
    pub fn initial_filename(&mut self, value: &str) -> &mut Self {
        self.initial_filename = Some(String::from(value));
        self
    }

    /// Once dialog is defined, this function will finally show it.
    ///
    /// Returns an option:
    ///
    /// * `Some(string)` - for the chosen filename, or
    /// * `None` - if cancel pressed.
    ///
    pub fn show(&self) -> Option<String> {
        let mut msg = String::from("puts [tk_getSaveFile ");

        if let Some(parent) = &self.parent {
            msg.push_str(&format!("-parent {} ", parent));
        }

        if let Some(title) = &self.title {
            msg.push_str(&format!("-title {{{}}} ", title));
        }

        msg.push_str(&format!(
            "-confirmoverwrite {} ",
            if self.confirm_overwrite { "1" } else { "0" }
        ));

        if let Some(types) = &self.file_types {
            if !types.is_empty() {
                msg.push_str("-filetypes {");

                for (txt, pat) in types {
                    msg.push_str(&format!("{{{{{}}} {{{}}}}} ", *txt, *pat));
                }

                msg.push_str("} ");
            }
        }

        if let Some(initial) = &self.initial_directory {
            msg.push_str(&format!("-initialdir {{{}}} ", initial));
        }

        if let Some(initial) = &self.initial_filename {
            msg.push_str(&format!("-initialfile {{{}}} ", initial));
        }

        msg.push_str("] ; flush stdout");

        let result = wish::ask_wish(&msg);
        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }
}

// -- font chooser is different - use individual functions

/// Set the parent widget for the font-chooser.
pub fn font_chooser_parent(parent: &impl widget::TkWidget) {
    let msg = format!("tk fontchooser configure -parent {}", parent.id());
    wish::tell_wish(&msg);
}

/// Set the title for the font-chooser.
pub fn font_chooser_title(title: &str) {
    let msg = format!("tk fontchooser configure -title {}", title);
    wish::tell_wish(&msg);
}

/// Set the command to be called when a font is chosen.
pub fn font_chooser_command(command: impl Fn(font::TkFont) + Send + 'static) {
    wish::add_callback1_font("font", wish::mk_callback1_font(command));
    let msg = "tk fontchooser configure -command [list font_choice font]";
    wish::tell_wish(&msg);
}

/// Get the font for the font-chooser.
pub fn font_chooser_font_get() -> String {
    let msg = "tk fontchooser configure -font ";
    wish::ask_wish(&msg)
}

/// Set the font for the font-chooser.
pub fn font_chooser_font_set(font: &str) {
    let msg = format!("tk fontchooser configure -font {}", font);
    wish::tell_wish(&msg);
}

/// Hide the font-chooser, making it not visible.
pub fn font_chooser_hide() {
    let msg = "tk fontchooser hide";
    wish::tell_wish(&msg);
}

/// Show the font-chooser, making it visible.
pub fn font_chooser_show() {
    let msg = "tk fontchooser show";
    wish::tell_wish(&msg);
}

/// Check if the font-chooser is currently visible.
pub fn font_chooser_visible() -> bool {
    let msg = "tk fontchooser configure -visible ";
    let result = wish::ask_wish(&msg);
    result == "1"
}