forked from linebender/druid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindow.rs
1528 lines (1355 loc) · 55.6 KB
/
window.rs
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! GTK window creation and management.
use std::cell::{Cell, RefCell};
use std::convert::TryInto;
use std::ffi::c_void;
use std::os::raw::{c_int, c_uint};
use std::panic::Location;
use std::ptr;
use std::slice;
use std::sync::{Arc, Mutex, Weak};
use std::time::Instant;
use gtk::gdk_pixbuf::Colorspace::Rgb;
use gtk::gdk_pixbuf::Pixbuf;
use gtk::glib::source::Continue;
use gtk::glib::translate::FromGlib;
use gtk::prelude::*;
use gtk::traits::SettingsExt;
use gtk::{AccelGroup, ApplicationWindow, DrawingArea};
use gdk_sys::GdkKeymapKey;
use anyhow::anyhow;
use cairo::Surface;
use gtk::gdk::{
EventKey, EventMask, EventType, ModifierType, ScrollDirection, Window, WindowTypeHint,
};
use instant::Duration;
use tracing::{error, warn};
#[cfg(feature = "raw-win-handle")]
use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, XcbWindowHandle};
use crate::kurbo::{Insets, Point, Rect, Size, Vec2};
use crate::piet::{Piet, PietText, RenderContext};
use crate::common_util::{ClickCounter, IdleCallback};
use crate::dialog::{FileDialogOptions, FileDialogType, FileInfo};
use crate::error::Error as ShellError;
use crate::keyboard::{KbKey, KeyEvent, KeyState, Modifiers};
use crate::mouse::{Cursor, CursorDesc, MouseButton, MouseButtons, MouseEvent};
use crate::piet::ImageFormat;
use crate::region::Region;
use crate::scale::{Scalable, Scale, ScaledArea};
use crate::text::{simulate_input, Event};
use crate::window::{
self, FileDialogToken, IdleToken, TextFieldToken, TimerToken, WinHandler, WindowLevel,
};
use super::application::Application;
use super::dialog;
use super::keycodes;
use super::menu::Menu;
use super::util;
/// The backend target DPI.
///
/// GTK considers 96 the default value which represents a 1.0 scale factor.
const SCALE_TARGET_DPI: f64 = 96.0;
/// Taken from <https://gtk-rs.org/docs-src/tutorial/closures>
/// It is used to reduce the boilerplate of setting up gtk callbacks
/// Example:
/// ```ignore
/// button.connect_clicked(clone!(handle => move |_| { ... }))
/// ```
/// is equivalent to:
/// ```ignore
/// {
/// let handle = handle.clone();
/// button.connect_clicked(move |_| { ... })
/// }
/// ```
macro_rules! clone {
(@param _) => ( _ );
(@param $x:ident) => ( $x );
($($n:ident),+ => move || $body:expr) => (
{
$( let $n = $n.clone(); )+
move || $body
}
);
($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
{
$( let $n = $n.clone(); )+
move |$(clone!(@param $p),)+| $body
}
);
}
#[derive(Clone, Default, Debug)]
pub struct WindowHandle {
pub(crate) state: Weak<WindowState>,
// Ensure that we don't implement Send, because it isn't actually safe to send the WindowState.
marker: std::marker::PhantomData<*const ()>,
}
impl PartialEq for WindowHandle {
fn eq(&self, other: &Self) -> bool {
match (self.state.upgrade(), other.state.upgrade()) {
(None, None) => true,
(Some(s), Some(o)) => std::sync::Arc::ptr_eq(&s, &o),
(_, _) => false,
}
}
}
impl Eq for WindowHandle {}
#[cfg(feature = "raw-win-handle")]
unsafe impl HasRawWindowHandle for WindowHandle {
fn raw_window_handle(&self) -> RawWindowHandle {
error!("HasRawWindowHandle trait not implemented for gtk.");
// GTK is not a platform, and there's no empty generic handle. Pick XCB randomly as fallback.
RawWindowHandle::Xcb(XcbWindowHandle::empty())
}
}
/// Operations that we defer in order to avoid re-entrancy. See the documentation in the windows
/// backend for more details.
enum DeferredOp {
SaveAs(FileDialogOptions, FileDialogToken),
Open(FileDialogOptions, FileDialogToken),
ContextMenu(Menu, WindowHandle),
}
/// Builder abstraction for creating new windows
pub(crate) struct WindowBuilder {
app: Application,
handler: Option<Box<dyn WinHandler>>,
title: String,
menu: Option<Menu>,
position: Option<Point>,
level: Option<WindowLevel>,
state: Option<window::WindowState>,
size: Size,
min_size: Option<Size>,
resizable: bool,
show_titlebar: bool,
transparent: bool,
}
#[derive(Clone)]
pub struct IdleHandle {
idle_queue: Arc<Mutex<Vec<IdleKind>>>,
state: Weak<WindowState>,
}
/// This represents different Idle Callback Mechanism
enum IdleKind {
Callback(Box<dyn IdleCallback>),
Token(IdleToken),
}
// We use RefCells for interior mutability, but we try to structure things so that double-borrows
// are impossible. See the documentation on crate::backend::x11::window::Window for more details,
// since the idea there is basically the same.
pub(crate) struct WindowState {
window: ApplicationWindow,
scale: Cell<Scale>,
area: Cell<ScaledArea>,
is_transparent: Cell<bool>,
handle_titlebar: Cell<bool>,
/// Used to determine whether to honor close requests from the system: we inhibit them unless
/// this is true, and this gets set to true when our client requests a close.
closing: Cell<bool>,
drawing_area: DrawingArea,
// A cairo surface for us to render to; we copy this to the drawing_area whenever necessary.
// This extra buffer is necessitated by DrawingArea's painting model: when our paint callback
// is called, we are given a cairo context that's already clipped to the invalid region. This
// doesn't match up with our painting model, because we need to call `prepare_paint` before we
// know what the invalid region is.
//
// The way we work around this is by always invalidating the entire DrawingArea whenever we
// need repainting; this ensures that GTK gives us an unclipped cairo context. Meanwhile, we
// keep track of the actual invalid region. We use that region to render onto `surface`, which
// we then copy onto `drawing_area`.
surface: RefCell<Option<Surface>>,
// The size of `surface` in pixels. This could be bigger than `drawing_area`.
surface_size: Cell<(i32, i32)>,
// The invalid region, in display points.
invalid: RefCell<Region>,
pub(crate) handler: RefCell<Box<dyn WinHandler>>,
idle_queue: Arc<Mutex<Vec<IdleKind>>>,
current_keycode: Cell<Option<u16>>,
click_counter: ClickCounter,
active_text_input: Cell<Option<TextFieldToken>>,
deferred_queue: RefCell<Vec<DeferredOp>>,
request_animation: Cell<bool>,
in_draw: Cell<bool>,
parent: Option<crate::WindowHandle>,
}
impl std::fmt::Debug for WindowState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str("WindowState{")?;
self.window.fmt(f)?;
f.write_str("}")?;
Ok(())
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct CustomCursor(gtk::gdk::Cursor);
impl WindowBuilder {
pub fn new(app: Application) -> WindowBuilder {
WindowBuilder {
app,
handler: None,
title: String::new(),
menu: None,
size: Size::new(500.0, 400.0),
position: None,
level: None,
state: None,
min_size: None,
resizable: true,
show_titlebar: true,
transparent: false,
}
}
pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) {
self.handler = Some(handler);
}
pub fn set_size(&mut self, size: Size) {
self.size = size;
}
pub fn set_min_size(&mut self, size: Size) {
self.min_size = Some(size);
}
pub fn resizable(&mut self, resizable: bool) {
self.resizable = resizable;
}
pub fn show_titlebar(&mut self, show_titlebar: bool) {
self.show_titlebar = show_titlebar;
}
pub fn set_transparent(&mut self, transparent: bool) {
self.transparent = transparent;
}
pub fn set_position(&mut self, position: Point) {
self.position = Some(position);
}
pub fn set_level(&mut self, level: WindowLevel) {
self.level = Some(level);
}
pub fn set_window_state(&mut self, state: window::WindowState) {
self.state = Some(state);
}
pub fn set_title(&mut self, title: impl Into<String>) {
self.title = title.into();
}
pub fn set_menu(&mut self, menu: Menu) {
self.menu = Some(menu);
}
pub fn build(self) -> Result<WindowHandle, ShellError> {
let handler = self
.handler
.expect("Tried to build a window without setting the handler");
let window = ApplicationWindow::new(self.app.gtk_app());
window.set_title(&self.title);
window.set_resizable(self.resizable);
window.set_decorated(self.show_titlebar);
let mut transparent = false;
if self.transparent {
if let Some(screen) = gtk::prelude::GtkWindowExt::screen(&window) {
let visual = screen.rgba_visual();
transparent = visual.is_some();
window.set_visual(visual.as_ref());
}
}
window.set_app_paintable(transparent);
// Get the scale factor based on the GTK reported DPI
let scale_factor = window.display().default_screen().resolution() / SCALE_TARGET_DPI;
let scale = Scale::new(scale_factor, scale_factor);
let area = ScaledArea::from_dp(self.size, scale);
let size_px = area.size_px();
window.set_default_size(size_px.width as i32, size_px.height as i32);
let accel_group = AccelGroup::new();
window.add_accel_group(&accel_group);
let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0);
window.add(&vbox);
let drawing_area = gtk::DrawingArea::new();
// Set the parent widget and handle level specific code
let mut parent: Option<crate::WindowHandle> = None;
if let Some(level) = &self.level {
let hint = match level {
WindowLevel::AppWindow => WindowTypeHint::Normal,
WindowLevel::Tooltip(_) => WindowTypeHint::Tooltip,
WindowLevel::DropDown(_) => WindowTypeHint::DropdownMenu,
WindowLevel::Modal(_) => WindowTypeHint::Dialog,
};
window.set_type_hint(hint);
match &level {
WindowLevel::Tooltip(p) => {
parent = Some(p.clone());
}
WindowLevel::DropDown(p) => {
parent = Some(p.clone());
}
WindowLevel::Modal(p) => {
parent = Some(p.clone());
window.set_urgency_hint(true);
window.set_modal(true);
}
_ => (),
};
if let Some(parent) = &parent {
if let Some(parent_state) = parent.0.state.upgrade() {
window.set_transient_for(Some(&parent_state.window));
}
}
}
let state = WindowState {
window,
scale: Cell::new(scale),
area: Cell::new(area),
is_transparent: Cell::new(transparent),
handle_titlebar: Cell::new(false),
closing: Cell::new(false),
drawing_area,
surface: RefCell::new(None),
surface_size: Cell::new((0, 0)),
invalid: RefCell::new(Region::EMPTY),
handler: RefCell::new(handler),
idle_queue: Arc::new(Mutex::new(vec![])),
current_keycode: Cell::new(None),
click_counter: ClickCounter::default(),
active_text_input: Cell::new(None),
deferred_queue: RefCell::new(Vec::new()),
request_animation: Cell::new(false),
in_draw: Cell::new(false),
parent,
};
let win_state = Arc::new(state);
self.app
.gtk_app()
.connect_shutdown(clone!(win_state => move |_| {
// this ties a clone of Arc<WindowState> to the ApplicationWindow to keep it alive
// when the ApplicationWindow is destroyed, the last Arc is dropped
// and any Weak<WindowState> will be None on upgrade()
let _ = &win_state;
}));
let mut handle = WindowHandle {
state: Arc::downgrade(&win_state),
marker: std::marker::PhantomData,
};
if let Some(pos) = self.position {
handle.set_position(pos);
}
if let Some(state) = self.state {
handle.set_window_state(state)
}
if let Some(menu) = self.menu {
let menu = menu.into_gtk_menubar(&handle, &accel_group);
vbox.pack_start(&menu, false, false, 0);
}
win_state.drawing_area.set_events(
EventMask::EXPOSURE_MASK
| EventMask::POINTER_MOTION_MASK
| EventMask::LEAVE_NOTIFY_MASK
| EventMask::BUTTON_PRESS_MASK
| EventMask::BUTTON_RELEASE_MASK
| EventMask::KEY_PRESS_MASK
| EventMask::ENTER_NOTIFY_MASK
| EventMask::KEY_RELEASE_MASK
| EventMask::SCROLL_MASK
| EventMask::SMOOTH_SCROLL_MASK
| EventMask::FOCUS_CHANGE_MASK,
);
win_state.drawing_area.set_can_focus(true);
win_state.drawing_area.grab_focus();
win_state
.drawing_area
.connect_enter_notify_event(|widget, _| {
widget.grab_focus();
Inhibit(true)
});
// Set the minimum size
if let Some(min_size_dp) = self.min_size {
let min_area = ScaledArea::from_dp(min_size_dp, scale);
let min_size_px = min_area.size_px();
win_state
.drawing_area
.set_size_request(min_size_px.width as i32, min_size_px.height as i32);
}
win_state
.drawing_area
.connect_realize(clone!(handle => move |drawing_area| {
if let Some(clock) = drawing_area.frame_clock() {
clock.connect_before_paint(clone!(handle => move |_clock|{
if let Some(state) = handle.state.upgrade() {
state.in_draw.set(true);
}
}));
clock.connect_after_paint(clone!(handle => move |_clock|{
if let Some(state) = handle.state.upgrade() {
state.in_draw.set(false);
if state.request_animation.get() {
state.request_animation.set(false);
state.drawing_area.queue_draw();
}
}
}));
}
}));
win_state.drawing_area.connect_draw(clone!(handle => move |widget, context| {
if let Some(state) = handle.state.upgrade() {
let mut scale = state.scale.get();
let mut scale_changed = false;
// Check if the GTK reported DPI has changed,
// so that we can change our scale factor without restarting the application.
if let Some(scale_factor) = state.window.window()
.map(|w| w.display().default_screen().resolution() / SCALE_TARGET_DPI) {
let reported_scale = Scale::new(scale_factor, scale_factor);
if scale != reported_scale {
scale = reported_scale;
state.scale.set(scale);
scale_changed = true;
state.with_handler(|h| h.scale(scale));
}
}
// Create a new cairo surface if necessary (either because there is no surface, or
// because the size or scale changed).
let extents = widget.allocation();
let size_px = Size::new(extents.width() as f64, extents.height() as f64);
let no_surface = state.surface.try_borrow().map(|x| x.is_none()).ok() == Some(true);
if no_surface || scale_changed || state.area.get().size_px() != size_px {
let area = ScaledArea::from_px(size_px, scale);
let size_dp = area.size_dp();
state.area.set(area);
if let Err(e) = state.resize_surface(extents.width(), extents.height()) {
error!("Failed to resize surface: {}", e);
}
state.with_handler(|h| h.size(size_dp));
state.invalidate_rect(size_dp.to_rect());
}
state.with_handler(|h| h.prepare_paint());
let invalid = match state.invalid.try_borrow_mut() {
Ok(mut invalid) => std::mem::replace(&mut *invalid, Region::EMPTY),
Err(_) => {
error!("invalid region borrowed while drawing");
Region::EMPTY
}
};
if let Ok(Some(surface)) = state.surface.try_borrow().as_ref().map(|s| s.as_ref()) {
// Note that we're borrowing the surface while calling the handler. This is ok,
// because we don't return control to the system or re-borrow the surface from
// any code that the client can call.
state.with_handler_and_dont_check_the_other_borrows(|handler| {
let surface_context = cairo::Context::new(surface).unwrap();
// Clip to the invalid region, in order that our surface doesn't get
// messed up if there's any painting outside them.
for rect in invalid.rects() {
let rect = rect.to_px(scale);
surface_context.rectangle(rect.x0, rect.y0, rect.width(), rect.height());
}
surface_context.clip();
surface_context.scale(scale.x(), scale.y());
let mut piet_context = Piet::new(&surface_context);
handler.paint(&mut piet_context, &invalid);
if let Err(e) = piet_context.finish() {
error!("piet error on render: {:?}", e);
}
// Copy the entire surface to the drawing area (not just the invalid
// region, because there might be parts of the drawing area that were
// invalidated by external forces).
// TODO: how are we supposed to handle these errors? What can we do besides panic? Probably nothing right?
let alloc = widget.allocation();
context.set_source_surface(surface, 0.0, 0.0).unwrap();
context.rectangle(0.0, 0.0, alloc.width() as f64, alloc.height() as f64);
context.fill().unwrap();
});
} else {
warn!("Drawing was skipped because there was no surface");
}
}
Inhibit(false)
}));
win_state.drawing_area.connect_screen_changed(
clone!(handle => move |widget, _prev_screen| {
if let Some(state) = handle.state.upgrade() {
if let Some(screen) = widget.screen(){
let visual = screen.rgba_visual();
state.is_transparent.set(visual.is_some());
widget.set_visual(visual.as_ref());
}
}
}),
);
win_state.drawing_area.connect_button_press_event(clone!(handle => move |_widget, event| {
if let Some(state) = handle.state.upgrade() {
state.with_handler(|handler| {
if let Some(button) = get_mouse_button(event.button()) {
let scale = state.scale.get();
let button_state = event.state();
let gtk_count = get_mouse_click_count(event.event_type());
let pos: Point = event.position().into();
let count = if gtk_count == 1 {
let settings = state.drawing_area.settings().unwrap();
let thresh_dist = settings.gtk_double_click_distance();
state.click_counter.set_distance(thresh_dist.into());
if let Ok(ms) = settings.gtk_double_click_time().try_into() {
state.click_counter.set_interval_ms(ms);
}
state.click_counter.count_for_click(pos)
} else {
0
};
if gtk_count == 0 || gtk_count == 1 {
handler.mouse_down(
&MouseEvent {
pos: pos.to_dp(scale),
buttons: get_mouse_buttons_from_modifiers(button_state).with(button),
mods: get_modifiers(button_state),
count,
focus: false,
button,
wheel_delta: Vec2::ZERO
},
);
}
if button.is_left() && state.handle_titlebar.replace(false) {
let (root_x, root_y) = event.root();
state.window.begin_move_drag(event.button() as i32, root_x as i32, root_y as i32, event.time());
}
}
});
}
Inhibit(true)
}));
win_state.drawing_area.connect_button_release_event(clone!(handle => move |_widget, event| {
if let Some(state) = handle.state.upgrade() {
state.with_handler(|handler| {
if let Some(button) = get_mouse_button(event.button()) {
let scale = state.scale.get();
let button_state = event.state();
handler.mouse_up(
&MouseEvent {
pos: Point::from(event.position()).to_dp(scale),
buttons: get_mouse_buttons_from_modifiers(button_state).without(button),
mods: get_modifiers(button_state),
count: 0,
focus: false,
button,
wheel_delta: Vec2::ZERO
},
);
if button.is_left() {
state.handle_titlebar.set(false);
}
}
});
}
Inhibit(true)
}));
win_state.drawing_area.connect_motion_notify_event(
clone!(handle => move |_widget, motion| {
if let Some(state) = handle.state.upgrade() {
let scale = state.scale.get();
let motion_state = motion.state();
let mouse_event = MouseEvent {
pos: Point::from(motion.position()).to_dp(scale),
buttons: get_mouse_buttons_from_modifiers(motion_state),
mods: get_modifiers(motion_state),
count: 0,
focus: false,
button: MouseButton::None,
wheel_delta: Vec2::ZERO
};
state.with_handler(|h| h.mouse_move(&mouse_event));
}
Inhibit(true)
}),
);
win_state.drawing_area.connect_leave_notify_event(
clone!(handle => move |_widget, _crossing| {
if let Some(state) = handle.state.upgrade() {
state.with_handler(|h| h.mouse_leave());
}
Inhibit(true)
}),
);
win_state
.drawing_area
.connect_scroll_event(clone!(handle => move |_widget, scroll| {
if let Some(state) = handle.state.upgrade() {
let scale = state.scale.get();
let mods = get_modifiers(scroll.state());
// The magic "120"s are from Microsoft's documentation for WM_MOUSEWHEEL.
// They claim that one "tick" on a scroll wheel should be 120 units.
let shift = mods.shift();
let wheel_delta = match scroll.direction() {
ScrollDirection::Up if shift => Some(Vec2::new(-120.0, 0.0)),
ScrollDirection::Up => Some(Vec2::new(0.0, -120.0)),
ScrollDirection::Down if shift => Some(Vec2::new(120.0, 0.0)),
ScrollDirection::Down => Some(Vec2::new(0.0, 120.0)),
ScrollDirection::Left => Some(Vec2::new(-120.0, 0.0)),
ScrollDirection::Right => Some(Vec2::new(120.0, 0.0)),
ScrollDirection::Smooth => {
//TODO: Look at how gtk's scroll containers implements it
let (mut delta_x, mut delta_y) = scroll.delta();
delta_x *= 120.;
delta_y *= 120.;
if shift {
delta_x += delta_y;
delta_y = 0.;
}
Some(Vec2::new(delta_x, delta_y))
}
e => {
warn!(
"Warning: the Druid widget got some whacky scroll direction {:?}",
e
);
None
}
};
if let Some(wheel_delta) = wheel_delta {
let mouse_event = MouseEvent {
pos: Point::from(scroll.position()).to_dp(scale),
buttons: get_mouse_buttons_from_modifiers(scroll.state()),
mods,
count: 0,
focus: false,
button: MouseButton::None,
wheel_delta
};
state.with_handler(|h| h.wheel(&mouse_event));
}
}
Inhibit(true)
}));
win_state
.drawing_area
.connect_key_press_event(clone!(handle => move |_widget, key| {
if let Some(state) = handle.state.upgrade() {
let hw_keycode = key.hardware_keycode();
let repeat = state.current_keycode.get() == Some(hw_keycode);
state.current_keycode.set(Some(hw_keycode));
state.with_handler(|h|
simulate_input(h, state.active_text_input.get(), make_key_event(key, repeat, KeyState::Down))
);
}
Inhibit(true)
}));
win_state
.drawing_area
.connect_key_release_event(clone!(handle => move |_widget, key| {
if let Some(state) = handle.state.upgrade() {
if state.current_keycode.get() == Some(key.hardware_keycode()) {
state.current_keycode.set(None);
}
state.with_handler(|h|
h.key_up(make_key_event(key, false, KeyState::Up))
);
}
Inhibit(true)
}));
win_state
.drawing_area
.connect_focus_in_event(clone!(handle => move |_widget, _event| {
if let Some(state) = handle.state.upgrade() {
state.with_handler(|h| h.got_focus());
}
Inhibit(true)
}));
win_state
.drawing_area
.connect_focus_out_event(clone!(handle => move |_widget, _event| {
if let Some(state) = handle.state.upgrade() {
state.with_handler(|h| h.lost_focus());
}
Inhibit(true)
}));
win_state
.window
.connect_delete_event(clone!(handle => move |_widget, _ev| {
if let Some(state) = handle.state.upgrade() {
state.with_handler(|h| h.request_close());
Inhibit(!state.closing.get())
} else {
Inhibit(false)
}
}));
win_state
.drawing_area
.connect_destroy(clone!(handle => move |_widget| {
if let Some(state) = handle.state.upgrade() {
state.with_handler(|h| h.destroy());
}
}));
vbox.pack_end(&win_state.drawing_area, true, true, 0);
win_state.drawing_area.realize();
win_state
.drawing_area
.window()
.expect("realize didn't create window")
.set_event_compression(false);
if let Some(level) = self.level {
let override_redirect = match level {
WindowLevel::AppWindow => false,
WindowLevel::Tooltip(_) | WindowLevel::DropDown(_) | WindowLevel::Modal(_) => true,
};
if let Some(window) = win_state.window.window() {
window.set_override_redirect(override_redirect);
}
}
let size = self.size;
win_state.with_handler(|h| {
h.connect(&handle.clone().into());
h.scale(scale);
h.size(size);
});
Ok(handle)
}
}
impl WindowState {
#[track_caller]
fn with_handler<T, F: FnOnce(&mut dyn WinHandler) -> T>(&self, f: F) -> Option<T> {
if self.invalid.try_borrow_mut().is_err() || self.surface.try_borrow_mut().is_err() {
error!("other RefCells were borrowed when calling into the handler");
return None;
}
let ret = self.with_handler_and_dont_check_the_other_borrows(f);
self.run_deferred();
ret
}
#[track_caller]
fn with_handler_and_dont_check_the_other_borrows<T, F: FnOnce(&mut dyn WinHandler) -> T>(
&self,
f: F,
) -> Option<T> {
match self.handler.try_borrow_mut() {
Ok(mut h) => Some(f(&mut **h)),
Err(_) => {
error!("failed to borrow WinHandler at {}", Location::caller());
None
}
}
}
fn resize_surface(&self, width: i32, height: i32) -> Result<(), anyhow::Error> {
fn next_size(x: i32) -> i32 {
// We round up to the nearest multiple of `accuracy`, which is between x/2 and x/4.
// Don't bother rounding to anything smaller than 32 = 2^(7-1).
let accuracy = 1 << ((32 - x.leading_zeros()).max(7) - 2);
let mask = accuracy - 1;
(x + mask) & !mask
}
let mut surface = self.surface.borrow_mut();
let mut cur_size = self.surface_size.get();
let (width, height) = (next_size(width), next_size(height));
if surface.is_none() || cur_size != (width, height) {
cur_size = (width, height);
self.surface_size.set(cur_size);
if let Some(s) = surface.as_ref() {
s.finish();
}
*surface = None;
if let Some(w) = self.drawing_area.window() {
if self.is_transparent.get() {
*surface = w.create_similar_surface(cairo::Content::ColorAlpha, width, height);
} else {
*surface = w.create_similar_surface(cairo::Content::Color, width, height);
}
if surface.is_none() {
return Err(anyhow!("create_similar_surface failed"));
}
} else {
return Err(anyhow!("drawing area has no window"));
}
}
Ok(())
}
/// Queues a call to `prepare_paint` and `paint`, but without marking any region for
/// invalidation.
fn request_anim_frame(&self) {
if self.in_draw.get() {
self.request_animation.set(true);
} else {
self.drawing_area.queue_draw()
}
}
/// Invalidates a rectangle, given in display points.
fn invalidate_rect(&self, rect: Rect) {
if let Ok(mut region) = self.invalid.try_borrow_mut() {
let scale = self.scale.get();
// We prefer to invalidate an integer number of pixels.
let rect = rect.to_px(scale).expand().to_dp(scale);
region.add_rect(rect);
self.window.queue_draw();
} else {
warn!("Not invalidating rect because region already borrowed");
}
}
/// Pushes a deferred op onto the queue.
fn defer(&self, op: DeferredOp) {
self.deferred_queue.borrow_mut().push(op);
}
fn run_deferred(&self) {
let queue = self.deferred_queue.replace(Vec::new());
for op in queue {
match op {
DeferredOp::Open(options, token) => {
// Keep the value of this option for later
let multi_selection = options.multi_selection;
let file_infos = match dialog::get_file_dialog_path(
self.window.upcast_ref(),
FileDialogType::Open,
options,
) {
Ok(infos) => infos
.iter()
.map(|path| FileInfo {
path: path.into(),
format: None,
})
.collect(),
Err(err) => {
tracing::error!("Error trying to open file: {}", err);
vec![]
}
};
if multi_selection {
self.with_handler(|h| h.open_files(token, file_infos));
} else {
self.with_handler(|h| h.open_file(token, file_infos.first().cloned()));
}
}
DeferredOp::SaveAs(options, token) => {
let file_info = dialog::get_file_dialog_path(
self.window.upcast_ref(),
FileDialogType::Save,
options,
)
.ok()
.map(|s| FileInfo {
// `get_file_dialog_path` guarantees that save dialogs
// only return on path
path: s.first().unwrap().into(),
format: None,
});
self.with_handler(|h| h.save_as(token, file_info));
}
DeferredOp::ContextMenu(menu, handle) => {
let accel_group = AccelGroup::new();
self.window.add_accel_group(&accel_group);
let menu = menu.into_gtk_menu(&handle, &accel_group);
menu.set_attach_widget(Some(&self.window));
menu.show_all();
menu.popup_easy(3, gtk::current_event_time());
}
}
}
}
}
impl WindowHandle {
pub fn show(&self) {
if let Some(state) = self.state.upgrade() {
state.window.show_all();
}
}
pub fn resizable(&self, resizable: bool) {
if let Some(state) = self.state.upgrade() {
state.window.set_resizable(resizable)
}
}
pub fn show_titlebar(&self, show_titlebar: bool) {
if let Some(state) = self.state.upgrade() {
state.window.set_decorated(show_titlebar)
}
}
pub fn set_position(&self, mut position: Point) {
if let Some(state) = self.state.upgrade() {
if let Some(parent_state) = &state.parent {
let pos = (*parent_state).get_position();
position += (pos.x, pos.y)
}
};
if let Some(state) = self.state.upgrade() {
let px = position.to_px(state.scale.get());
state.window.move_(px.x as i32, px.y as i32)
}
}
pub fn get_position(&self) -> Point {
if let Some(state) = self.state.upgrade() {
let (x, y) = state.window.position();
let position = Point::new(x as f64, y as f64).to_dp(state.scale.get());
if let Some(parent_handle) = &state.parent {
let pos = parent_handle.get_position();