-
-
Notifications
You must be signed in to change notification settings - Fork 687
/
window.py
953 lines (800 loc) · 34.7 KB
/
window.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
from __future__ import annotations
import warnings
from builtins import id as identifier
from collections.abc import Coroutine, Iterator
from pathlib import Path
from typing import TYPE_CHECKING, Any, MutableSet, Protocol, TypeVar
import toga
from toga import dialogs
from toga.command import CommandSet
from toga.constants import WindowState
from toga.handlers import AsyncResult, wrapped_handler
from toga.images import Image
from toga.platform import get_platform_factory
from toga.types import Position, Size
if TYPE_CHECKING:
from toga.app import App
from toga.images import ImageT
from toga.screens import Screen
from toga.types import PositionT, SizeT
from toga.widgets.base import Widget
_window_count = -1
def _initial_position() -> Position:
"""Compute a cascading initial position for platforms that don't have a native
implementation.
This is a stateful method; each time it is invoked, it will yield a new initial
position.
:returns: The position for the new window.
"""
# Each new window created without an explicit position is positioned
# 50px down and to the right from the previous window, with the first
# window positioned at (100, 100). Every 15 windows, move back to a
# y coordinate of 100, and start from 50 pixels further right.
global _window_count
_window_count += 1
pos = 100 + (_window_count % 15) * 50
return Position(pos + (_window_count // 15 * 50), pos)
class FilteredWidgetRegistry:
# A class that exposes a mapping lookup interface, filtered to widgets from a single
# window. The underlying data store is on the app.
def __init__(self, window: Window) -> None:
self._window = window
def __len__(self) -> int:
return len(list(self.items()))
def __getitem__(self, key: str) -> Widget:
item = self._window.app.widgets[key]
if item.window != self._window:
raise KeyError(key)
return item
def __contains__(self, key: str) -> bool:
try:
item = self._window.app.widgets[key]
return item.window == self._window
except KeyError:
return False
def __iter__(self) -> Iterator[Widget]:
return iter(self.values())
def __repr__(self) -> str:
return "{" + ", ".join(f"{k!r}: {v!r}" for k, v in sorted(self.items())) + "}"
def items(self) -> Iterator[tuple[str, Widget]]:
for item in self._window.app.widgets.items():
if item[1].window == self._window:
yield item
def keys(self) -> Iterator[str]:
for item in self._window.app.widgets.items():
if item[1].window == self._window:
yield item[0]
def values(self) -> Iterator[Widget]:
for item in self._window.app.widgets.items():
if item[1].window == self._window:
yield item[1]
class OnCloseHandler(Protocol):
def __call__(self, window: Window, /, **kwargs: Any) -> bool:
"""A handler to invoke when a window is about to close.
The return value of this callback controls whether the window is allowed to close.
This can be used to prevent a window closing with unsaved changes, etc.
:param window: The window instance that is closing.
:param kwargs: Ensures compatibility with arguments added in future versions.
:returns: ``True`` if the window is allowed to close; ``False`` if the window
is not allowed to close.
"""
_DialogResultT = TypeVar("_DialogResultT")
class DialogResultHandler(Protocol[_DialogResultT]):
def __call__(
self, window: Window, result: _DialogResultT, /, **kwargs: Any
) -> object:
"""A handler to invoke when a dialog is closed.
:param window: The window that opened the dialog.
:param kwargs: Ensures compatibility with arguments added in future versions.
:param result: The result returned by the dialog.
"""
class Dialog(AsyncResult):
RESULT_TYPE = "dialog"
def __init__(self, window: Window, on_result: DialogResultHandler[Any]):
super().__init__(on_result=on_result)
self.window = window
self.app = window.app
class Window:
_WINDOW_CLASS = "Window"
def __init__(
self,
id: str | None = None,
title: str | None = None,
position: PositionT | None = None,
size: SizeT = Size(640, 480),
resizable: bool = True,
closable: bool = True,
minimizable: bool = True,
on_close: OnCloseHandler | None = None,
content: Widget | None = None,
resizeable: None = None, # DEPRECATED
closeable: None = None, # DEPRECATED
) -> None:
"""Create a new Window.
:param id: A unique identifier for the window. If not provided, one will be
automatically generated.
:param title: Title for the window. Defaults to the formal name of the app.
:param position: Position of the window, as a :any:`toga.Position` or tuple of
``(x, y)`` coordinates, in :ref:`CSS pixels <css-units>`.
:param size: Size of the window, as a :any:`toga.Size` or tuple of ``(width,
height)``, in :ref:`CSS pixels <css-units>`.
:param resizable: Can the window be resized by the user?
:param closable: Can the window be closed by the user?
:param minimizable: Can the window be minimized by the user?
:param on_close: The initial :any:`on_close` handler.
:param content: The initial content for the window.
:param resizeable: **DEPRECATED** - Use ``resizable``.
:param closeable: **DEPRECATED** - Use ``closable``.
"""
######################################################################
# 2023-08: Backwards compatibility
######################################################################
if resizeable is not None:
warnings.warn(
"Window.resizeable has been renamed Window.resizable",
DeprecationWarning,
)
resizable = resizeable
if closeable is not None:
warnings.warn(
"Window.closeable has been renamed Window.closable",
DeprecationWarning,
)
closable = closeable
######################################################################
# End backwards compatibility
######################################################################
# Needs to be a late import to avoid circular dependencies.
from toga import App
self._id = str(id if id else identifier(self))
self._impl: Any = None
self._content: Widget | None = None
self._closed = False
self._resizable = resizable
self._closable = closable
self._minimizable = minimizable
# The app needs to exist before windows are created. _app will only be None
# until the window is added to the app below.
self._app: App = None
if App.app is None:
raise RuntimeError("Cannot create a Window before creating an App")
self.factory = get_platform_factory()
self._impl = getattr(self.factory, self._WINDOW_CLASS)(
interface=self,
title=title if title else self._default_title,
position=None if position is None else Position(*position),
size=Size(*size),
)
# Add the window to the app
App.app.windows.add(self)
# If content has been provided, set it
if content:
self.content = content
self.on_close = on_close
def __lt__(self, other: Window) -> bool:
return self.id < other.id
######################################################################
# Window properties
######################################################################
@property
def app(self) -> App:
"""The :any:`App` that this window belongs to (read-only).
New windows are automatically associated with the currently active app."""
return self._app
@app.setter
def app(self, app: App) -> None:
if self._app:
raise ValueError("Window is already associated with an App")
self._app = app
self._impl.set_app(app._impl)
@property
def closable(self) -> bool:
"""Can the window be closed by the user?"""
return self._closable
@property
def id(self) -> str:
"""A unique identifier for the window."""
return self._id
@property
def minimizable(self) -> bool:
"""Can the window be minimized by the user?"""
return self._minimizable
@property
def resizable(self) -> bool:
"""Can the window be resized by the user?"""
return self._resizable
@property
def _default_title(self) -> str:
return toga.App.app.formal_name
@property
def title(self) -> str:
"""Title of the window. If no title is provided, the title will default to
"Toga"."""
return self._impl.get_title()
@title.setter
def title(self, title: str) -> None:
if not title:
title = self._default_title
self._impl.set_title(str(title).split("\n")[0])
######################################################################
# Window lifecycle
######################################################################
def close(self) -> None:
"""Close the window.
This *does not* invoke the ``on_close`` handler. If the window being closed
is the app's main window, it will trigger ``on_exit`` handling; otherwise, the
window will be immediately and unconditionally closed.
Once a window has been closed, it *cannot* be reused. The behavior of any method
or property on a :class:`~toga.Window` instance after it has been closed is
undefined, except for :attr:`closed` which can be used to check if the window
was closed.
:returns: True if the window was actually closed; False if closing the window
triggered ``on_exit`` handling.
"""
close_window = True
if self.app.main_window == self:
# Closing the window marked as the main window is a request to exit.
self.app.request_exit()
close_window = False
elif self.app.main_window is None:
# If this is an app without a main window, the app is running, this
# is the last window in the app, and the platform exits on last
# window close, request an exit.
if (
len(self.app.windows) == 1
and self.app._impl.CLOSE_ON_LAST_WINDOW
and self.app.loop.is_running()
):
self.app.request_exit()
close_window = False
if close_window:
self._close()
# Return whether the window was actually closed
return close_window
def _close(self):
# The actual logic for closing a window. This is abstracted so that the testbed
# can monkeypatch this method, recording the close request without actually
# closing the app.
# Restore to normal state if in presentation mode. On some backends (e.g., Cocoa),
# the content is in presentation mode, not the window. Closing the window directly
# can cause rendering glitches.
if self.state == WindowState.PRESENTATION:
self.state = WindowState.NORMAL
if self.content:
self.content.window = None
self.app.windows.discard(self)
self._impl.close()
self._closed = True
@property
def closed(self) -> bool:
"""Whether the window was closed."""
return self._closed
def show(self) -> None:
"""Show the window. If the window is already visible, this method has no
effect."""
self._impl.show()
######################################################################
# Window content and resources
######################################################################
@property
def content(self) -> Widget | None:
"""Content of the window. On setting, the content is added to the same app as
the window."""
return self._content
@content.setter
def content(self, widget: Widget) -> None:
# Set window of old content to None
if self._content:
self._content.window = None
# Assign the content widget to the same app as the window.
widget.app = self.app
# Assign the content widget to the window.
widget.window = self
# Track our new content
self._content = widget
# Manifest the widget
self._impl.set_content(widget._impl)
# Update the geometry of the widget
widget.refresh()
@property
def widgets(self) -> FilteredWidgetRegistry:
"""The widgets contained in the window.
Can be used to look up widgets by ID (e.g., ``window.widgets["my_id"]``).
"""
return FilteredWidgetRegistry(self)
######################################################################
# Window size
######################################################################
@property
def size(self) -> Size:
"""Size of the window, in :ref:`CSS pixels <css-units>`."""
return self._impl.get_size()
@size.setter
def size(self, size: SizeT) -> None:
self._impl.set_size(size)
if self.content:
self.content.refresh()
######################################################################
# Window position
######################################################################
@property
def position(self) -> Position:
"""Absolute position of the window, in :ref:`CSS pixels <css-units>`.
The origin is the top left corner of the primary screen.
"""
absolute_origin = self._app.screens[0].origin
absolute_window_position = self._impl.get_position()
window_position = absolute_window_position - absolute_origin
return window_position
@position.setter
def position(self, position: PositionT) -> None:
absolute_origin = self._app.screens[0].origin
absolute_new_position = Position(*position) + absolute_origin
self._impl.set_position(absolute_new_position)
@property
def screen(self) -> Screen:
"""Instance of the :class:`toga.Screen` on which this window is present."""
return self._impl.get_current_screen().interface
@screen.setter
def screen(self, app_screen: Screen) -> None:
original_window_location = self.position
original_origin = self.screen.origin
new_origin = app_screen.origin
self._impl.set_position(original_window_location - original_origin + new_origin)
@property
def screen_position(self) -> Position:
"""Position of the window with respect to current screen, in
:ref:`CSS pixels <css-units>`."""
return self.position - self.screen.origin
@screen_position.setter
def screen_position(self, position: PositionT) -> None:
new_relative_position = Position(*position) + self.screen.origin
self._impl.set_position(new_relative_position)
######################################################################
# Window visibility
######################################################################
def hide(self) -> None:
"""Hide the window. If the window is already hidden, this method has no
effect."""
self._impl.hide()
@property
def visible(self) -> bool:
"""Is the window visible?"""
return self._impl.get_visible()
@visible.setter
def visible(self, visible: bool) -> None:
if visible:
self.show()
else:
self.hide()
######################################################################
# Window state
######################################################################
@property
def state(self) -> WindowState:
"""The current state of the window."""
return self._impl.get_window_state()
@state.setter
def state(self, state: WindowState) -> None:
if not self.resizable and state in {
WindowState.MAXIMIZED,
WindowState.FULLSCREEN,
WindowState.PRESENTATION,
}:
raise ValueError(
f"A non-resizable window cannot be set to a state of {state}."
)
else:
# State checks are handled by the backend to accommodate for
# non-blocking native OS calls(e.g., Cocoa). Performing these
# checks at the core level could result in incorrect inferences,
# as non-blocking OS calls may not have completed at the time
# the core checks the current state. This could lead to incorrect
# assertions and potential glitches.
self._impl.set_window_state(state)
######################################################################
# Window capabilities
######################################################################
def as_image(self, format: type[ImageT] = Image) -> ImageT:
"""Render the current contents of the window as an image.
:param format: Format to provide. Defaults to :class:`~toga.images.Image`; also
supports :any:`PIL.Image.Image` if Pillow is installed, as well as any image
types defined by installed :doc:`image format plugins
</reference/plugins/image_formats>`.
:returns: An image containing the window content, in the format requested.
"""
return Image(self._impl.get_image_data()).as_format(format)
async def dialog(self, dialog) -> Coroutine[None, None, Any]:
"""Display a dialog to the user, modal to this window.
:param: The :doc:`dialog <resources/dialogs>` to display to the user.
:returns: The result of the dialog.
"""
return await dialog._show(self)
######################################################################
# Window events
######################################################################
@property
def on_close(self) -> OnCloseHandler | None:
"""The handler to invoke if the user attempts to close the window."""
return self._on_close
@on_close.setter
def on_close(self, handler: OnCloseHandler | None) -> None:
def cleanup(window: Window, should_close: bool) -> None:
if should_close or handler is None:
window.close()
self._on_close = wrapped_handler(self, handler, cleanup=cleanup)
######################################################################
# 2024-06: Backwards compatibility
######################################################################
def info_dialog(
self,
title: str,
message: str,
on_result: DialogResultHandler[None] | None = None,
) -> Dialog:
"""**DEPRECATED** - await :meth:`dialog` with an :any:`InfoDialog`"""
######################################################################
# 2024-06: Backwards compatibility
######################################################################
warnings.warn(
"info_dialog(...) has been deprecated; use dialog(toga.InfoDialog(...))",
DeprecationWarning,
)
######################################################################
# End Backwards compatibility
######################################################################
result = Dialog(
self,
on_result=wrapped_handler(self, on_result) if on_result else None,
)
result.dialog = dialogs.InfoDialog(title, message)
result.dialog._impl.show(self, result)
return result
def question_dialog(
self,
title: str,
message: str,
on_result: DialogResultHandler[bool] | None = None,
) -> Dialog:
"""**DEPRECATED** - await :meth:`dialog` with a :any:`QuestionDialog`"""
######################################################################
# 2024-06: Backwards compatibility
######################################################################
warnings.warn(
"question_dialog(...) has been deprecated; use dialog(toga.QuestionDialog(...))",
DeprecationWarning,
)
######################################################################
# End Backwards compatibility
######################################################################
result = Dialog(
self,
on_result=wrapped_handler(self, on_result) if on_result else None,
)
result.dialog = dialogs.QuestionDialog(title, message)
result.dialog._impl.show(self, result)
return result
def confirm_dialog(
self,
title: str,
message: str,
on_result: DialogResultHandler[bool] | None = None,
) -> Dialog:
"""**DEPRECATED** - await :meth:`dialog` with a :any:`ConfirmDialog`"""
######################################################################
# 2024-06: Backwards compatibility
######################################################################
warnings.warn(
"confirm_dialog(...) has been deprecated; use dialog(toga.ConfirmDialog(...))",
DeprecationWarning,
)
######################################################################
# End Backwards compatibility
######################################################################
result = Dialog(
self,
on_result=wrapped_handler(self, on_result) if on_result else None,
)
result.dialog = dialogs.ConfirmDialog(title, message)
result.dialog._impl.show(self, result)
return result
def error_dialog(
self,
title: str,
message: str,
on_result: DialogResultHandler[None] | None = None,
) -> Dialog:
"""**DEPRECATED** - await :meth:`dialog` with an :any:`ErrorDialog`"""
######################################################################
# 2024-06: Backwards compatibility
######################################################################
warnings.warn(
"error_dialog(...) has been deprecated; use dialog(toga.ErrorDialog(...))",
DeprecationWarning,
)
######################################################################
# End Backwards compatibility
######################################################################
result = Dialog(
self,
on_result=wrapped_handler(self, on_result) if on_result else None,
)
result.dialog = dialogs.ErrorDialog(title, message)
result.dialog._impl.show(self, result)
return result
def stack_trace_dialog(
self,
title: str,
message: str,
content: str,
retry: bool = False,
on_result: DialogResultHandler[bool] | DialogResultHandler[None] | None = None,
) -> Dialog:
"""**DEPRECATED** - await :meth:`dialog` with a :any:`StackTraceDialog`"""
######################################################################
# 2024-06: Backwards compatibility
######################################################################
warnings.warn(
"stack_trace_dialog(...) has been deprecated; use dialog(toga.StackTraceDialog(...))",
DeprecationWarning,
)
######################################################################
# End Backwards compatibility
######################################################################
result = Dialog(
self,
on_result=wrapped_handler(self, on_result) if on_result else None,
)
result.dialog = dialogs.StackTraceDialog(
title,
message=message,
content=content,
retry=retry,
)
result.dialog._impl.show(self, result)
return result
def save_file_dialog(
self,
title: str,
suggested_filename: Path | str,
file_types: list[str] | None = None,
on_result: DialogResultHandler[Path | None] | None = None,
) -> Dialog:
"""**DEPRECATED** - await :meth:`dialog` with a :any:`SaveFileDialog`"""
######################################################################
# 2024-06: Backwards compatibility
######################################################################
warnings.warn(
"save_file_dialog(...) has been deprecated; use dialog(toga.SaveFileDialog(...))",
DeprecationWarning,
)
######################################################################
# End Backwards compatibility
######################################################################
result = Dialog(
self,
on_result=wrapped_handler(self, on_result) if on_result else None,
)
result.dialog = dialogs.SaveFileDialog(
title,
suggested_filename=suggested_filename,
file_types=file_types,
)
result.dialog._impl.show(self, result)
return result
def open_file_dialog(
self,
title: str,
initial_directory: Path | str | None = None,
file_types: list[str] | None = None,
multiple_select: bool = False,
on_result: (
DialogResultHandler[list[Path]]
| DialogResultHandler[Path]
| DialogResultHandler[None]
| None
) = None,
multiselect: None = None, # DEPRECATED
) -> Dialog:
"""**DEPRECATED** - await :meth:`dialog` with an :any:`OpenFileDialog`"""
######################################################################
# 2024-06: Backwards compatibility
######################################################################
warnings.warn(
"open_file_dialog(...) has been deprecated; use dialog(toga.OpenFileDialog(...))",
DeprecationWarning,
)
######################################################################
# End Backwards compatibility
######################################################################
######################################################################
# 2023-08: Backwards compatibility
######################################################################
if multiselect is not None:
warnings.warn(
"open_file_dialog(multiselect) has been renamed multiple_select",
DeprecationWarning,
)
multiple_select = multiselect
######################################################################
# End Backwards compatibility
######################################################################
result = Dialog(
self,
on_result=wrapped_handler(self, on_result) if on_result else None,
)
result.dialog = dialogs.OpenFileDialog(
title,
initial_directory=initial_directory,
file_types=file_types,
multiple_select=multiple_select,
)
result.dialog._impl.show(self, result)
return result
def select_folder_dialog(
self,
title: str,
initial_directory: Path | str | None = None,
multiple_select: bool = False,
on_result: (
DialogResultHandler[list[Path]]
| DialogResultHandler[Path]
| DialogResultHandler[None]
| None
) = None,
multiselect: None = None, # DEPRECATED
) -> Dialog:
"""**DEPRECATED** - await :meth:`dialog` with a :any:`SelectFolderDialog`"""
######################################################################
# 2024-06: Backwards compatibility
######################################################################
warnings.warn(
"select_folder_dialog(...) has been deprecated; use dialog(toga.SelectFolderDialog(...))",
DeprecationWarning,
)
######################################################################
# End Backwards compatibility
######################################################################
######################################################################
# 2023-08: Backwards compatibility
######################################################################
if multiselect is not None:
warnings.warn(
"select_folder_dialog(multiselect) has been renamed multiple_select",
DeprecationWarning,
)
multiple_select = multiselect
######################################################################
# End Backwards compatibility
######################################################################
result = Dialog(
self,
on_result=wrapped_handler(self, on_result) if on_result else None,
)
result.dialog = dialogs.SelectFolderDialog(
title,
initial_directory=initial_directory,
multiple_select=multiple_select,
)
result.dialog._impl.show(self, result)
return result
######################################################################
# 2023-08: Backwards compatibility
######################################################################
@property
def resizeable(self) -> bool:
"""**DEPRECATED** Use :attr:`resizable`"""
warnings.warn(
"Window.resizeable has been renamed Window.resizable",
DeprecationWarning,
)
return self._resizable
@property
def closeable(self) -> bool:
"""**DEPRECATED** Use :attr:`closable`"""
warnings.warn(
"Window.closeable has been renamed Window.closable",
DeprecationWarning,
)
return self._closable
######################################################################
# End Backwards compatibility
######################################################################
######################################################################
# 2024-07: Backwards compatibility
######################################################################
@property
def full_screen(self) -> bool:
"""**DEPRECATED** – Use :any:`Window.state`."""
warnings.warn(
("`Window.full_screen` is deprecated. Use `Window.state` instead."),
DeprecationWarning,
)
return bool(self.state == WindowState.FULLSCREEN)
@full_screen.setter
def full_screen(self, is_full_screen: bool) -> None:
warnings.warn(
("`Window.full_screen` is deprecated. Use `Window.state` instead."),
DeprecationWarning,
)
self._impl.set_window_state(
WindowState.FULLSCREEN if is_full_screen else WindowState.NORMAL
)
######################################################################
# End Backwards compatibility
######################################################################
class MainWindow(Window):
_WINDOW_CLASS = "MainWindow"
def __init__(self, *args, **kwargs):
"""Create a new Main Window.
Accepts the same arguments as :class:`~toga.Window`.
"""
super().__init__(*args, **kwargs)
# Create a toolbar that is linked to the app.
self._toolbar = CommandSet(app=self.app)
# If the window has been created during startup(), we don't want to
# install a change listener yet, as the startup process may install
# additional commands - we want to wait until startup is complete,
# create the initial state of the menus and toolbars, and then add a
# change listener. However, if startup *has* completed, we can install a
# change listener immediately, and trigger the creation of menus and
# toolbars.
if self.app.commands.on_change:
self._toolbar.on_change = self._impl.create_toolbar
self._impl.create_menus()
self._impl.create_toolbar()
@property
def toolbar(self) -> CommandSet:
"""Toolbar for the window."""
return self._toolbar
class WindowSet(MutableSet[Window]):
def __init__(self, app: App):
"""A collection of windows managed by an app.
A window is automatically added to the app when it is created, and removed when
it is closed. Adding a window to an App's window set automatically sets the
:attr:`~toga.Window.app` property of the Window.
"""
self.app = app
self.elements: set[Window] = set()
def add(self, window: Window) -> None:
if not isinstance(window, Window):
raise TypeError("Can only add objects of type toga.Window")
# Silently not add if duplicate
if window not in self.elements:
self.elements.add(window)
window.app = self.app
def discard(self, window: Window) -> None:
if not isinstance(window, Window):
raise TypeError("Can only discard objects of type toga.Window")
if window not in self.elements:
raise ValueError(f"{window!r} is not part of this app")
self.elements.remove(window)
######################################################################
# 2023-10: Backwards compatibility
######################################################################
def __iadd__(self, window: Window) -> WindowSet:
# The standard set type does not have a += operator.
warnings.warn(
"Windows are automatically associated with the app; += is not required",
DeprecationWarning,
stacklevel=2,
)
return self
def __isub__(self, other: Window) -> WindowSet:
# The standard set type does have a -= operator, but it takes sets rather than
# individual items.
warnings.warn(
"Windows are automatically removed from the app; -= is not required",
DeprecationWarning,
stacklevel=2,
)
return self
######################################################################
# End backwards compatibility
######################################################################
def __iter__(self) -> Iterator[Window]:
return iter(self.elements)
def __contains__(self, value: object) -> bool:
return value in self.elements
def __len__(self) -> int:
return len(self.elements)