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
//! Menu widget - for building menubars and menus.
//!
//! The menu widget is a versatile widget. It can take on any of these
//! roles:
//!
//! * a window's menubar, containing several menus, such as "File", "Edit",
//!   "Help" etc.
//! * a menu containing menu items, such as "Open File", or submenus, such
//!   as "Recent files...".
//! * a menu button, which can be clicked to invoke an action. This button
//!   can act as a button, a check button, or a radio button.
//!
//! This library uses separate structs for the different types of menu which can
//! be added to an existing menu. These are built up in standard "builder"
//! style, before being added or inserted.
//!
//! * also see the Tk [manual](https://www.tcl-lang.org/man/tcl8.6/TkCmd/menu.htm)
//!

use super::image;
use super::widget;
use super::wish;

/// Refers to a menu widget
#[derive(Clone, Debug, PartialEq)]
pub struct TkMenu {
    pub id: String,
}

/// Creates an instance of a menu widget in given parent.
pub fn make_menu(parent: &impl widget::TkWidget) -> TkMenu {
    let id = wish::next_wid(parent.id());
    let msg = format!("menu {}", id);
    wish::tell_wish(&msg);

    TkMenu { id }
}

// -- subtypes of menu

/// Refers to a submenu
#[derive(Clone, Debug)]
pub struct TkMenuCascade {
    parent: String,
    compound: widget::Compound,
    font: Option<String>,
    image: Option<String>,
    label: Option<String>,
    menu: Option<String>,
    state: widget::State,
    underline: Option<u64>,
}

/// Refers to a check-button menu-item
#[derive(Clone, Debug)]
pub struct TkMenuCheck {
    parent: String,
    accelerator: Option<String>,
    command: Option<String>,
    command_variable: Option<String>,
    compound: widget::Compound,
    font: Option<String>,
    image: Option<String>,
    label: Option<String>,
    state: widget::State,
    underline: Option<u64>,
}

/// Refers to a command (menu-item)
#[derive(Clone, Debug)]
pub struct TkMenuCommand {
    parent: String,
    accelerator: Option<String>,
    command: Option<String>,
    compound: widget::Compound,
    font: Option<String>,
    image: Option<String>,
    label: Option<String>,
    state: widget::State,
    underline: Option<u64>,
}

/// Refers to a radio-button menu-item
#[derive(Clone, Debug)]
pub struct TkMenuRadio {
    parent: String,
    group: String,
    value: String,
    accelerator: Option<String>,
    command: Option<String>,
    command_variable: Option<String>,
    compound: widget::Compound,
    font: Option<String>,
    image: Option<String>,
    label: Option<String>,
    state: widget::State,
    underline: Option<u64>,
}

/// Refers to a menu separator
#[derive(Clone, Debug)]
pub struct TkMenuSeparator {
    parent: String,
}

// -- implementations of each menu type

impl widget::TkWidget for TkMenu {
    /// Returns the widget's id reference - used within tk
    fn id(&self) -> &str {
        &self.id
    }
}

impl TkMenu {
    /// Start to create a submenu.
    pub fn cascade(&self) -> TkMenuCascade {
        TkMenuCascade {
            parent: self.id.clone(),
            compound: widget::Compound::None,
            font: None,
            image: None,
            label: None,
            menu: None,
            state: widget::State::Normal,
            underline: None,
        }
    }

    /// Start to create a check-button menu-item.
    pub fn check_button(&self) -> TkMenuCheck {
        TkMenuCheck {
            parent: self.id.clone(),
            accelerator: None,
            command: None,
            command_variable: None,
            compound: widget::Compound::None,
            font: None,
            image: None,
            label: None,
            state: widget::State::Normal,
            underline: None,
        }
    }

    /// Start to create a command (simple menu item).
    pub fn command(&self) -> TkMenuCommand {
        TkMenuCommand {
            parent: self.id.clone(),
            accelerator: None,
            command: None,
            compound: widget::Compound::None,
            font: None,
            image: None,
            label: None,
            state: widget::State::Normal,
            underline: None,
        }
    }

    /// Start to create a radio-button menu-item.
    ///
    /// Radio buttons are arranged in groups, with each button in the group
    /// having its own value. For this reason, the group and value are
    /// required when making a radio-button menu-item.
    pub fn radio_button(&self, group: &str, value: &str) -> TkMenuRadio {
        TkMenuRadio {
            parent: self.id.clone(),
            group: String::from(group),
            value: String::from(value),
            accelerator: None,
            command: None,
            command_variable: None,
            compound: widget::Compound::None,
            font: None,
            image: None,
            label: None,
            state: widget::State::Normal,
            underline: None,
        }
    }

    /// Returns the value for a given radio-button group.
    pub fn radio_button_value_get(&self, group: &str) -> String {
        let msg = format!("puts $::mrb_group_{} ; flush stdout", group);
        wish::ask_wish(&msg)
    }

    /// Sets the value for a given radio-button group.
    pub fn radio_button_value(&self, group: &str, value: &str) {
        let msg = format!("set ::mrb_group_{} {}", group, value);
        wish::tell_wish(&msg);
    }

    /// Start to create a separator.
    pub fn separator(&self) -> TkMenuSeparator {
        TkMenuSeparator {
            parent: self.id.clone(),
        }
    }

    /// Deletes the menu-item at given index position.
    pub fn delete(&self, index: u64) {
        let msg = format!("{} delete {}", &self.id, index);
        wish::tell_wish(&msg);
    }

    /// Returns the value (as a String) for given option for
    /// menu-item at given index position.
    pub fn entry_cget(&self, index: u64, option: &str) -> String {
        let msg = format!("{} entrycfig {} {{{}}}", &self.id, index, option);
        wish::ask_wish(&msg)
    }

    /// Sets the value (as a String) for given option for
    /// menu-item at given index position.
    pub fn entry_configure(&self, index: u64, option: &str, value: &str) {
        let msg = format!(
            "{} entryconfigure {} {{{}}} {{{}}}",
            &self.id, index, option, value
        );
        wish::tell_wish(&msg);
    }

    /// Invokes any associated command for the menu-item at given index
    /// position.
    pub fn invoke(&self, index: u64) {
        let msg = format!("{} invoke {}", &self.id, index);
        wish::tell_wish(&msg);
    }

    /// Shows this menu at screen coordinates x, y.
    pub fn popup(&self, x: i64, y: i64) {
        let msg = format!("tk_popup {} {} {}", &self.id, x, y);
        wish::tell_wish(&msg);
    }
}

// Convert core options into a string representation
fn common_option_string(
    compound: &widget::Compound,
    font: &Option<String>,
    image: &Option<String>,
    label: &Option<String>,
    state: &widget::State,
    underline: &Option<u64>,
) -> String {
    let mut msg = String::new();

    msg.push_str(&format!("-compound {} ", compound));
    if let Some(font) = &font {
        msg.push_str(&format!("-font {{{}}} ", font));
    }
    if let Some(image) = &image {
        msg.push_str(&format!("-image {{{}}} ", image));
    }
    if let Some(label) = &label {
        msg.push_str(&format!("-label {{{}}} ", label));
    }
    msg.push_str(&format!("-state {} ", state));
    if let Some(underline) = &underline {
        msg.push_str(&format!("-underline {} ", underline));
    }

    msg
}

impl TkMenuCascade {
    /// Sets arrangement if menu item has both an image and a label.
    pub fn compound(&mut self, value: widget::Compound) -> &mut Self {
        self.compound = value;
        self
    }

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

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

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

    /// Sets submenu to display.
    pub fn menu(&mut self, submenu: &TkMenu) -> &mut Self {
        self.menu = Some(submenu.id.clone());
        self
    }

    /// Sets display state for menu item.
    pub fn state(&mut self, value: widget::State) -> &mut Self {
        self.state = value;
        self
    }

    /// Sets index of text label to underline.
    pub fn underline(&mut self, value: u64) -> &mut Self {
        self.underline = Some(value);
        self
    }

    // Convert options into a string representation
    fn option_string(&self) -> String {
        let mut msg = common_option_string(
            &self.compound,
            &self.font,
            &self.image,
            &self.label,
            &self.state,
            &self.underline,
        );

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

        msg
    }

    /// Adds cascade menu-item to parent with current set of options.
    pub fn add(&self) {
        let msg = format!("{} add cascade {}", &self.parent, &self.option_string());
        wish::tell_wish(&msg);
    }

    /// Inserts cascade menu-item to parent at given index with current set of options.
    pub fn insert(&self, index: u64) {
        let msg = format!(
            "{} insert cascade {} {}",
            &self.parent,
            index,
            &self.option_string()
        );
        wish::tell_wish(&msg);
    }
}

impl TkMenuCheck {
    /// Sets value of accelerator key - displayed to right of menu.
    pub fn accelerator(&mut self, key_definition: &str) -> &mut Self {
        self.accelerator = Some(String::from(key_definition));
        self
    }

    /// Sets the function to be called when the menu item is clicked.
    pub fn command(&mut self, command: impl Fn(bool) + Send + 'static) -> &mut Self {
        let id = wish::next_wid(".");
        let var = format!("::mcb{}", wish::current_id());
        wish::add_callback1_bool(&id, wish::mk_callback1_bool(command));
        self.command = Some(id);
        self.command_variable = Some(var);
        self
    }

    /// Sets arrangement if menu item has both an image and a label.
    pub fn compound(&mut self, value: widget::Compound) -> &mut Self {
        self.compound = value;
        self
    }

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

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

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

    /// Sets display state for menu item.
    pub fn state(&mut self, value: widget::State) -> &mut Self {
        self.state = value;
        self
    }

    /// Sets index of text label to underline.
    pub fn underline(&mut self, value: u64) -> &mut Self {
        self.underline = Some(value);
        self
    }

    // Convert options into a string representation
    fn option_string(&self) -> String {
        let mut msg = common_option_string(
            &self.compound,
            &self.font,
            &self.image,
            &self.label,
            &self.state,
            &self.underline,
        );

        if let Some(accelerator) = &self.accelerator {
            msg.push_str(&format!("-accelerator {{{}}} ", &accelerator));
        }
        if let Some(command) = &self.command {
            if let Some(command_variable) = &self.command_variable {
                msg.push_str(&format!(
                    "-command {{ puts cb1b-{}-${} ; flush stdout }} ",
                    &command, &command_variable
                ));
                msg.push_str(&format!("-variable {} ", &command_variable));
            }
        }

        msg
    }

    /// Adds check-button menu-item to parent with current set of options.
    pub fn add(&self) {
        let msg = format!("{} add checkbutton {}", &self.parent, &self.option_string());
        wish::tell_wish(&msg);
    }

    /// Inserts check-button menu-item to parent at given index with current set of options.
    pub fn insert(&self, index: u64) {
        let msg = format!(
            "{} insert checkbutton {} {}",
            &self.parent,
            index,
            &self.option_string()
        );
        wish::tell_wish(&msg);
    }
}

impl TkMenuCommand {
    /// Sets value of accelerator key - displayed to right of menu.
    pub fn accelerator(&mut self, key_definition: &str) -> &mut Self {
        self.accelerator = Some(String::from(key_definition));
        self
    }

    /// Sets command to invoke when menu-item clicked.
    pub fn command(&mut self, command: impl Fn() + Send + 'static) -> &mut Self {
        let id = wish::next_wid(".");
        wish::add_callback0(&id, wish::mk_callback0(command));
        self.command = Some(id);
        self
    }

    /// Sets arrangement if menu item has both an image and a label.
    pub fn compound(&mut self, value: widget::Compound) -> &mut Self {
        self.compound = value;
        self
    }

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

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

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

    /// Sets display state for menu item.
    pub fn state(&mut self, value: widget::State) -> &mut Self {
        self.state = value;
        self
    }

    /// Sets index of text label to underline.
    pub fn underline(&mut self, value: u64) -> &mut Self {
        self.underline = Some(value);
        self
    }

    // Convert options into a string representation
    fn option_string(&self) -> String {
        let mut msg = common_option_string(
            &self.compound,
            &self.font,
            &self.image,
            &self.label,
            &self.state,
            &self.underline,
        );

        if let Some(accelerator) = &self.accelerator {
            msg.push_str(&format!("-accelerator {{{}}} ", &accelerator));
        }
        if let Some(command) = &self.command {
            msg.push_str(&format!(
                "-command {{ puts clicked-{} ; flush stdout }} ",
                &command
            ));
        }

        msg
    }

    /// Adds command menu-item to parent with current set of options.
    pub fn add(&self) {
        let msg = format!("{} add command {}", &self.parent, &self.option_string());
        wish::tell_wish(&msg);
    }

    /// Inserts command menu-item to parent at given index with current set of options.
    pub fn insert(&self, index: u64) {
        let msg = format!(
            "{} insert command {} {}",
            &self.parent,
            index,
            &self.option_string()
        );
        wish::tell_wish(&msg);
    }
}

impl TkMenuRadio {
    /// Sets value of accelerator key - displayed to right of menu.
    pub fn accelerator(&mut self, key_definition: &str) -> &mut Self {
        self.accelerator = Some(String::from(key_definition));
        self
    }

    /// Sets the function to be called when the menu item is clicked.
    pub fn command(&mut self, command: impl Fn(bool) + Send + 'static) -> &mut Self {
        let id = wish::next_wid(".");
        let var = format!("::mcb{}", wish::current_id());
        wish::add_callback1_bool(&id, wish::mk_callback1_bool(command));
        self.command = Some(id);
        self.command_variable = Some(var);
        self
    }

    /// Sets arrangement if menu item has both an image and a label.
    pub fn compound(&mut self, value: widget::Compound) -> &mut Self {
        self.compound = value;
        self
    }

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

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

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

    /// Sets display state for menu item.
    pub fn state(&mut self, value: widget::State) -> &mut Self {
        self.state = value;
        self
    }

    /// Sets index of text label to underline.
    pub fn underline(&mut self, value: u64) -> &mut Self {
        self.underline = Some(value);
        self
    }

    // Convert options into a string representation
    fn option_string(&self) -> String {
        let mut msg = common_option_string(
            &self.compound,
            &self.font,
            &self.image,
            &self.label,
            &self.state,
            &self.underline,
        );

        msg.push_str(&format!(
            "-variable ::mrb_group_{} -value {{{}}} ",
            &self.group, &self.value
        ));
        if let Some(accelerator) = &self.accelerator {
            msg.push_str(&format!("-accelerator {{{}}} ", &accelerator));
        }
        if let Some(command) = &self.command {
            if let Some(command_variable) = &self.command_variable {
                msg.push_str(&format!(
                    "-command {{ puts cb1b-{}-{} ; flush stdout }} ",
                    &command, &command_variable
                ));
                msg.push_str(&format!("-variable {{{}}} ", &command_variable));
            }
        }

        msg
    }

    /// Adds radio-button menu-item to parent with current set of options.
    pub fn add(&self) {
        let msg = format!("{} add radiobutton {}", &self.parent, &self.option_string());
        wish::tell_wish(&msg);
    }

    /// Inserts radio-button menu-item to parent at given index with current set of options.
    pub fn insert(&self, index: u64) {
        let msg = format!(
            "{} insert radiobutton {} {}",
            &self.parent,
            index,
            &self.option_string()
        );
        wish::tell_wish(&msg);
    }
}

impl TkMenuSeparator {
    /// Adds separator to the parent menu.
    pub fn add(&self) {
        let msg = format!("{} add separator", &self.parent);
        wish::tell_wish(&msg);
    }

    /// Inserts separator into parent at given index.
    pub fn insert(&self, index: u64) {
        let msg = format!("{} insert sepator {}", &self.parent, index);
        wish::tell_wish(&msg);
    }
}