forked from linebender/druid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindow.rs
1418 lines (1291 loc) · 49 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 2020 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.
//! X11 window creation and window management.
use std::any::Any;
use std::cell::RefCell;
use std::convert::{TryFrom, TryInto};
use std::collections::BinaryHeap;
use std::os::unix::io::RawFd;
use std::rc::{Rc, Weak};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use anyhow::{anyhow, Context, Error};
use cairo::{XCBConnection as CairoXCBConnection, XCBDrawable, XCBSurface, XCBVisualType};
use x11rb::atom_manager;
use x11rb::connection::Connection;
use x11rb::protocol::present::{CompleteNotifyEvent, ConnectionExt as _, IdleNotifyEvent};
use x11rb::protocol::xfixes::{ConnectionExt as _, Region};
use x11rb::protocol::xproto::{
self, AtomEnum, ConfigureNotifyEvent, ConnectionExt, CreateGCAux, EventMask, Gcontext, Pixmap,
PropMode, Rectangle, Visualtype, WindowClass,
};
use x11rb::wrapper::ConnectionExt as _;
use x11rb::xcb_ffi::XCBConnection;
use crate::common_util::IdleCallback;
use crate::dialog::{FileDialogOptions, FileInfo};
use crate::error::Error as ShellError;
use crate::keyboard::{KeyEvent, KeyState, Modifiers};
use crate::kurbo::{Point, Rect, Size, Vec2};
use crate::mouse::{Cursor, MouseButton, MouseButtons, MouseEvent};
use crate::piet::{Piet, RenderContext};
use crate::scale::Scale;
use crate::window::{IdleToken, Text, TimerToken, WinHandler};
use super::application::Application;
use super::keycodes;
use super::menu::Menu;
use super::util::{self, Timer};
/// A version of XCB's `xcb_visualtype_t` struct. This was copied from the [example] in x11rb; it
/// is used to interoperate with cairo.
///
/// The official upstream reference for this struct definition is [here].
///
/// [example]: https://github.com/psychon/x11rb/blob/master/cairo-example/src/main.rs
/// [here]: https://xcb.freedesktop.org/manual/structxcb__visualtype__t.html
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct xcb_visualtype_t {
pub visual_id: u32,
pub class: u8,
pub bits_per_rgb_value: u8,
pub colormap_entries: u16,
pub red_mask: u32,
pub green_mask: u32,
pub blue_mask: u32,
pub pad0: [u8; 4],
}
impl From<Visualtype> for xcb_visualtype_t {
fn from(value: Visualtype) -> xcb_visualtype_t {
xcb_visualtype_t {
visual_id: value.visual_id,
class: value.class.into(),
bits_per_rgb_value: value.bits_per_rgb_value,
colormap_entries: value.colormap_entries,
red_mask: value.red_mask,
green_mask: value.green_mask,
blue_mask: value.blue_mask,
pad0: [0; 4],
}
}
}
pub(crate) struct WindowBuilder {
app: Application,
handler: Option<Box<dyn WinHandler>>,
title: String,
size: Size,
min_size: Size,
}
impl WindowBuilder {
pub fn new(app: Application) -> WindowBuilder {
WindowBuilder {
app,
handler: None,
title: String::new(),
size: Size::new(500.0, 400.0),
min_size: Size::new(0.0, 0.0),
}
}
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, min_size: Size) {
log::warn!("WindowBuilder::set_min_size is implemented, but the setting is currently unused for X11 platforms.");
self.min_size = min_size;
}
pub fn resizable(&mut self, _resizable: bool) {
log::warn!("WindowBuilder::resizable is currently unimplemented for X11 platforms.");
}
pub fn show_titlebar(&mut self, _show_titlebar: bool) {
log::warn!("WindowBuilder::show_titlebar is currently unimplemented for X11 platforms.");
}
pub fn set_title<S: Into<String>>(&mut self, title: S) {
self.title = title.into();
}
pub fn set_menu(&mut self, _menu: Menu) {
// TODO(x11/menus): implement WindowBuilder::set_menu (currently a no-op)
}
/// Registers and returns all the atoms that the window will need.
fn atoms(&self, window_id: u32) -> Result<WindowAtoms, Error> {
let conn = self.app.connection();
let atoms = WindowAtoms::new(conn.as_ref())?
.reply()
.context("get X11 atoms")?;
// Replace the window's WM_PROTOCOLS with the following.
let protocols = [atoms.WM_DELETE_WINDOW];
conn.change_property32(
PropMode::Replace,
window_id,
atoms.WM_PROTOCOLS,
AtomEnum::ATOM,
&protocols,
)?
.check()
.context("set WM_PROTOCOLS")?;
Ok(atoms)
}
fn create_cairo_surface(
&self,
window_id: u32,
visual_type: &Visualtype,
) -> Result<XCBSurface, Error> {
let conn = self.app.connection();
let cairo_xcb_connection = unsafe {
CairoXCBConnection::from_raw_none(
conn.get_raw_xcb_connection() as *mut cairo_sys::xcb_connection_t
)
};
let cairo_drawable = XCBDrawable(window_id);
let mut xcb_visual = xcb_visualtype_t::from(*visual_type);
let cairo_visual_type = unsafe {
XCBVisualType::from_raw_none(
&mut xcb_visual as *mut xcb_visualtype_t as *mut cairo_sys::xcb_visualtype_t,
)
};
let cairo_surface = XCBSurface::create(
&cairo_xcb_connection,
&cairo_drawable,
&cairo_visual_type,
self.size.width as i32,
self.size.height as i32,
)
.map_err(|status| anyhow!("Failed to create cairo surface: {}", status))?;
Ok(cairo_surface)
}
// TODO(x11/menus): make menus if requested
pub fn build(self) -> Result<WindowHandle, Error> {
let conn = self.app.connection();
let screen_num = self.app.screen_num();
let id = conn.generate_id()?;
let setup = conn.setup();
let screen = setup
.roots
.get(screen_num as usize)
.ok_or_else(|| anyhow!("Invalid screen num: {}", screen_num))?;
let visual_type = util::get_visual_from_screen(&screen)
.ok_or_else(|| anyhow!("Couldn't get visual from screen"))?;
let visual_id = visual_type.visual_id;
let cw_values = xproto::CreateWindowAux::new().event_mask(
EventMask::Exposure
| EventMask::StructureNotify
| EventMask::KeyPress
| EventMask::KeyRelease
| EventMask::ButtonPress
| EventMask::ButtonRelease
| EventMask::PointerMotion,
);
// Create the actual window
let (width, height) = (self.size.width as u16, self.size.height as u16);
conn.create_window(
// Window depth
x11rb::COPY_FROM_PARENT.try_into().unwrap(),
// The new window's ID
id,
// Parent window of this new window
// TODO(#468): either `screen.root()` (no parent window) or pass parent here to attach
screen.root,
// X-coordinate of the new window
0,
// Y-coordinate of the new window
0,
// Width of the new window
// TODO(x11/dpi_scaling): figure out DPI scaling
width,
// Height of the new window
// TODO(x11/dpi_scaling): figure out DPI scaling
height,
// Border width
0,
// Window class type
WindowClass::InputOutput,
// Visual ID
visual_id,
// Window properties mask
&cw_values,
)?
.check()
.context("create window")?;
// Allocate a graphics context (currently used only for copying pixels when present is
// unavailable).
let gc = conn.generate_id()?;
conn.create_gc(gc, id, &CreateGCAux::new())?
.check()
.context("create graphics context")?;
// TODO(x11/errors): Should do proper cleanup (window destruction etc) in case of error
let atoms = self.atoms(id)?;
let cairo_surface = RefCell::new(self.create_cairo_surface(id, &visual_type)?);
let state = RefCell::new(WindowState {
size: self.size,
invalid: Rect::ZERO,
});
let present_data = match self.initialize_present_data(id) {
Ok(p) => Some(p),
Err(e) => {
log::info!("Failed to initialize present extension: {}", e);
None
}
};
let handler = RefCell::new(self.handler.unwrap());
// When using present, we generally need two buffers (because after we present, we aren't
// allowed to use that buffer for a little while, and so we might want to render to the
// other one). Otherwise, we only need one.
let buf_count = if present_data.is_some() { 2 } else { 1 };
let buffers = RefCell::new(Buffers::new(
conn,
id,
buf_count,
width,
height,
screen.root_depth,
)?);
// Initialize some properties
let pid = nix::unistd::Pid::this().as_raw();
if let Ok(pid) = u32::try_from(pid) {
conn.change_property32(
xproto::PropMode::Replace,
id,
atoms._NET_WM_PID,
AtomEnum::CARDINAL,
&[pid],
)?
.check()
.context("set _NET_WM_PID")?;
}
let window = Rc::new(Window {
id,
gc,
app: self.app.clone(),
handler,
cairo_surface,
atoms,
state,
timer_queue: Mutex::new(BinaryHeap::new()),
idle_queue: Arc::new(Mutex::new(Vec::new())),
idle_pipe: self.app.idle_pipe(),
present_data: RefCell::new(present_data),
buffers,
});
window.set_title(&self.title);
let handle = WindowHandle::new(id, Rc::downgrade(&window));
window.connect(handle.clone())?;
self.app.add_window(id, window)?;
Ok(handle)
}
fn initialize_present_data(&self, window_id: u32) -> Result<PresentData, Error> {
if self.app.present_opcode().is_some() {
let conn = self.app.connection();
// We use the CompleteNotify events to schedule the next frame, and the IdleNotify
// events to manage our buffers.
let id = conn.generate_id()?;
use x11rb::protocol::present::EventMask::*;
conn.present_select_input(id, window_id, CompleteNotify | IdleNotify)?
.check()
.context("set present event mask")?;
let region_id = conn.generate_id()?;
conn.xfixes_create_region(region_id, &[])
.context("create region")?;
Ok(PresentData {
serial: 0,
region: region_id,
waiting_on: None,
needs_present: false,
last_msc: None,
last_ust: None,
})
} else {
Err(anyhow!("no present opcode"))
}
}
}
/// An X11 window.
pub(crate) struct Window {
id: u32,
gc: Gcontext,
app: Application,
handler: RefCell<Box<dyn WinHandler>>,
cairo_surface: RefCell<XCBSurface>,
atoms: WindowAtoms,
state: RefCell<WindowState>,
/// Timers, sorted by "earliest deadline first"
timer_queue: Mutex<BinaryHeap<Timer>>,
idle_queue: Arc<Mutex<Vec<IdleKind>>>,
// Writing to this wakes up the event loop, so that it can run idle handlers.
idle_pipe: RawFd,
/// When this is `Some(_)`, we use the X11 Present extension to present windows. This syncs all
/// presentation to vblank and it appears to prevent tearing (subject to various caveats
/// regarding broken video drivers).
///
/// The Present extension works roughly like this: we submit a pixmap for presentation. It will
/// get drawn at the next vblank, and some time shortly after that we'll get a notification
/// that the drawing was completed.
///
/// There are three ways that rendering can get triggered:
/// 1) We render a frame, and it signals to us that an animation is requested. In this case, we
/// will render the next frame as soon as we get a notification that the just-presented
/// frame completed. In other words, we use `CompleteNotifyEvent` to schedule rendering.
/// 2) We get an expose event telling us that a region got invalidated. In
/// this case, we will render the next frame immediately unless we're already waiting for a
/// completion notification. (If we are waiting for a completion notification, we just make
/// a note to schedule a new frame once we get it.)
/// 3) Someone calls `invalidate` or `invalidate_rect` on us. We schedule ourselves to repaint
/// in the idle loop. This is better than rendering straight away, because for example they
/// might have called `invalidate` from their paint callback, and then we'd end up painting
/// re-entrantively.
///
/// This is probably not the best (or at least, not the lowest-latency) scheme we can come up
/// with, because invalidations that happen shortly after a vblank might need to wait 2 frames
/// before they appear. If we're getting lots of invalidations, it might be better to render more
/// than once per frame. Note that if we do, it will require some changes to part 1) above,
/// because if we render twice in a frame then we will get two completion notifications in a
/// row, so we don't want to present on both of them. The `msc` field of the completion
/// notification might be useful here, because it allows us to check how many frames have
/// actually been presented.
present_data: RefCell<Option<PresentData>>,
buffers: RefCell<Buffers>,
}
// This creates a `struct WindowAtoms` containing the specified atoms as members (along with some
// convenience methods to intern and query those atoms). We use the following atoms:
//
// WM_PROTOCOLS
//
// List of atoms that identify the communications protocols between
// the client and window manager in which the client is willing to participate.
//
// https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#wm_protocols_property
//
// WM_DELETE_WINDOW
//
// Including this atom in the WM_PROTOCOLS property on each window makes sure that
// if the window manager respects WM_DELETE_WINDOW it will send us the event.
//
// The WM_DELETE_WINDOW event is sent when there is a request to close the window.
// Registering for but ignoring this event means that the window will remain open.
//
// https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#window_deletion
//
// _NET_WM_PID
//
// A property containing the PID of the process that created the window.
//
// https://specifications.freedesktop.org/wm-spec/wm-spec-1.3.html#idm45805407915360
//
// _NET_WM_NAME
//
// A version of WM_NAME supporting UTF8 text.
//
// https://specifications.freedesktop.org/wm-spec/wm-spec-1.3.html#idm45805407982336
//
// UTF8_STRING
//
// The type of _NET_WM_NAME
atom_manager! {
WindowAtoms: WindowAtomsCookie {
WM_PROTOCOLS,
WM_DELETE_WINDOW,
_NET_WM_PID,
_NET_WM_NAME,
UTF8_STRING,
}
}
/// The mutable state of the window.
struct WindowState {
size: Size,
/// The region that was invalidated since the last time we rendered.
invalid: Rect,
}
/// A collection of pixmaps for rendering to. This gets used in two different ways: if the present
/// extension is enabled, we render to a pixmap and then present it. If the present extension is
/// disabled, we render to a pixmap and then call `copy_area` on it (this probably isn't the best
/// way to imitate double buffering, but it's the fallback anyway).
struct Buffers {
/// A list of idle pixmaps. We take a pixmap from here for rendering to.
///
/// When we're not using the present extension, all pixmaps belong in here; as soon as we copy
/// from one, we can use it again.
///
/// When we submit a pixmap to present, we're not allowed to touch it again until we get a
/// corresponding IDLE_NOTIFY event. In my limited experiments this happens shortly after
/// vsync, meaning that we may want to start rendering the next pixmap before we get the old
/// one back. Therefore, we keep a list of pixmaps. We pop one each time we render, and push
/// one when we get IDLE_NOTIFY.
///
/// Since the current code only renders at most once per vsync, two pixmaps seems to always be
/// enough. Nevertheless, we will allocate more on the fly if we need them. Note that rendering
/// more than once per vsync can only improve latency, because only the most recently-presented
/// pixmap will get rendered.
idle_pixmaps: Vec<Pixmap>,
/// A list of all the allocated pixmaps (including the idle ones).
all_pixmaps: Vec<Pixmap>,
/// The sizes of the pixmaps (they all have the same size). In order to avoid repeatedly
/// reallocating as the window size changes, we allow these to be bigger than the window.
width: u16,
height: u16,
/// The depth of the currently allocated pixmaps.
depth: u8,
}
/// The state involved in using X's [Present] extension.
///
/// [Present]: https://cgit.freedesktop.org/xorg/proto/presentproto/tree/presentproto.txt
#[derive(Debug)]
struct PresentData {
/// A monotonically increasing present request counter.
serial: u32,
/// The region that we use for telling X what to present.
region: Region,
/// Did we submit a present that hasn't completed yet? If so, this is its serial number.
waiting_on: Option<u32>,
/// We need to render another frame as soon as the current one is done presenting.
needs_present: bool,
/// The last MSC (media stream counter) that was completed. This can be used to diagnose
/// latency problems, because MSC is a frame counter: it increments once per frame. We should
/// be presenting on every frame, and storing the last completed MSC lets us know if we missed
/// one.
last_msc: Option<u64>,
/// The time at which the last frame was completed. The present protocol documentation doesn't
/// define the units, but it appears to be in microseconds.
last_ust: Option<u64>,
}
impl Window {
fn connect(&self, handle: WindowHandle) -> Result<(), Error> {
let mut handler = borrow_mut!(self.handler)?;
let size = self.size()?;
handler.connect(&handle.into());
handler.scale(Scale::default());
handler.size(size);
Ok(())
}
/// Start the destruction of the window.
pub fn destroy(&self) {
log_x11!(self.app.connection().destroy_window(self.id));
}
fn size(&self) -> Result<Size, Error> {
Ok(borrow!(self.state)?.size)
}
fn set_size(&self, size: Size) -> Result<(), Error> {
// TODO(x11/dpi_scaling): detect DPI and scale size
let new_size = {
let mut state = borrow_mut!(self.state)?;
if size != state.size {
state.size = size;
true
} else {
false
}
};
if new_size {
borrow_mut!(self.buffers)?.set_size(
self.app.connection(),
self.id,
size.width as u16,
size.height as u16,
);
borrow_mut!(self.cairo_surface)?
.set_size(size.width as i32, size.height as i32)
.map_err(|status| {
anyhow!(
"Failed to update cairo surface size to {:?}: {}",
size,
status
)
})?;
self.enlarge_invalid_rect(size.to_rect())?;
borrow_mut!(self.handler)?.size(size);
}
Ok(())
}
// Ensure that our cairo context is targeting the right drawable, allocating one if necessary.
fn update_cairo_surface(&self) -> Result<(), Error> {
let mut buffers = borrow_mut!(self.buffers)?;
let pixmap = if let Some(p) = buffers.idle_pixmaps.last() {
*p
} else {
log::info!("ran out of idle pixmaps, creating a new one");
buffers.create_pixmap(self.app.connection(), self.id)?
};
let drawable = XCBDrawable(pixmap);
borrow_mut!(self.cairo_surface)?
.set_drawable(&drawable, buffers.width as i32, buffers.height as i32)
.map_err(|e| anyhow!("Failed to update cairo drawable: {}", e))?;
Ok(())
}
fn render(&self) -> Result<(), Error> {
let size = borrow!(self.state)?.size;
let invalid_rect = borrow!(self.state)?.invalid;
let mut anim = false;
self.update_cairo_surface()?;
{
let surface = borrow!(self.cairo_surface)?;
let mut cairo_ctx = cairo::Context::new(&surface);
let mut piet_ctx = Piet::new(&mut cairo_ctx);
piet_ctx.clip(invalid_rect);
// We need to be careful with earlier returns here, because piet_ctx
// can panic if it isn't finish()ed. Also, we want to reset cairo's clip
// even on error.
let err;
match borrow_mut!(self.handler) {
Ok(mut handler) => {
anim = handler.paint(&mut piet_ctx, invalid_rect);
err = piet_ctx
.finish()
.map_err(|e| anyhow!("Window::render - piet finish failed: {}", e));
}
Err(e) => {
err = Err(e);
if let Err(e) = piet_ctx.finish() {
// We can't return both errors, so just log this one.
log::error!("Window::render - piet finish failed in error branch: {}", e);
}
}
};
cairo_ctx.reset_clip();
err?;
}
borrow_mut!(self.state)?.invalid = Rect::ZERO;
self.set_needs_present(false)?;
let mut buffers = borrow_mut!(self.buffers)?;
let pixmap = *buffers
.idle_pixmaps
.last()
.ok_or_else(|| anyhow!("after rendering, no pixmap to present"))?;
if let Some(present) = borrow_mut!(self.present_data)?.as_mut() {
present.present(self.app.connection(), pixmap, self.id, invalid_rect)?;
buffers.idle_pixmaps.pop();
if anim {
self.enlarge_invalid_rect(size.to_rect())?;
present.needs_present = true;
}
} else {
let (x, y) = (invalid_rect.x0 as i16, invalid_rect.y0 as i16);
let (w, h) = (invalid_rect.width() as u16, invalid_rect.height() as u16);
self.app
.connection()
.copy_area(pixmap, self.id, self.gc, x, y, x, y, w, h)?;
// We aren't using the present extension, so use the idle loop to schedule redraws.
// Note that the idle loop's wakeup times are roughly tied to the refresh rate, so this
// shouldn't draw too often.
if anim {
self.invalidate();
}
}
Ok(())
}
fn show(&self) {
log_x11!(self.app.connection().map_window(self.id));
}
fn close(&self) {
self.destroy();
}
/// Set whether the window should be resizable
fn resizable(&self, _resizable: bool) {
log::warn!("Window::resizeable is currently unimplemented for X11 platforms.");
}
/// Set whether the window should show titlebar
fn show_titlebar(&self, _show_titlebar: bool) {
log::warn!("Window::show_titlebar is currently unimplemented for X11 platforms.");
}
/// Bring this window to the front of the window stack and give it focus.
fn bring_to_front_and_focus(&self) {
// TODO(x11/misc): Unsure if this does exactly what the doc comment says; need a test case.
let conn = self.app.connection();
log_x11!(conn.configure_window(
self.id,
&xproto::ConfigureWindowAux::new().stack_mode(xproto::StackMode::Above),
));
log_x11!(conn.set_input_focus(
xproto::InputFocus::PointerRoot,
self.id,
xproto::Time::CurrentTime,
));
}
fn enlarge_invalid_rect(&self, rect: Rect) -> Result<(), Error> {
let invalid = &mut borrow_mut!(self.state)?.invalid;
// This is basically just a rectangle union, but we need to be careful because
// `Rect::union` doesn't do what we want when one rect is empty.
if invalid.area() == 0.0 {
*invalid = rect;
} else if rect.area() > 0.0 {
*invalid = invalid.union(rect);
}
Ok(())
}
/// Redraw more-or-less now.
///
/// "More-or-less" because if we're already waiting on a present, we defer the drawing until it
/// completes.
fn redraw_now(&self) -> Result<(), Error> {
if self.waiting_on_present()? {
self.set_needs_present(true)?;
} else {
self.render()?;
}
Ok(())
}
/// Schedule a redraw on the idle loop, or if we are waiting on present then schedule it for
/// when the current present finishes.
fn redraw_soon(&self) {
if let Ok(true) = self.waiting_on_present() {
if let Err(e) = self.set_needs_present(true) {
log::error!("Window::redraw_soon - failed to schedule present: {}", e);
}
} else {
let idle = IdleHandle {
queue: Arc::clone(&self.idle_queue),
pipe: self.idle_pipe,
};
idle.schedule_redraw();
}
}
fn invalidate(&self) {
match self.size() {
Ok(size) => self.invalidate_rect(size.to_rect()),
Err(err) => log::error!("Window::invalidate - failed to get size: {}", err),
}
}
fn invalidate_rect(&self, rect: Rect) {
if let Err(err) = self.enlarge_invalid_rect(rect) {
log::error!("Window::invalidate_rect - failed to enlarge rect: {}", err);
}
self.redraw_soon();
}
fn set_title(&self, title: &str) {
// This is technically incorrect. STRING encoding is *not* UTF8. However, I am not sure
// what it really is. WM_LOCALE_NAME might be involved. Hopefully, nothing cares about this
// as long as _NET_WM_NAME is also set (which uses UTF8).
log_x11!(self.app.connection().change_property8(
xproto::PropMode::Replace,
self.id,
AtomEnum::WM_NAME,
AtomEnum::STRING,
title.as_bytes(),
));
log_x11!(self.app.connection().change_property8(
xproto::PropMode::Replace,
self.id,
self.atoms._NET_WM_NAME,
self.atoms.UTF8_STRING,
title.as_bytes(),
));
}
fn set_menu(&self, _menu: Menu) {
// TODO(x11/menus): implement Window::set_menu (currently a no-op)
}
fn get_scale(&self) -> Result<Scale, Error> {
// TODO(x11/dpi_scaling): figure out DPI scaling
Ok(Scale::new(1.0, 1.0))
}
pub fn handle_expose(&self, expose: &xproto::ExposeEvent) -> Result<(), Error> {
// TODO(x11/dpi_scaling): when dpi scaling is
// implemented, it needs to be used here too
let rect = Rect::from_origin_size(
(expose.x as f64, expose.y as f64),
(expose.width as f64, expose.height as f64),
);
self.enlarge_invalid_rect(rect)?;
if self.waiting_on_present()? {
self.set_needs_present(true)?;
} else if expose.count == 0 {
self.redraw_soon();
}
Ok(())
}
pub fn handle_key_press(&self, key_press: &xproto::KeyPressEvent) -> Result<(), Error> {
let hw_keycode = key_press.detail;
let code = keycodes::hardware_keycode_to_code(hw_keycode);
let mods = key_mods(key_press.state);
let key = keycodes::code_to_key(code, mods);
let location = keycodes::code_to_location(code);
let state = KeyState::Down;
let key_event = KeyEvent {
code,
key,
mods,
location,
state,
repeat: false,
is_composing: false,
};
borrow_mut!(self.handler)?.key_down(key_event);
Ok(())
}
pub fn handle_button_press(
&self,
button_press: &xproto::ButtonPressEvent,
) -> Result<(), Error> {
let button = mouse_button(button_press.detail);
let mouse_event = MouseEvent {
pos: Point::new(button_press.event_x as f64, button_press.event_y as f64),
// The xcb state field doesn't include the newly pressed button, but
// druid wants it to be included.
buttons: mouse_buttons(button_press.state).with(button),
mods: key_mods(button_press.state),
// TODO: detect the count
count: 1,
focus: false,
button,
wheel_delta: Vec2::ZERO,
};
borrow_mut!(self.handler)?.mouse_down(&mouse_event);
Ok(())
}
pub fn handle_button_release(
&self,
button_release: &xproto::ButtonReleaseEvent,
) -> Result<(), Error> {
let button = mouse_button(button_release.detail);
let mouse_event = MouseEvent {
pos: Point::new(button_release.event_x as f64, button_release.event_y as f64),
// The xcb state includes the newly released button, but druid
// doesn't want it.
buttons: mouse_buttons(button_release.state).without(button),
mods: key_mods(button_release.state),
count: 0,
focus: false,
button,
wheel_delta: Vec2::ZERO,
};
borrow_mut!(self.handler)?.mouse_up(&mouse_event);
Ok(())
}
pub fn handle_wheel(&self, event: &xproto::ButtonPressEvent) -> Result<(), Error> {
let button = event.detail;
let mods = key_mods(event.state);
// We use a delta of 120 per tick to match the behavior of Windows.
let is_shift = mods.shift();
let delta = match button {
4 if is_shift => (-120.0, 0.0),
4 => (0.0, -120.0),
5 if is_shift => (120.0, 0.0),
5 => (0.0, 120.0),
6 => (-120.0, 0.0),
7 => (120.0, 0.0),
_ => return Err(anyhow!("unexpected mouse wheel button: {}", button)),
};
let mouse_event = MouseEvent {
pos: Point::new(event.event_x as f64, event.event_y as f64),
buttons: mouse_buttons(event.state),
mods: key_mods(event.state),
count: 0,
focus: false,
button: MouseButton::None,
wheel_delta: delta.into(),
};
borrow_mut!(self.handler)?.wheel(&mouse_event);
Ok(())
}
pub fn handle_motion_notify(
&self,
motion_notify: &xproto::MotionNotifyEvent,
) -> Result<(), Error> {
let mouse_event = MouseEvent {
pos: Point::new(motion_notify.event_x as f64, motion_notify.event_y as f64),
buttons: mouse_buttons(motion_notify.state),
mods: key_mods(motion_notify.state),
count: 0,
focus: false,
button: MouseButton::None,
wheel_delta: Vec2::ZERO,
};
borrow_mut!(self.handler)?.mouse_move(&mouse_event);
Ok(())
}
pub fn handle_client_message(
&self,
client_message: &xproto::ClientMessageEvent,
) -> Result<(), Error> {
// https://www.x.org/releases/X11R7.7/doc/libX11/libX11/libX11.html#id2745388
// https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#window_deletion
if client_message.type_ == self.atoms.WM_PROTOCOLS && client_message.format == 32 {
let protocol = client_message.data.as_data32()[0];
if protocol == self.atoms.WM_DELETE_WINDOW {
self.close();
}
}
Ok(())
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn handle_destroy_notify(
&self,
_destroy_notify: &xproto::DestroyNotifyEvent,
) -> Result<(), Error> {
borrow_mut!(self.handler)?.destroy();
Ok(())
}
pub fn handle_configure_notify(&self, event: &ConfigureNotifyEvent) -> Result<(), Error> {
self.set_size(Size::new(event.width as f64, event.height as f64))
}
pub fn handle_complete_notify(&self, event: &CompleteNotifyEvent) -> Result<(), Error> {
if let Some(present) = borrow_mut!(self.present_data)?.as_mut() {
// A little sanity check (which isn't worth an early return): we should only have
// one present request in flight, so we should only get notified about the request
// that we're waiting for.
if present.waiting_on != Some(event.serial) {
log::warn!(
"Got a notify for serial {}, but waiting on {:?}",
event.serial,
present.waiting_on
);
}
// Check whether we missed presenting on any frames.
if let Some(last_msc) = present.last_msc {
if last_msc.wrapping_add(1) != event.msc {
log::debug!(
"missed a present: msc went from {} to {}",
last_msc,
event.msc
);
if let Some(last_ust) = present.last_ust {
log::debug!("ust went from {} to {}", last_ust, event.ust);
}
}
}
// Only store the last MSC if we're animating (if we aren't animating, missed MSCs
// aren't interesting).
present.last_msc = if present.needs_present {
Some(event.msc)
} else {
None
};
present.last_ust = Some(event.ust);
present.waiting_on = None;
}
if self.needs_present()? {
self.render()?;
}
Ok(())
}
pub fn handle_idle_notify(&self, event: &IdleNotifyEvent) -> Result<(), Error> {
let mut buffers = borrow_mut!(self.buffers)?;
if buffers.all_pixmaps.contains(&event.pixmap) {
buffers.idle_pixmaps.push(event.pixmap);
} else {
// We must have reallocated the buffers while this pixmap was busy, so free it now.
// Regular freeing happens in `Buffers::free_pixmaps`.
self.app.connection().free_pixmap(event.pixmap)?;
}
Ok(())
}
fn waiting_on_present(&self) -> Result<bool, Error> {
Ok(borrow!(self.present_data)?
.as_ref()
.map(|p| p.waiting_on.is_some())
.unwrap_or(false))
}
fn set_needs_present(&self, val: bool) -> Result<(), Error> {
if let Some(present) = borrow_mut!(self.present_data)?.as_mut() {
present.needs_present = val;
}
Ok(())
}
fn needs_present(&self) -> Result<bool, Error> {
Ok(borrow!(self.present_data)?
.as_ref()
.map(|p| p.needs_present)
.unwrap_or(false))
}
pub(crate) fn run_idle(&self) {
let mut queue = Vec::new();
std::mem::swap(&mut *self.idle_queue.lock().unwrap(), &mut queue);
let mut needs_redraw = false;
if let Ok(mut handler) = self.handler.try_borrow_mut() {
for callback in queue {
match callback {
IdleKind::Callback(f) => {
f.call(handler.as_any());
}
IdleKind::Token(tok) => {
handler.idle(tok);
}
IdleKind::Redraw => {
needs_redraw = true;
}
}