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
use enigo::{
    self,
    Enigo,
    KeyboardControllable,
    MouseButton,
    MouseControllable,
};
use gdk::{WindowExt, keyval_to_unicode};
use gdk::keys::Key;
use gdk::keys::constants as key;
use glib::{
    Cast,
    Continue,
    IsA,
    Object,
    StaticType,
};
use gtk::{
    self,
    Bin,
    BinExt,
    Container,
    ContainerExt,
    EditableExt,
    Entry,
    Widget,
    WidgetExt,
    Window,
};

/// Simulate a click on a widget.
///
/// ## Warning!
///
/// Please note that the click will "fail" if the window isn't on top of all other windows (this
/// is a common issue on OSX). Don't forget to bring the button's window on top by using:
///
/// ```ignore
/// window.activate_focus();
/// ```
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Button, ButtonExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let but = Button::new();
/// but.connect_clicked(|_| {
///     println!("clicked");
/// });
/// gtk_test::click(&but);
/// # }
/// ```
pub fn click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
    wait_for_draw(widget, || {
        let allocation = widget.get_allocation();
        mouse_move(widget, allocation.width / 2, allocation.height / 2);
        let mut enigo = Enigo::new();
        enigo.mouse_click(MouseButton::Left);
        run_loop();
    });
}

/// Simulate a double-click on a widget.
///
/// ## Warning!
///
/// Please note that the double-click will "fail" if the window isn't on top of all other windows
/// (this is a common issue on OSX). Don't forget to bring the button's window on top by using:
///
/// ```ignore
/// window.activate_focus();
/// ```
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{FileChooserAction, FileChooserWidget, FileChooserExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let fcw = FileChooserWidget::new(FileChooserAction::Open);
/// fcw.connect_file_activated(|_| {
///     println!("double clicked");
/// });
/// gtk_test::double_click(&fcw);
/// # }
/// ```
pub fn double_click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
    click(widget);
    click(widget);
}

/// Move the mouse relative to the widget position.
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::Button;
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let but = Button::new();
/// gtk_test::mouse_move(&but, 0, 0); // the mouse will be on the top-left corner of the button
/// # }
/// ```
pub fn mouse_move<W: IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, x: i32, y: i32) {
    wait_for_draw(widget, || {
        let toplevel_window = widget.get_toplevel().and_then(|toplevel| toplevel.get_window());
        if let (Some(toplevel), Some(toplevel_window)) = (widget.get_toplevel(), toplevel_window) {
            let (_, window_x, window_y) = toplevel_window.get_origin();
            if let Some((x, y)) = widget.translate_coordinates(&toplevel, x, y) {
                let x = window_x + x;
                let y = window_y + y;
                let mut enigo = Enigo::new();
                enigo.mouse_move_to(x, y);
                run_loop();
            }
        }
    });
}

/// Send a mouse press event to the given widget.
///
/// ## Warning!
///
/// Please note that the mouse-press event will "fail" if the window isn't on top of all other
/// windows (this is a common issue on OSX). Don't forget to bring the button's window on top
/// by using:
///
/// ```ignore
/// window.activate_focus();
/// ```
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Entry, EntryExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let entry = Entry::new();
/// entry.connect_icon_press(|_, _, _| {
///     println!("pressed");
/// });
/// gtk_test::mouse_press(&entry);
/// # }
/// ```
pub fn mouse_press<W: IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
    wait_for_draw(widget, || {
        let allocation = widget.get_allocation();
        mouse_move(widget, allocation.width / 2, allocation.height / 2);
        let mut enigo = Enigo::new();
        enigo.mouse_down(MouseButton::Left);
        run_loop();
    });
}

/// Send a mouse release event to the given widget.
///
/// ## Warning!
///
/// Please note that the mouse-release event will "fail" if the window isn't on top of all other
/// windows (this is a common issue on OSX). Don't forget to bring the button's window on top
/// by using:
///
/// ```ignore
/// window.activate_focus();
/// ```
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Entry, EntryExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let entry = Entry::new();
/// entry.connect_icon_release(|_, _, _| {
///     println!("released");
/// });
/// gtk_test::mouse_release(&entry);
/// # }
/// ```
pub fn mouse_release<W: IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
    wait_for_draw(widget, || {
        let allocation = widget.get_allocation();
        mouse_move(widget, allocation.width / 2, allocation.height / 2);
        let mut enigo = Enigo::new();
        enigo.mouse_up(MouseButton::Left);
        run_loop();
    });
}

/// Send a key event to the given widget.
///
/// ## Warning!
///
/// Please note that the enter-key event will "fail" if the window isn't on top of all other
/// windows (this is a common issue on OSX). Don't forget to bring the button's window on top
/// by using:
///
/// ```ignore
/// window.activate_focus();
/// ```
///
/// Example:
///
/// ```
/// extern crate gdk;
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Entry, EntryExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let entry = Entry::new();
/// entry.connect_preedit_changed(|_, _| {
///     println!("key entered");
/// });
/// gtk_test::enter_key(&entry, gdk::keys::constants::Agrave);
/// # }
/// ```
pub fn enter_key<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
    wait_for_draw(widget, || {
        focus(widget);
        let mut enigo = Enigo::new();
        enigo.key_click(gdk_key_to_enigo_key(key));
        run_loop();
    });
}

/// Send keys event to the given widget.
///
/// ## Warning!
///
/// Please note that the enter-key event will "fail" if the window isn't on top of all other
/// windows (this is a common issue on OSX). Don't forget to bring the button's window on top
/// by using:
///
/// ```ignore
/// window.activate_focus();
/// ```
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Entry, EntryExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let entry = Entry::new();
/// entry.connect_preedit_changed(|_, _| {
///     println!("key entered");
/// });
/// gtk_test::enter_keys(&entry, "A lot of keys!");
/// # }
/// ```
pub fn enter_keys<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, text: &str) {
    wait_for_draw(widget, || {
        focus(widget);
        let mut enigo = Enigo::new();
        for char in text.chars() {
            enigo.key_sequence(&char.to_string());
            run_loop();
        }
    });
}

/// Returns the child element which has the given name.
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{prelude::BuildableExtManual, Button, ContainerExt, WidgetExt, Window, WindowType};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let but = Button::new();
/// let w = Window::new(WindowType::Toplevel);
///
/// but.set_widget_name("Button");
/// w.add(&but);
///
/// gtk_test::find_child_by_name::<Button, Window>(&w, "Button").expect("failed to find child");
/// // Or even better:
/// let but: Button = gtk_test::find_child_by_name(&w, "Button").expect("failed to find child");
/// # }
/// ```
pub fn find_child_by_name<C: IsA<Widget>, W: Clone + IsA<Object> + IsA<Widget>>(parent: &W, name: &str) -> Option<C> {
    find_widget_by_name(parent, name)
        .and_then(|widget| widget.downcast().ok())
}

/// Returns the child widget which has the given name.
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Button, ContainerExt, WidgetExt, Window, WindowType};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let but = Button::new();
/// let w = Window::new(WindowType::Toplevel);
///
/// but.set_widget_name("Button");
/// w.add(&but);
///
/// gtk_test::find_widget_by_name(&w, "Button").unwrap();
/// # }
/// ```
pub fn find_widget_by_name<W: Clone + IsA<Object> + IsA<Widget>>(parent: &W, name: &str) -> Option<Widget> {
    if let Ok(container) = parent.clone().dynamic_cast::<Container>() {
        for child in container.get_children() {
            if child.get_widget_name() == name {
                return Some(child);
            }
            if let Some(widget) = find_widget_by_name(&child, name) {
                return Some(widget);
            }
        }
    }
    else if let Ok(bin) = parent.clone().dynamic_cast::<Bin>() {
        if let Some(child) = bin.get_child() {
            if child.get_widget_name() == name {
                return Some(child);
            }
            if let Some(widget) = find_widget_by_name(&child, name) {
                return Some(widget);
            }
        }
    }
    None
}

/// Focus on the given widget.
///
/// Example:
///
/// ```
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Button, Inhibit, WidgetExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let but = Button::new();
///
/// but.connect_focus(|_, _| {
///     println!("focused!");
///     Inhibit(false)
/// });
/// gtk_test::focus(&but);
/// # }
/// ```
pub fn focus<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
    wait_for_draw(widget, || {
        if !widget.has_focus() {
            widget.grab_focus();
            if let Ok(entry) = widget.clone().dynamic_cast::<Entry>() {
                // Hack to make it work on Travis.
                // Should use grab_focus_without_selecting() instead.
                entry.set_position(-1);
            }
        }
    });
}

/// Send a key press event to the given widget.
///
/// ## Warning!
///
/// Please note that the key-press event will "fail" if the window isn't on top of all other
/// windows (this is a common issue on OSX). Don't forget to bring the button's window on top
/// by using:
///
/// ```ignore
/// window.activate_focus();
/// ```
///
/// Example:
///
/// ```
/// extern crate gdk;
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Entry, Inhibit, WidgetExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let entry = Entry::new();
/// entry.connect_key_press_event(|_, _| {
///     println!("key pressed");
///     Inhibit(false)
/// });
/// gtk_test::key_press(&entry, gdk::keys::constants::Agrave);
/// # }
/// ```
pub fn key_press<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
    wait_for_draw(widget, || {
        focus(widget);
        let mut enigo = Enigo::new();
        enigo.key_down(gdk_key_to_enigo_key(key));
        run_loop();
    });
}

/// Send a key release event to the given widget.
///
/// ## Warning!
///
/// Please note that the key-release event will "fail" if the window isn't on top of all other
/// windows (this is a common issue on OSX). Don't forget to bring the button's window on top
/// by using:
///
/// ```ignore
/// window.activate_focus();
/// ```
///
/// Example:
///
/// ```
/// extern crate gdk;
/// extern crate gtk;
/// #[macro_use]
/// extern crate gtk_test;
///
/// use gtk::{Entry, Inhibit, WidgetExt};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let entry = Entry::new();
/// entry.connect_key_release_event(|_, _| {
///     println!("key released");
///     Inhibit(false)
/// });
/// gtk_test::key_release(&entry, gdk::keys::constants::Agrave);
/// # }
/// ```
pub fn key_release<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
    wait_for_draw(widget, || {
        focus(widget);
        let mut enigo = Enigo::new();
        enigo.key_up(gdk_key_to_enigo_key(key));
        run_loop();
    });
}

/// Wait for events the specified amount the milliseconds.
///
/// Very convenient when you need GTK to update the UI to let it process some events.
///
/// Example:
///
/// ```
/// extern crate gtk;
/// extern crate gtk_test;
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// gtk_test::wait(1000); // wait for a second
/// # }
/// ```
pub fn wait(ms: u32) {
    gtk::timeout_add(ms, || {
        gtk::main_quit();
        Continue(false)
    });
    gtk::main();
}

/// Process all pending events and then return.
///
/// This function is called in all functions related to events handling (like `key_release` for
/// example).
///
/// Example:
///
/// ```
/// extern crate gtk;
/// extern crate gtk_test;
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// gtk_test::run_loop();
/// # }
/// ```
pub fn run_loop() {
    while gtk::events_pending() {
        gtk::main_iteration();
    }
}

/// Wait until the given condition returns `true`.
///
/// Example:
///
/// ```
/// extern crate gtk;
/// extern crate gtk_test;
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let mut x = 0;
///
/// gtk_test::wait_until_done(move || {
///     x += 1;
///     x > 10
/// });
/// # }
/// ```
pub fn wait_until_done<F: FnMut() -> bool>(mut f: F) {
    while !f() {
        run_loop();
    }
}

/// Wait for a widget to be drawn.
///
/// Example:
///
/// ```
/// extern crate gtk;
/// extern crate gtk_test;
///
/// use gtk::{WidgetExt, Window, WindowType};
///
/// # fn main() {
/// gtk::init().expect("GTK init failed");
/// let mut w = Window::new(WindowType::Toplevel);
///
/// w.show_all();
/// gtk_test::wait_for_draw(&w, || {
///     println!("drawn!");
/// });
/// # }
/// ```
pub fn wait_for_draw<W, F: FnOnce()>(widget: &W, callback: F)
where W: IsA<Object> + IsA<Widget> + WidgetExt {
    if widget.get_ancestor(Window::static_type()).is_none() {
        return;
    }
    gtk::test_widget_wait_for_draw(widget);
    callback();
}

fn gdk_key_to_enigo_key(key: Key) -> enigo::Key {
    use enigo::Key::*;
    match key {
        key::Return => Return,
        key::Tab => Tab,
        key::space => Space,
        key::BackSpace => Backspace,
        key::Escape => Escape,
        key::Super_L | key::Super_R => Meta,
        key::Control_L | key::Control_R => Control,
        key::Shift_L | key::Shift_R => Shift,
        key::Shift_Lock => CapsLock,
        key::Alt_L | key::Alt_R => Alt,
        key::Option => Option,
        key::Home => Home,
        key::Page_Down => PageDown,
        key::Page_Up => PageUp,
        key::leftarrow => LeftArrow,
        key::rightarrow => RightArrow,
        key::downarrow => DownArrow,
        key::uparrow => UpArrow,
        key::F1 => F1,
        key::F2 => F2,
        key::F3 => F3,
        key::F4 => F4,
        key::F5 => F5,
        key::F6 => F6,
        key::F7 => F7,
        key::F8 => F8,
        key::F9 => F9,
        key::F10 => F10,
        key::F11 => F11,
        key::F12 => F12,
        _ => {
            if let Some(char) = keyval_to_unicode(*key) {
                Layout(char)
            }
            else {
                Raw(*key as u16)
            }
        },
    }
}