rstk 0.3.0

A Rust binding for the Tk graphics toolkit. Tk is suitable for creating simple GUI programs or interactive graphical displays. This library supports a large portion of the Tk API, in a generally rust-like style.
Documentation
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
//! Core functions and data structures for interacting with the wish process.
//!
//! The basic structure of a program using wish is as follows:
//!
//! ```ignore
//! fn main() {
//!   let root = rstk::start_wish().unwrap();
//!
//!   // -- add code here to create program
//!
//!   rstk::mainloop();
//! }
//! ```
//!
//! The call to `start_wish` starts the "wish" program and sets up some
//! internal structure to store information about your program's interaction
//! with wish. The return value is a `Result`, so must be unwrapped (or 
//! otherwise handled) to obtain the top-level window.
//!
//! If you are using a different program to "wish", e.g. a tclkit, then
//! call instead:
//!
//! ```ignore
//!   let root = rstk::start_with("tclkit").unwrap();
//! ```
//!
//! All construction of the GUI must be done after starting a wish process.
//!
//! (For debugging purposes, [trace_with] additionally displays all 
//! messages to/from the wish program on stdout.)
//!
//! Tk is event-driven, so the code sets up the content and design
//! of various widgets and associates commands to particular events: events
//! can be button-clicks or the movement of a mouse onto a canvas.
//!
//! Once the GUI is created, then the [mainloop] must be started, which will
//! process and react to events: the call to `mainloop` is usually the last
//! statement in the program.
//!
//! The program will usually exit when the top-level window is closed. However,
//! that can be over-ridden or, to exit in another way, use [end_wish].
//!
//! ## Low-level API
//!
//! The modules in this crate aim to provide a rust-friendly, type-checked set 
//! of structs and methods for using the Tk library.
//!
//! However, there are many features in Tk and not all of them are likely to be
//! wrapped. If there is a feature missing they may be used by directly calling 
//! Tk commands through the low-level API.
//!
//! 1. every widget has an `id` field, which gives the Tk identifier.
//! 2. [tell_wish] sends a given string directly to wish
//! 3. [ask_wish] sends a given string directly to wish and
//!    returns, as a [String], the response.
//!
//! For example, label's
//! [takefocus](https://www.tcl-lang.org/man/tcl8.6/TkCmd/ttk_widget.htm#M-takefocus)
//! flag is not wrapped. You can nevertheless set its value using:
//!
//! ```ignore
//! let label = rstk::make_label(&root);
//!
//! rstk::tell_wish(&format!("{} configure -takefocus 0", &label.id));
//! ```
//!
//! Also useful are:
//!
//! * [cget](widget::TkWidget::cget) - queries any option and returns its current value
//! * [configure](widget::TkWidget::configure) - used to set any option to a value
//! * [winfo](widget::TkWidget::winfo) - returns window-related information
//!
//! ## Extensions
//!
//! Extensions can be created with the help of [next_wid],
//! which returns a new, unique ID in Tk format. Writing an extension requires:
//!
//! 1. importing the tcl/tk library (using `tell_wish`)
//! 2. creating an instance of the underlying Tk widget using a unique id
//! 3. retaining that id in a struct, for later reference
//! 4. wrapping the widget's functions as methods, calling out to Tk with
//!    the stored id as a reference.
//!

use std::collections::HashMap;
use std::io::{Read, Write};
use std::process;
use std::sync::mpsc;
use std::sync::{Mutex, OnceLock};
use std::thread;

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

use once_cell::sync::Lazy;

/// Reports an error in interacting with the Tk program.
#[derive(Debug)]
pub struct TkError {
    message: String,
}

static TRACE_WISH: OnceLock<bool> = OnceLock::new();
fn tracing() -> bool {
    *TRACE_WISH.get().unwrap_or(&false)
}

static mut WISH: OnceLock<process::Child> = OnceLock::new();
static mut OUTPUT: OnceLock<process::ChildStdout> = OnceLock::new();
static mut SENDER: OnceLock<mpsc::Sender<String>> = OnceLock::new();

// Kills the wish process - should be called to exit
pub(super) fn kill_wish() {
    unsafe {
        WISH.get_mut()
            .unwrap()
            .kill()
            .expect("Wish was unexpectedly already finished");
    }
}

/// Sends a message (tcl command) to wish.
///
/// Use with caution: the message must be valid tcl.
///
pub fn tell_wish(msg: &str) {
    if tracing() {
        println!("wish: {}", msg);
    }
    unsafe {
        SENDER.get_mut().unwrap().send(String::from(msg)).unwrap();
        SENDER.get_mut().unwrap().send(String::from("\n")).unwrap();
    }
}

/// Sends a message (tcl command) to wish and expects a result.
/// Returns a result as a string
///
/// Use with caution: the message must be valid tcl.
///
pub fn ask_wish(msg: &str) -> String {
    tell_wish(msg);
    
    unsafe {
        let mut input = [32; 10000]; // TODO - long inputs can get split?
        if OUTPUT.get_mut().unwrap().read(&mut input).is_ok() {
            if let Ok(input) = String::from_utf8(input.to_vec()) {
                if tracing() {
                    println!("---: {:?}", &input.trim());
                }
                return input.trim().to_string();
            }
        }
    }

    panic!("Eval-wish failed to get a result");
}

// -- Counter for making new ids

static NEXT_ID: Lazy<Mutex<i64>> = Lazy::new(|| Mutex::new(0));

/// Returns a new id string which can be used to name a new
/// widget instance. The new id will be in reference to the
/// parent, as is usual in Tk.
///
/// This is only for use when writing an extension library.
///
pub fn next_wid(parent: &str) -> String {
    let mut nid = NEXT_ID.lock().unwrap();
    *nid += 1;
    if parent == "." {
        format!(".r{}", nid)
    } else {
        format!("{}.r{}", parent, nid)
    }
}

/// Returns a new variable name. This is used in the chart
/// module to reference the chart instances in Tk.
///
/// This is only for use when writing an extension library.
///
pub fn next_var() -> String {
    let mut nid = NEXT_ID.lock().unwrap();
    *nid += 1;
    format!("::var{}", nid)
}

pub(super) fn current_id() -> i64 {
    let nid = NEXT_ID.lock().unwrap();
    *nid
}

// -- Store for callback functions, such as on button clicks

type Callback0 = Box<(dyn Fn() + Send + 'static)>;
pub(super) fn mk_callback0<F>(f: F) -> Callback0
where
    F: Fn() + Send + 'static,
{
    Box::new(f) as Callback0
}

static CALLBACKS0: Lazy<Mutex<HashMap<String, Callback0>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

pub(super) fn add_callback0(wid: &str, callback: Callback0) {
    CALLBACKS0
        .lock()
        .unwrap()
        .insert(String::from(wid), callback);
}

fn get_callback0(wid: &str) -> Option<Callback0> {
    if let Some((_, command)) = CALLBACKS0.lock().unwrap().remove_entry(wid) {
        Some(command)
    } else {
        None
    }
}

fn eval_callback0(wid: &str) {
    if let Some(command) = get_callback0(wid) {
        command();
        if !wid.contains("after") && // after commands apply once only
            !CALLBACKS0.lock().unwrap().contains_key(wid) // do not overwrite if a replacement command added
            {
            add_callback0(wid, command);
        }
    } // TODO - error?
}

type Callback1Bool = Box<(dyn Fn(bool) + Send + 'static)>;
pub(super) fn mk_callback1_bool<F>(f: F) -> Callback1Bool
where
    F: Fn(bool) + Send + 'static,
{
    Box::new(f) as Callback1Bool
}

static CALLBACKS1BOOL: Lazy<Mutex<HashMap<String, Callback1Bool>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

pub(super) fn add_callback1_bool(wid: &str, callback: Callback1Bool) {
    CALLBACKS1BOOL
        .lock()
        .unwrap()
        .insert(String::from(wid), callback);
}

fn get_callback1_bool(wid: &str) -> Option<Callback1Bool> {
    if let Some((_, command)) = CALLBACKS1BOOL.lock().unwrap().remove_entry(wid) {
        Some(command)
    } else {
        None
    }
}

fn eval_callback1_bool(wid: &str, value: bool) {
    if let Some(command) = get_callback1_bool(wid) {
        command(value);
        if !CALLBACKS1BOOL.lock().unwrap().contains_key(wid) {
            add_callback1_bool(wid, command);
        }
    } // TODO - error?
}

type Callback1Event = Box<(dyn Fn(widget::TkEvent) + Send + 'static)>;
pub(super) fn mk_callback1_event<F>(f: F) -> Callback1Event
where
    F: Fn(widget::TkEvent) + Send + 'static,
{
    Box::new(f) as Callback1Event
}

// for bound events, key is widgetid/all + pattern, as multiple events can be
// bound to same entity
static CALLBACKS1EVENT: Lazy<Mutex<HashMap<String, Callback1Event>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

pub(super) fn add_callback1_event(wid: &str, callback: Callback1Event) {
    CALLBACKS1EVENT
        .lock()
        .unwrap()
        .insert(String::from(wid), callback);
}

fn get_callback1_event(wid: &str) -> Option<Callback1Event> {
    if let Some((_, command)) = CALLBACKS1EVENT.lock().unwrap().remove_entry(wid) {
        Some(command)
    } else {
        None
    }
}

fn eval_callback1_event(wid: &str, value: widget::TkEvent) {
    if let Some(command) = get_callback1_event(wid) {
        command(value);
        if !CALLBACKS1EVENT.lock().unwrap().contains_key(wid) {
            add_callback1_event(wid, command);
        }
    } // TODO - error?
}

type Callback1Float = Box<(dyn Fn(f64) + Send + 'static)>;
pub(super) fn mk_callback1_float<F>(f: F) -> Callback1Float
where
    F: Fn(f64) + Send + 'static,
{
    Box::new(f) as Callback1Float
}

static CALLBACKS1FLOAT: Lazy<Mutex<HashMap<String, Callback1Float>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

pub(super) fn add_callback1_float(wid: &str, callback: Callback1Float) {
    CALLBACKS1FLOAT
        .lock()
        .unwrap()
        .insert(String::from(wid), callback);
}

fn get_callback1_float(wid: &str) -> Option<Callback1Float> {
    if let Some((_, command)) = CALLBACKS1FLOAT.lock().unwrap().remove_entry(wid) {
        Some(command)
    } else {
        None
    }
}

fn eval_callback1_float(wid: &str, value: f64) {
    if let Some(command) = get_callback1_float(wid) {
        command(value);
        if !CALLBACKS1FLOAT.lock().unwrap().contains_key(wid) {
            add_callback1_float(wid, command);
        }
    } // TODO - error?
}

type Callback1Font = Box<(dyn Fn(font::TkFont) + Send + 'static)>;
pub(super) fn mk_callback1_font<F>(f: F) -> Callback1Font
where
    F: Fn(font::TkFont) + Send + 'static,
{
    Box::new(f) as Callback1Font
}

static CALLBACKS1FONT: Lazy<Mutex<HashMap<String, Callback1Font>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

pub(super) fn add_callback1_font(wid: &str, callback: Callback1Font) {
    CALLBACKS1FONT
        .lock()
        .unwrap()
        .insert(String::from(wid), callback);
}

fn get_callback1_font(wid: &str) -> Option<Callback1Font> {
    if let Some((_, command)) = CALLBACKS1FONT.lock().unwrap().remove_entry(wid) {
        Some(command)
    } else {
        None
    }
}

fn eval_callback1_font(wid: &str, value: font::TkFont) {
    if let Some(command) = get_callback1_font(wid) {
        command(value);
        if !CALLBACKS1FONT.lock().unwrap().contains_key(wid) {
            add_callback1_font(wid, command);
        }
    } // TODO - error?
}

/// Loops while GUI events occur
pub fn mainloop() {
    unsafe {
        loop {
            let mut input = [32; 10000];
            if OUTPUT.get_mut().unwrap().read(&mut input).is_ok() {
                if let Ok(input) = String::from_utf8(input.to_vec()) {
                    if tracing() {
                        println!("Callback: {:?}", &input.trim());
                    }

                    // here - do a match or similar on what was read from wish
                    if input.starts_with("clicked") {
                        // -- callbacks
                        if let Some(n) = input.find(&['\n', '\r']) {
                            let widget = &input[8..n];
                            eval_callback0(widget);
                        }
                    } else if input.starts_with("cb1b") {
                        // -- callback 1 with bool
                        let parts: Vec<&str> = input.split('-').collect();
                        let widget = parts[1].trim();
                        let value = parts[2].trim();
                        eval_callback1_bool(widget, value == "1");
                    } else if input.starts_with("cb1e") {
                        // -- callback 1 with event
                        let parts: Vec<&str> = input.split(':').collect();
                        let widget_pattern = parts[1].trim();
                        let x = parts[2].parse::<i64>().unwrap_or(0);
                        let y = parts[3].parse::<i64>().unwrap_or(0);
                        let root_x = parts[4].parse::<i64>().unwrap_or(0);
                        let root_y = parts[5].parse::<i64>().unwrap_or(0);
                        let height = parts[6].parse::<i64>().unwrap_or(0);
                        let width = parts[7].parse::<i64>().unwrap_or(0);
                        let key_code = parts[8].parse::<u64>().unwrap_or(0);
                        let key_symbol = parts[9].parse::<String>().unwrap_or_default();
                        let mouse_button = parts[10].parse::<u64>().unwrap_or(0);
                        let event = widget::TkEvent {
                            x,
                            y,
                            root_x,
                            root_y,
                            height,
                            width,
                            key_code,
                            key_symbol,
                            mouse_button,
                        };
                        eval_callback1_event(widget_pattern, event);
                    } else if input.starts_with("cb1f") {
                        // -- callback 1 with float
                        let parts: Vec<&str> = input.split('-').collect();
                        let widget = parts[1].trim();
                        let value = parts[2].trim().parse::<f64>().unwrap_or(0.0);
                        eval_callback1_float(widget, value);
                    } else if let Some(font) = input.strip_prefix("font") {
                        // -- callback 1 with font
                        let font = font.trim();
                        if let Ok(font) = font.parse::<font::TkFont>() {
                            eval_callback1_font("font", font);
                        }
                    } else if input.starts_with("exit") {
                        // -- wish has exited
                        kill_wish();
                        return; // exit loop and program
                    }
                }
            }
        }
    }
}

/// Creates a connection with the "wish" program.
pub fn start_wish() -> Result<toplevel::TkTopLevel, TkError> {
    start_with("wish")
}

/// Creates a connection with the given wish/tclkit program.
pub fn start_with(wish: &str) -> Result<toplevel::TkTopLevel, TkError> {
    if let Ok(_) = TRACE_WISH.set(false) {
        start_tk_connection(wish)
    } else {
        return Err(TkError { message: String::from("Failed to set trace option") })
    }
}

/// Creates a connection with the given wish/tclkit program with 
/// debugging output enabled (wish interactions are reported to stdout).
pub fn trace_with(wish: &str) -> Result<toplevel::TkTopLevel, TkError> {
    if let Ok(_) = TRACE_WISH.set(true) {
        start_tk_connection(wish)
    } else {
        return Err(TkError { message: String::from("Failed to set trace option") })
    }
}

/// Creates a connection with the given wish/tclkit program.
fn start_tk_connection(wish: &str)-> Result<toplevel::TkTopLevel, TkError> {

    let err_msg = format!("Do not start {} twice", wish);

    unsafe {
        if let Ok(wish_process) = process::Command::new(wish)
            .stdin(process::Stdio::piped())
                .stdout(process::Stdio::piped())
                .spawn()
                {
                    if WISH.set(wish_process).is_err() {
                        return Err(TkError { message: err_msg });
                    }
                } else {
                    return Err(TkError {
                        message: format!("Failed to start {} process", wish),
                    });
                };

        let mut input = WISH.get_mut().unwrap().stdin.take().unwrap();
        if OUTPUT
            .set(WISH.get_mut().unwrap().stdout.take().unwrap())
                .is_err()
                {
                    return Err(TkError { message: err_msg });
                }

        // -- initial setup of Tcl/Tk environment

        // load the plotchart package - TODO: give some indication if this fails
        input.write_all(b"catch {{ package require Plotchart }}\n").unwrap();

        // set close button to output 'exit' message, so rust can close connection
        input
            .write_all(b"wm protocol . WM_DELETE_WINDOW { puts stdout {exit} ; flush stdout } \n")
            .unwrap();
        // remove the 'tearoff' menu option
        input.write_all(b"option add *tearOff 0\n").unwrap();
        // tcl function to help working with font chooser
        input
            .write_all(
                b"proc font_choice {w font args} {
            set res {font }
            append res [font actual $font]
                puts $res
                flush stdout
        }\n",
        )
            .unwrap();
        // tcl function to help working with scale widget
        input
            .write_all(
                b"proc scale_value {w value args} {
            puts cb1f-$w-$value
                flush stdout
        }\n",
        )
            .unwrap();

        let (sender, receiver) = mpsc::channel();
        SENDER.set(sender).expect(&err_msg);

        // create thread to receive strings to send on to wish
        thread::spawn(move || loop {
            let msg: Result<String, mpsc::RecvError> = receiver.recv();
            if let Ok(msg) = msg {
                input.write_all(msg.as_bytes()).unwrap();
                input.write_all(b"\n").unwrap();
            }
        });
    }

    Ok(toplevel::TkTopLevel {
        id: String::from("."),
    })
}

/// Used to cleanly end the wish process and current rust program.
pub fn end_wish() {
    kill_wish();
    process::exit(0);
}

// Splits tcl string where items can be single words or grouped in {..}
pub(super) fn split_items(text: &str) -> Vec<String> {
    let mut result: Vec<String> = vec![];

    let mut remaining = text.trim();
    while !remaining.is_empty() {
        if let Some(start) = remaining.find('{') {
            // -- add any words before first {
            for word in remaining[..start].split_whitespace() {
                result.push(String::from(word));
            }

            if let Some(end) = remaining.find('}') {
                result.push(String::from(&remaining[start + 1..end]));
                remaining = remaining[end + 1..].trim();
            } else {
                // TODO keep what we have
                break; // panic!("Incorrectly formed font family string");
            }
        } else {
            // no { }, so just split all the words and end
            for word in remaining.split_whitespace() {
                result.push(String::from(word));
            }
            break;
        }
        }

        result
    }

#[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn split_items_1() {
            let result = split_items("");
            assert_eq!(0, result.len());
        }

        #[test]
        fn split_items_2() {
            let result = split_items("abc");
            assert_eq!(1, result.len());
            assert_eq!("abc", result[0]);
        }

        #[test]
        fn split_items_3() {
            let result = split_items("  abc  def  ");
            assert_eq!(2, result.len());
            assert_eq!("abc", result[0]);
            assert_eq!("def", result[1]);
        }

        #[test]
        fn split_items_4() {
            let result = split_items("{abc def}");
            assert_eq!(1, result.len());
            assert_eq!("abc def", result[0]);
        }

        #[test]
        fn split_items_5() {
            let result = split_items("{abc def} xy_z {another}");
            assert_eq!(3, result.len());
            assert_eq!("abc def", result[0]);
            assert_eq!("xy_z", result[1]);
            assert_eq!("another", result[2]);
        }
    }