-
Notifications
You must be signed in to change notification settings - Fork 129
/
titlebar.py
2292 lines (1836 loc) · 83.4 KB
/
titlebar.py
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
# The MIT License (MIT)
#
# Copyright (c) <2022-Present> <Alex Huszagh>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
'''
titlebar
========
A full-featured, custom titlebar for a subwindow in an MDI area. This
uses a frameless window hint with a custom titlebar, and event filter
to capture titlebar and frame events. This example can also be easily
applied to a top-level window.
The custom titlebar supports the following:
- Title text
- Title bar with menu, help, min, max, restore, close, shade, and unshade.
- Help, shade, and unshade are optional.
- Menu contains restore, min, max, move, resize, stay on top, and close.
- Custom window minimization.
- Minimized windows can be placed in any corner.
- Windows reposition on resize events to avoid truncating windows.
- Dynamically toggle window state to keep windows above others.
- Drag titlebar to move window
- Double click titlebar to change window state.
- Restores if maximized or minimized.
- Shades or unshades if in normal state and applicable.
- Otherwise, maximizes window.
- Context menu move and resize events.
- Click "Size" to resize from the bottom right based on cursor.
- Click "Move" to move bottom-center of titlebar to cursor.
- Drag to resize on window border with or without size grips.
- If the window contains size grips, use the default behavior.
- Otherwise, monitor mouse and hover events on window border.
- If hovering over window border, draw appropriate resize cursor.
- If clicked on window border, enter resize mode.
- Click again to exit resize mode.
- Custom border width for a window outline.
The following Qt properties ensure proper styling of the UI:
- `isTitlebar`: should be set on the title bar. ensures all widgets
in the title bar have the correct background.
- `isWindow`: set on the window to ensure there is no default border.
- `hasWindowFrame`: set on a window with a border to draw the frame.
The widget choice is very deliberate: any modifications can cause
unexpected changes. `TitleBar` must be a `QFrame` so the background
is filled, but must have a `NoFrame` shape. The window frame should
have `NoFrame` without a border, but should be a `Box` with a border.
Any other more elaborate style, like a `Panel`, won't be rendered
correctly.
NOTE: you cannot correctly emulate a title bar if the desktop environment
is Wayland, even if the app is running in X11 mode. This mostly affects
just the top-level title bar (and subwindows almost entirely work),
but there are a few small issues for subwindows.
The top-level title bar can have a few issues on Wayland.
- Cannot move the window position. This cannot be done even if you know
the compositor (such as kwin).
- Cannot use the menu resize due to `QWidget::mouseGrab()`.
- This plugin supports grabbing the mouse only for popup windows
- The window stops tracking mouse movements past a certain distance.
- Attempting to move the window position causes global position to be wrong.
- Wayland does not support `Stay on Top` directive.
- qt.qpa.wayland: Wayland does not support QWindow::requestActivate()
A few other issues exist on Wayland.
- The menu resize has to guess the mouse position outside of the window bounds.
- This cannot be fixed since we cannot use mouse events if the user
is outside the main window, nor do hover events trigger.
We cannot guess where the user left the main window, since
`QCursor::pos` will not be updated until the user moves the
mouse within the application, so merely resizing until the
actual cursor is within the window won't work.
- We cannot intercept mouse events for the menu resize outside the window.
- This even occurs when forcing X11 on Wayland.
On Windows, only the menu resize event fails. For the subwindow, it stops
tracking outside of the window boundaries, and for the main window, it does
the same, making it practically useless.
# Testing
The current platforms/desktop environments have been tested:
- Gnome (X11, Wayland)
- KDE Plasma (X11, Wayland)
- Windows 10
'''
# pylint: disable=protected-access
import enum
import os
import sys
from pathlib import Path
HOME = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.dirname(HOME))
import shared # noqa # pylint: disable=wrong-import-position,import-error
parser = shared.create_parser()
parser.add_argument(
'--minimize-location',
help='location to minimize windows to in the MDI area',
default='BottomLeft',
choices=['TopLeft', 'TopRight', 'BottomLeft', 'BottomRight'],
)
parser.add_argument(
'--border-width',
help='width of the subwindow borders',
type=int,
choices=range(0, 6),
default=1,
)
parser.add_argument(
'--default-window-frame',
help='use the default title bars',
action='store_true',
)
parser.add_argument(
'--status-bar',
help='use a top-level status bar',
action='store_true',
)
parser.add_argument(
'--window-help',
help='add a top-level context help button',
action='store_true',
)
parser.add_argument(
'--window-shade',
help='add a top-level shade/unshade button',
action='store_true',
)
parser.add_argument(
'--wayland-testing',
help='debug with a custom titlebar on wayland',
action='store_true',
)
args, unknown = shared.parse_args(parser)
QtCore, QtGui, QtWidgets = shared.import_qt(args)
compat = shared.get_compat_definitions(args)
colors = shared.get_colors(args, compat)
ICON_MAP = shared.get_icon_map(compat)
# 100ms between repaints, so we avoid over-repainting.
# Allows us to avoid glitchy motion during drags/
REPAINT_TIMER = 100
TRACK_TIMER = 20
CLICK_TIMER = 20
# Make the titlebar size too large, so we can get the real value with min.
TITLEBAR_HEIGHT = 2**16
# QWIDGETSIZE_MAX isn't exported, which is needed to remove fixedSize constraints.
QWIDGETSIZE_MAX = (1 << 24) - 1
# Determine the Linux display server protocol we're using.
# Use `XDG_SESSION_TYPE`, since we can override it for X11.
IS_WAYLAND = os.environ.get('XDG_SESSION_TYPE') == 'wayland'
IS_XWAYLAND = os.environ.get('XDG_SESSION_TYPE') == 'xwayland'
IS_X11 = os.environ.get('XDG_SESSION_TYPE') == 'x11'
# We can run X11 on Wayland, but this doesn't support certain
# features like mouse grabbing, so we don't use it here.
IS_TRUE_WAYLAND = 'WAYLAND_DISPLAY' in os.environ
USE_WAYLAND_FRAME = IS_WAYLAND and not args.wayland_testing
class MinimizeLocation(enum.IntEnum):
'''Location where to place minimized widgets.'''
TopLeft = 0
TopRight = 1
BottomLeft = 2
BottomRight = 3
class WindowEdge(enum.IntEnum):
'''Enumerations for window edge positions.'''
NoEdge = 0
Top = 1
Bottom = 2
Left = 3
Right = 4
TopLeft = 5
TopRight = 6
BottomLeft = 7
BottomRight = 8
MINIMIZE_LOCATION = getattr(MinimizeLocation, args.minimize_location)
TOP_EDGES = (WindowEdge.Top, WindowEdge.TopLeft, WindowEdge.TopRight)
BOTTOM_EDGES = (WindowEdge.Bottom, WindowEdge.BottomLeft, WindowEdge.BottomRight)
LEFT_EDGES = (WindowEdge.Left, WindowEdge.TopLeft, WindowEdge.BottomLeft)
RIGHT_EDGES = (WindowEdge.Right, WindowEdge.TopRight, WindowEdge.BottomRight)
def standard_icon(widget, icon):
'''Get a standard icon.'''
return shared.standard_icon(args, widget, icon, ICON_MAP)
def menu_icon(widget):
'''Get the menu icon depending on the stylesheet.'''
return standard_icon(widget, compat.SP_TitleBarMenuButton)
def minimize_icon(widget):
'''Get the minimize icon depending on the stylesheet.'''
return standard_icon(widget, compat.SP_TitleBarMinButton)
def maximize_icon(widget):
'''Get the maximize icon depending on the stylesheet.'''
return standard_icon(widget, compat.SP_TitleBarMaxButton)
def restore_icon(widget):
'''Get the restore icon depending on the stylesheet.'''
return standard_icon(widget, compat.SP_TitleBarNormalButton)
def help_icon(widget):
'''Get the help icon depending on the stylesheet.'''
return standard_icon(widget, compat.SP_TitleBarContextHelpButton)
def shade_icon(widget):
'''Get the shade icon depending on the stylesheet.'''
return standard_icon(widget, compat.SP_TitleBarShadeButton)
def unshade_icon(widget):
'''Get the unshade icon depending on the stylesheet.'''
return standard_icon(widget, compat.SP_TitleBarUnshadeButton)
def close_icon(widget):
'''Get the close icon depending on the stylesheet.'''
return standard_icon(widget, compat.SP_TitleBarCloseButton)
def transparent_icon(widget):
'''Create a transparent icon.'''
_ = widget
return QtGui.QIcon()
def action(text, parent=None, icon=None, checkable=None):
'''Create a custom QAction.'''
value = compat.QAction(text, parent)
if icon is not None:
value.setIcon(icon)
if checkable is not None:
value.setCheckable(checkable)
return value
def size_greater(x, y):
'''Compare 2 sizes, determining if any bounds of x are greater than y.'''
return x.width() > y.width() or x.height() > y.height()
def size_less(x, y):
'''Compare 2 sizes, determining if any bounds of x are less than y.'''
return x.width() < y.width() or x.height() < y.height()
# UI WIDGETS
# These are just to populate the views: these could be anything.
class LargeTable(QtWidgets.QTableWidget):
'''Table with a large number of elements.'''
def __init__(self, parent=None):
super().__init__(parent)
self.setColumnCount(100)
self.setRowCount(100)
for index in range(100):
row = QtWidgets.QTableWidgetItem(f'Row {index + 1}')
self.setVerticalHeaderItem(index, row)
column = QtWidgets.QTableWidgetItem(f'Column {index + 1}')
self.setHorizontalHeaderItem(index, column)
class SortableTree(QtWidgets.QTreeWidget):
'''Tree with checkboxes and a sort indicator on the header.'''
def __init__(self, parent=None):
super().__init__(parent)
self.item0 = QtWidgets.QTreeWidgetItem(self)
self.item1 = QtWidgets.QTreeWidgetItem(self)
self.item2 = QtWidgets.QTreeWidgetItem(self.item1)
self.item2.setText(0, 'subitem')
self.item3 = QtWidgets.QTreeWidgetItem(self.item2, ['Row 2.1'])
self.item3.setFlags(self.item3.flags() | compat.ItemIsUserCheckable)
self.item3.setCheckState(0, compat.Unchecked)
self.item4 = QtWidgets.QTreeWidgetItem(self.item2, ['Row 2.2'])
self.item5 = QtWidgets.QTreeWidgetItem(self.item4, ['Row 2.2.1'])
self.item6 = QtWidgets.QTreeWidgetItem(self.item5, ['Row 2.2.1.1'])
self.item7 = QtWidgets.QTreeWidgetItem(self.item5, ['Row 2.2.1.2'])
self.item3.setFlags(self.item7.flags() | compat.ItemIsUserCheckable)
self.item7.setCheckState(0, compat.Checked)
self.item8 = QtWidgets.QTreeWidgetItem(self.item2, ['Row 2.3'])
self.item8.setFlags(self.item8.flags() | compat.ItemIsUserTristate)
self.item8.setCheckState(0, compat.PartiallyChecked)
self.item9 = QtWidgets.QTreeWidgetItem(self, ['Row 3'])
self.item10 = QtWidgets.QTreeWidgetItem(self.item9, ['Row 3.1'])
self.item11 = QtWidgets.QTreeWidgetItem(self, ['Row 4'])
self.headerItem().setText(0, 'qdz')
self.setSortingEnabled(False)
self.topLevelItem(0).setText(0, 'qzd')
self.topLevelItem(1).setText(0, 'effefe')
self.setSortingEnabled(True)
class SettingTabs(QtWidgets.QTabWidget):
'''Sample setting widget with a tab view.'''
def __init__(self, parent=None): # pylint: disable=too-many-statements
super().__init__(parent)
self.setTabPosition(compat.North)
self.general = QtWidgets.QWidget()
self.addTab(self.general, 'General')
self.addTab(QtWidgets.QWidget(), 'Colors')
self.general_layout = QtWidgets.QGridLayout(self.general)
self.general_layout.setColumnStretch(3, 10)
for row in range(1, 10):
self.general_layout.setRowStretch(row, 1)
self.general_layout.setRowStretch(7, 10)
# Add the data folder hboxlayout
self.general_layout.addWidget(QtWidgets.QLabel('Data Folder'), 0, 0)
self.data_folder = QtWidgets.QLineEdit(str(Path.home()))
self.general_layout.addWidget(self.data_folder, 0, 1, 1, 3)
self.file_dialog = QtWidgets.QPushButton('...', checkable=False)
self.general_layout.addWidget(self.file_dialog, 0, 4)
self.file_dialog.clicked.connect(self.launch_filedialog)
# Add default font.
app = QtWidgets.QApplication.instance()
self.general_layout.addWidget(QtWidgets.QLabel('Default Font'), 1, 0)
self.font_value = QtWidgets.QLineEdit(app.font().family())
self.general_layout.addWidget(self.font_value, 1, 1, 1, 3)
self.font_dialog = QtWidgets.QPushButton('...', checkable=False)
self.general_layout.addWidget(self.font_dialog, 1, 4)
self.font_dialog.clicked.connect(lambda _: self.launch_fontdialog(self.font_value))
# Add item label font
self.general_layout.addWidget(QtWidgets.QLabel('Item Label Font'), 2, 0)
self.item_label_value = QtWidgets.QLineEdit(app.font().family())
self.general_layout.addWidget(self.item_label_value, 2, 1, 1, 3)
self.item_label_dialog = QtWidgets.QPushButton('...', checkable=False)
self.general_layout.addWidget(self.item_label_dialog, 2, 4)
self.item_label_dialog.clicked.connect(lambda _: self.launch_fontdialog(self.item_label_value))
# Add the "Show Grid" QCheckbox.
self.grid = QtWidgets.QCheckBox('Show grid', self.general)
self.general_layout.addWidget(self.grid, 3, 2, 1, 1)
# Grid square size.
self.grid_size = QtWidgets.QLabel('Grid Square Size', self.general)
self.general_layout.addWidget(self.grid_size, 4, 0, 1, 2)
self.grid_spin = QtWidgets.QSpinBox(self.general)
self.grid_spin.setValue(16)
self.general_layout.addWidget(self.grid_spin, 4, 2, 1, 1)
# Add units of measurement
self.units = QtWidgets.QLabel('Default length unit of measurement', self.general)
self.general_layout.addWidget(self.units, 5, 0, 1, 2)
self.units_combo = QtWidgets.QComboBox()
self.units_combo.addItem('Inches')
self.units_combo.addItem('Foot')
self.units_combo.addItem('Meter')
self.general_layout.addWidget(self.units_combo, 5, 2, 1, 1)
# Add the alignment options
self.align_combo = QtWidgets.QComboBox()
self.align_combo.addItem('Align Top')
self.align_combo.addItem('Align Bottom')
self.align_combo.addItem('Align Left')
self.align_combo.addItem('Align Right')
self.align_combo.addItem('Align Center')
self.general_layout.addWidget(self.align_combo, 6, 0, 1, 2)
self.word_wrap = QtWidgets.QCheckBox('Word Wrap', self.general)
self.general_layout.addWidget(self.word_wrap, 6, 2, 1, 1)
def launch_filedialog(self):
'''Launch the file dialog and store the folder.'''
dialog = QtWidgets.QFileDialog()
dialog.setFileMode(compat.Directory)
dialog.setOption(compat.FileDontUseNativeDialog)
dialog.setDirectory(self.data_folder.text())
if shared.execute(args, dialog):
self.data_folder.setText(dialog.selectedFiles()[0])
def launch_fontdialog(self, edit):
'''Launch our font selection disablog.'''
initial = QtGui.QFont()
initial.setFamily(edit.text())
font, ok = QtWidgets.QFontDialog.getFont(initial)
if ok:
edit.setText(font.family())
# RESIZE HELPERS
def border_size(self):
'''Get the size of the border, regardless if present.'''
return QtCore.QSize(2 * self._border, 2 * self._border)
def minimized_content_size(self):
'''Get the minimum content size of the widget.'''
return self._titlebar_size
def minimized_size(self):
'''Get the minimum size of the widget, with the size grips hidden.'''
size = self.minimized_content_size
if self._border:
size = size + self.border_size
return size
def minimum_size(self):
'''Get the minimum size for the widget.'''
size = self.minimized_size
if getattr(self, '_sizegrip', None) is not None and self._sizegrip.isVisible():
# Don't modify in place: percolates later.
size = size + self._sizegrip_size
if getattr(self, '_statusbar', None) is not None and self._statusbar.isVisible():
size = size + self._statusbar_size
return size
def get_larger_size(x, y):
'''Get the larger of the two sizes, for both the height and width.'''
return QtCore.QSize(max(x.width(), y.width()), max(x.height(), y.height()))
def set_minimum_size(self):
'''Sets the minimum size of the window and the titlebar, with clobbering.'''
self._old_minimum_size = self.minimumSize()
self._titlebar.set_minimum_size()
self._titlebar_size = self._titlebar.minimumSize()
self.setMinimumSize(self.minimum_size)
def set_larger_minimum_size(self):
'''Sets the minimum size of the window and the titlebar, without clobbering.'''
if self._old_minimum_size is not None:
self.setMinimumSize(self._old_minimum_size)
self._titlebar.set_minimum_size()
self._titlebar_size = self._titlebar.minimumSize()
size = get_larger_size(self.minimum_size, self.minimumSize())
self.setMinimumSize(size)
def move_to(self, position):
'''Move the window to the desired position'''
# Also updates the stored previous subwindow position, if applicable.
# This means shading/unshading uses the new position of the window,
# but the old sizes, rather than jump the window back.
# NOTICE: this fails on Wayland. Worse, using `QMainWindow::move` on
# Wayland causes the cursor position to be incorrect, causing issues
# with other events.
if IS_WAYLAND and self.window() == self:
return
self.move(position)
rect = self._titlebar._window_rect
if rect is not None:
rect.moveTo(position)
def set_geometry(self, rect):
'''Set the window geometry.'''
# See `move_to` for documentation.
self.resize(rect.size())
window_rect = self._titlebar._window_rect
if window_rect is not None:
window_rect.setSize(rect.size())
move_to(self, rect.topLeft())
def shade(self, size, grip_type):
'''Shade the window, hiding the main widget and size grip.'''
self._widget.hide()
if getattr(self, f'_{grip_type}') is not None:
getattr(self, f'_{grip_type}').hide()
self.set_minimum_size()
self.resize(size)
def unshade(self, rect, grip_type):
'''Unshade the window, showing the main widget and size grip.'''
self._widget.show()
if getattr(self, f'_{grip_type}') is not None:
getattr(self, f'_{grip_type}').show()
self.set_larger_minimum_size()
self.set_geometry(rect)
def start_drag(self, event, window_type):
'''Start the window drag state.'''
setattr(self, f'_{window_type}_drag', event.pos())
def handle_drag(self, event, window, window_type):
'''Handle the window drag event.'''
position = event.pos() - getattr(window, f'_{window_type}_drag')
self.move_to(self.mapToParent(position))
def end_drag(self, window_type):
'''End the window drag state.'''
setattr(self, f'_{window_type}_drag', None)
def start_move(self, widget, window_type):
'''Start the window move state.'''
setattr(self, f'_{window_type}_move', widget)
widget.menu_move_to(QtGui.QCursor.pos())
def handle_move(self, position, window_type):
'''Handle the window move event.'''
getattr(self, f'_{window_type}_move').menu_move_to(position)
def end_move(self, window_type):
'''End the window move state.'''
setattr(self, f'_{window_type}_move', None)
def start_resize(self, window, window_type):
'''Start the window resize state.'''
# NOTE: We can't use a rubber band with mouse tracking,
# since mouse events only occurs if the user is holding
# down the house. Simulating a mouse click isn't enough,
# even if it sends a mouse press without a release.
setattr(self, f'_{window_type}_resize', window)
self.window().setCursor(compat.SizeFDiagCursor)
self.menu_size_to(QtGui.QCursor.pos())
# Grab the mouse so we can intercept the click event,
# and track hover events outside the app. This doesn't
# work on Wayland or on macOS. On Windows, it only works
# within the window owned by the process.
# https://doc.qt.io/qt-6/qwidget.html#grabMouse
if not IS_TRUE_WAYLAND and sys.platform != 'darwin':
self.window().grabMouse()
def handle_resize(self, position):
'''Handle the window resize event.'''
self.menu_size_to(position)
def end_resize(self, window_type):
'''End the window resize state.'''
window = getattr(self, f'_{window_type}_resize')
if window is None:
return
setattr(self, f'_{window_type}_resize', None)
window.window().unsetCursor()
if not IS_TRUE_WAYLAND and sys.platform != 'darwin':
self.window().releaseMouse()
def start_frame(self, frame, window_type):
'''Start the window frame resize state.'''
setattr(self, f'_{window_type}_frame', frame)
def handle_frame(self, window, event, window_type):
'''Handle the window frame resize event.'''
# Check if use size grips, return early.
frame = getattr(window, '_sizeframe', None)
if frame is None:
return
self.frame_event(event, frame)
# Store if the frame state is active.
if frame.is_active and not getattr(self, f'_{window_type}_frame'):
start_frame(self, frame, window_type)
elif not frame.is_active and getattr(self, f'_{window_type}_frame'):
end_frame(self, window_type)
def end_frame(self, window_type):
'''End the window frame resize state.'''
setattr(self, f'_{window_type}_frame', None)
# EVENT HANDLES
def window_resize_event(self, event):
'''Ensure titlebar text elides normally.'''
# Need to trigger the titlebar title resize. Need to handle it
# here, since the SizeFrame resizes won't always trigger a
# Label::resizeEvent, which can cause the text to stay elided.
title_timer = self._titlebar._title._timer
title_timer.start(REPAINT_TIMER)
super(type(self), self).resizeEvent(event)
def window_show_event(self, event, grip_type):
'''Set the minimum size policies once the widgets are shown.'''
# Until shown, the size grip has inaccurate sizes.
# Set the minimum size policy of the widget.
# The show event occurs just after everything is shown,
# so the widget sizes (and isVisible) are accurate.
self._titlebar_size = self._titlebar.minimumSize()
if getattr(self, f'_{grip_type}') is not None:
grip_size = getattr(self, f'_{grip_type}').sizeHint()
setattr(self, f'_{grip_type}_size', QtCore.QSize(0, grip_size.height()))
size = get_larger_size(self.minimum_size, self.minimumSize())
self.setMinimumSize(size)
super(type(self), self).showEvent(event)
def window_mouse_double_click_event(self, event):
'''Override the mouse double click, and don't call the press event.'''
# By default, the flowchart for titlebar double clicks is as follows:
# 1. If minimized, restore
# 2. If maximized, restore
# 3. If no state and can shade, shade
# 4. If no state and cannot shade, maximize
# 5. If shaded, unshade.
widget = self._titlebar
if not widget.underMouse() or event.button() != compat.LeftButton:
return super(type(self), self).mouseDoubleClickEvent(event)
if widget._is_shaded:
return widget.unshade()
if widget.isMinimized() or widget.isMaximized():
return widget.restore()
if widget._has_shade:
return widget.shade()
return widget.maximize()
def window_mouse_press_event(self, event, window, window_type):
'''Override a mouse click on the titlebar to allow a move.'''
widget = self._titlebar
if widget.underMouse():
# `self.window()._subwindow_move` cannot be set, since we're inside
# the global event filter here. We handle conflicts here,
# so only one of the 4 states can be set. We can't move
# minimized widgets, so don't try.
is_left = event.button() == compat.LeftButton
is_minimized = self.isMinimized() and not widget._is_shaded
has_frame = getattr(window, f'_{window_type}_frame') is not None
if is_left and not is_minimized and not has_frame:
start_drag(self.window(), event, window_type)
elif event.button() == compat.RightButton:
position = shared.single_point_global_position(args, event)
shared.execute(args, widget._main_menu, position)
return super(type(self), self).mousePressEvent(event)
def window_mouse_move_event(self, event, window, window_type):
'''Reposition the window on the move event.'''
if getattr(window, f'_{window_type}_frame') is not None:
end_drag(window, window_type)
if getattr(window, f'_{window_type}_drag') is not None:
handle_drag(self, event, window, window_type)
return super(type(self), self).mouseMoveEvent(event)
def window_mouse_release_event(self, event, window, window_type):
'''End the drag event.'''
end_drag(window, window_type)
return super(type(self), self).mouseReleaseEvent(event)
# WINDOW WIDGETS
class Label(QtWidgets.QLabel):
'''Custom QLabel-like class that allows text elision.'''
def __init__(
self,
text='',
parent=None,
elide=compat.ElideNone,
width_cb=None,
):
super().__init__(text, parent)
self._text = text
self._elide = elide
self._width_cb = width_cb
self._timer = QtCore.QTimer()
self._timer.setSingleShot(True)
self._timer.timeout.connect(self.elide)
def text(self):
'''Get the internal text for the label.'''
return self._text
def setText(self, text):
'''Override the set text event to store the text internally.'''
# Need to set the text first, otherwise
# the `width()` might be too small.
self._text = text
super().setText(text)
self.elide()
def elideMode(self):
'''Get the elide mode for the label.'''
return self._elide
def setElideMode(self, elide):
'''Set the elide mode for the label.'''
self._elide = elide
def elide(self):
'''Elide the text in the QLabel.'''
# The width estimate might not be valid: check the callback.
width = self.width()
if self._width_cb is not None:
width = self._width_cb()
metrics = QtGui.QFontMetrics(self.font())
elided = metrics.elidedText(self._text, self._elide, width)
super().setText(elided)
class TitleButton(QtWidgets.QToolButton):
'''An icon-only button, without borders, for the titlebar.'''
def __init__(self, icon, parent=None):
super().__init__()
_ = parent
self.setIcon(icon)
self.setAutoRaise(True)
class TitleBar(QtWidgets.QFrame):
'''Custom instance of a QTitlebar'''
def __init__(self, window, parent=None, flags=None): # pylint: disable=(too-many-statements
super().__init__(parent)
# Get and set some properties.
self.setProperty('isTitlebar', True)
self._window = window
self._window_type = 'window'
if isinstance(self._window, SubWindow):
self._window_type = 'subwindow'
self._state = compat.WindowNoState
self._window_rect = None
self._has_help = False
self._has_shade = False
self._is_shaded = False
self._has_shown = False
self._title_column = None
self._move_timer = QtCore.QTimer()
self._move_timer.setSingleShot(True)
self._move_timer.timeout.connect(self.menu_move)
self._size_timer = QtCore.QTimer()
self._size_timer.setSingleShot(True)
self._size_timer.timeout.connect(self.menu_size)
if flags is not None:
self._has_help = bool(flags & compat.WindowContextHelpButtonHint)
self._has_shade = bool(flags & compat.WindowShadeButtonHint)
# Create our widgets.
self._layout = QtWidgets.QGridLayout(self)
self._menu = TitleButton(menu_icon(self))
self._title = Label('', self, compat.ElideRight, self.title_width)
self._min = TitleButton(minimize_icon(self))
self._max = TitleButton(maximize_icon(self))
self._restore = TitleButton(restore_icon(self))
self._close = TitleButton(close_icon(self))
if self._has_help:
self._help = TitleButton(help_icon(self))
if self._has_shade:
self._shade = TitleButton(shade_icon(self))
self._unshade = TitleButton(unshade_icon(self))
# Add actions to our menu.
self._menu.setPopupMode(compat.InstantPopup)
self._main_menu = QtWidgets.QMenu(self)
self._restore_action = action('&Restore', self, restore_icon(self))
self._restore_action.triggered.connect(self.restore)
self._move_action = action('&Move', self, transparent_icon(self))
self._move_action.triggered.connect(self.move_timer)
self._size_action = action('&Size', self, transparent_icon(self))
self._size_action.triggered.connect(self.size_timer)
self._min_action = action('Mi&nimize', self, minimize_icon(self))
self._min_action.triggered.connect(self.minimize)
self._max_action = action('Ma&ximize', self, maximize_icon(self))
self._max_action.triggered.connect(self.maximize)
self._top_action = action('Stay on &Top', self, checkable=True)
self._top_action.toggled.connect(self.toggle_keep_above)
self._close_action = action('&Close', self, close_icon(self))
self._close_action.triggered.connect(self._window.close)
self._main_menu.addActions(
[
self._restore_action,
self._move_action,
self._size_action,
self._min_action,
self._max_action,
self._top_action,
]
)
self._main_menu.addSeparator()
self._main_menu.addAction(self._close_action)
self._menu.setMenu(self._main_menu)
# Customize the enabled items.
self._restore_action.setEnabled(False)
# Create our layout.
col = 0
self._layout.addWidget(self._menu, 0, col)
col += 1
self._layout.addWidget(self._title, 0, col, compat.AlignHCenter)
self._layout.setColumnStretch(col, 1)
self._title_column = col
col += 1
if self._has_help:
self._layout.addWidget(self._help, 0, col)
col += 1
self._layout.addWidget(self._min, 0, col)
self._state1_column = col
col += 1
self._layout.addWidget(self._max, 0, col)
self._state2_column = col
col += 1
if self._has_shade:
self._layout.addWidget(self._shade, 0, col)
col += 1
self._layout.addWidget(self._close, 0, col)
self._close_column = col
self._restore.hide()
if self._has_shade:
self._unshade.hide()
# Add in our event triggers.
self._min.clicked.connect(self.minimize)
self._max.clicked.connect(self.maximize)
self._restore.clicked.connect(self.restore)
self._close.clicked.connect(self._window.close)
if self._has_help:
self._help.clicked.connect(self.help)
if self._has_shade:
self._shade.clicked.connect(self.shade)
self._unshade.clicked.connect(self.unshade)
# PROPERTIES
@property
def minimum_width(self):
'''Get the height (in pixels) for the minimum title bar width.'''
app = QtWidgets.QApplication.instance()
icon_width = self._menu.iconSize().width()
font_size = app.font().pointSizeF()
# We can have 4-6 icons, which with padding means we need
# room for at least 10 characters.
return 6 * icon_width + int(16 * font_size)
@property
def minimum_height(self):
'''Get the height (in pixels) for the minimum title bar height.'''
return TITLEBAR_HEIGHT
@property
def minimum_size(self):
'''Get the minimum dimensions for the title bar.'''
return QtCore.QSize(self.minimum_width, self.minimum_height)
def title_width(self):
'''Get the width of the title based on the grid layout.'''
return self._layout.cellRect(0, self._title_column).width()
# QT-LIKE PROPERTIES
def windowTitle(self):
'''Get the titlebar's window title.'''
return self._title.text()
def setWindowTitle(self, title):
'''Get the titlebar's window title.'''
self._title.setText(title)
def isNormal(self):
'''Get if the titlebar and therefore window has no state.'''
return self._state == compat.WindowNoState
def isMinimized(self):
'''Get if the titlebar and therefore window is minimized.'''
return self._state == compat.WindowMinimized
def isMaximized(self):
'''Get if the titlebar and therefore window is maximized.'''
return self._state == compat.WindowMaximized
# QT EVENTS
def showEvent(self, event):
'''Set the minimum size policies once the widgets are shown.'''
global TITLEBAR_HEIGHT
if not self._has_shown:
TITLEBAR_HEIGHT = min(self.height(), TITLEBAR_HEIGHT)
self._has_shown = True
# Set some size policies.
self.setMinimumSize(self.minimum_width, self.minimum_height)
super().showEvent(event)
# ACTIONS
def set_minimum_size(self):
'''Set the minimum size of the titlebar.'''
self.setMinimumSize(self.minimum_width, self.minimum_height)
def move_timer(self):
'''Start timer to invoke menu_move.'''
# We use a timer since the clicks on the menu can invoke the
# MousePressEvent, which instantly cancels the move event.
self._move_timer.start(CLICK_TIMER)
def menu_move(self):
'''Start a manually trigger move.'''
start_move(self.window(), self, self._window_type)
def menu_move_to(self, global_position):
'''
Move the subwindow so that the position is in the center bottom
of the title bar. The position is given in global coordinates.
'''
# Move it so the position is right below the bottom and the center.
position = self.mapFromGlobal(global_position)
rect = self.geometry()
x = position.x() - rect.width() // 2
y = position.y()
rect.moveBottomLeft(QtCore.QPoint(x, y))