Debian Codegraph @

gi/overrides/Gtk.py

raw
1 # Copyright (C) 2009 Johan Dahlin <[email protected]>
2 # 2010 Simon van der Linden <[email protected]>
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
17 # USA
18
19 import sys
20 import warnings
21
22 from gi.repository import GObject, GLib
23 from .._ossighelper import register_sigint_fallback, get_event_loop
24 from .._gtktemplate import Template, _extract_handler_and_args
25 from ..overrides import (
26 override,
27 strip_boolean_result,
28 deprecated_init,
29 wrap_list_store_sort_func,
30 )
31 from ..module import get_introspection_module
32 from gi import PyGIDeprecationWarning, get_option
33
34
35 Gtk = get_introspection_module("Gtk")
36 GTK3 = Gtk._version == "3.0"
37 GTK4 = Gtk._version == "4.0"
38
39 __all__ = []
40
41
42 Template = Template
43 __all__.append("Template")
44
45 # Exposed for unit-testing.
46 _extract_handler_and_args = _extract_handler_and_args
47 __all__.append("_extract_handler_and_args")
48
49
50 class PyGTKDeprecationWarning(PyGIDeprecationWarning):
51 pass
52
53
54 __all__.append("PyGTKDeprecationWarning")
55
56
57 if GTK3:
58
59 def _construct_target_list(targets):
60 """Create a list of TargetEntry items from a list of tuples in the form (target, flags, info).
61
62 The list can also contain existing TargetEntry items in which case the existing entry
63 is re-used in the return list.
64 """
65 target_entries = []
66 for entry in targets:
67 if not isinstance(entry, Gtk.TargetEntry):
68 entry = Gtk.TargetEntry.new(*entry)
69 target_entries.append(entry)
70 return target_entries
71
72 __all__.append("_construct_target_list")
73
74
75 def _builder_connect_callback(
76 builder, gobj, signal_name, handler_name, connect_obj, flags, obj_or_map
77 ):
78 handler, args = _extract_handler_and_args(obj_or_map, handler_name)
79
80 after = flags & GObject.ConnectFlags.AFTER
81 if connect_obj is not None:
82 if after:
83 gobj.connect_object_after(signal_name, handler, connect_obj, *args)
84 else:
85 gobj.connect_object(signal_name, handler, connect_obj, *args)
86 else:
87 if after:
88 gobj.connect_after(signal_name, handler, *args)
89 else:
90 gobj.connect(signal_name, handler, *args)
91
92
93 class _FreezeNotifyManager:
94 def __init__(self, obj):
95 self.obj = obj
96
97 def __enter__(self):
98 pass
99
100 def __exit__(self, exc_type, exc_value, traceback):
101 self.obj.thaw_child_notify()
102
103
104 class Widget(Gtk.Widget):
105 translate_coordinates = strip_boolean_result(Gtk.Widget.translate_coordinates)
106
107 if GTK4:
108
109 def __contains__(self, child):
110 return child in list(self)
111
112 def __iter__(self):
113 child = self.get_first_child()
114 while child:
115 yield child
116 child = child.get_next_sibling()
117
118 if GTK3:
119
120 def freeze_child_notify(self):
121 super().freeze_child_notify()
122 return _FreezeNotifyManager(self)
123
124 if GTK3:
125
126 def drag_dest_set_target_list(self, target_list):
127 if (target_list is not None) and (
128 not isinstance(target_list, Gtk.TargetList)
129 ):
130 target_list = Gtk.TargetList.new(_construct_target_list(target_list))
131 super().drag_dest_set_target_list(target_list)
132
133 if GTK3:
134
135 def drag_source_set_target_list(self, target_list):
136 if (target_list is not None) and (
137 not isinstance(target_list, Gtk.TargetList)
138 ):
139 target_list = Gtk.TargetList.new(_construct_target_list(target_list))
140 super().drag_source_set_target_list(target_list)
141
142 if GTK3:
143
144 def style_get_property(self, property_name, value=None):
145 if value is None:
146 prop = self.find_style_property(property_name)
147 if prop is None:
148 raise ValueError(
149 f'Class "{self}" does not contain style property "{property_name}"'
150 )
151 value = GObject.Value(prop.value_type)
152
153 Gtk.Widget.style_get_property(self, property_name, value)
154 return value.get_value()
155
156
157 Widget = override(Widget)
158 __all__.append("Widget")
159
160
161 if GTK3:
162
163 class Container(Gtk.Container, Widget):
164 def __len__(self):
165 return len(self.get_children())
166
167 def __contains__(self, child):
168 return child in self.get_children()
169
170 def __iter__(self):
171 return iter(self.get_children())
172
173 def __bool__(self):
174 return True
175
176 def child_get_property(self, child, property_name, value=None):
177 if value is None:
178 prop = self.find_child_property(property_name)
179 if prop is None:
180 raise ValueError(
181 f'Class "{self}" does not contain child property "{property_name}"'
182 )
183 value = GObject.Value(prop.value_type)
184
185 Gtk.Container.child_get_property(self, child, property_name, value)
186 return value.get_value()
187
188 def child_get(self, child, *prop_names):
189 """Returns a list of child property values for the given names."""
190 return [self.child_get_property(child, name) for name in prop_names]
191
192 def child_set(self, child, **kwargs):
193 """Set a child properties on the given child to key/value pairs."""
194 for name, value in kwargs.items():
195 name = name.replace("_", "-")
196 self.child_set_property(child, name, value)
197
198 get_focus_chain = strip_boolean_result(Gtk.Container.get_focus_chain)
199
200 Container = override(Container)
201 __all__.append("Container")
202 else:
203 Container = object
204
205
206 class Editable(Gtk.Editable):
207 def insert_text(self, text, position):
208 return super().insert_text(text, -1, position)
209
210 get_selection_bounds = strip_boolean_result(
211 Gtk.Editable.get_selection_bounds, fail_ret=()
212 )
213
214
215 Editable = override(Editable)
216 __all__.append("Editable")
217
218
219 if GTK3:
220
221 class Action(Gtk.Action):
222 __init__ = deprecated_init(
223 Gtk.Action.__init__,
224 arg_names=("name", "label", "tooltip", "stock_id"),
225 category=PyGTKDeprecationWarning,
226 )
227
228 Action = override(Action)
229 __all__.append("Action")
230
231 class RadioAction(Gtk.RadioAction):
232 __init__ = deprecated_init(
233 Gtk.RadioAction.__init__,
234 arg_names=("name", "label", "tooltip", "stock_id", "value"),
235 category=PyGTKDeprecationWarning,
236 )
237
238 RadioAction = override(RadioAction)
239 __all__.append("RadioAction")
240
241 class ActionGroup(Gtk.ActionGroup):
242 __init__ = deprecated_init(
243 Gtk.ActionGroup.__init__,
244 arg_names=("name",),
245 category=PyGTKDeprecationWarning,
246 )
247
248 def add_actions(self, entries, user_data=None):
249 """The add_actions() method is a convenience method that creates a number
250 of gtk.Action objects based on the information in the list of action
251 entry tuples contained in entries and adds them to the action group.
252 The entry tuples can vary in size from one to six items with the
253 following information:
254
255 * The name of the action. Must be specified.
256 * The stock id for the action. Optional with a default value of None
257 if a label is specified.
258 * The label for the action. This field should typically be marked
259 for translation, see the set_translation_domain() method. Optional
260 with a default value of None if a stock id is specified.
261 * The accelerator for the action, in the format understood by the
262 gtk.accelerator_parse() function. Optional with a default value of
263 None.
264 * The tooltip for the action. This field should typically be marked
265 for translation, see the set_translation_domain() method. Optional
266 with a default value of None.
267 * The callback function invoked when the action is activated.
268 Optional with a default value of None.
269
270 The "activate" signals of the actions are connected to the callbacks and
271 their accel paths are set to <Actions>/group-name/action-name.
272 """
273 try:
274 iter(entries)
275 except TypeError:
276 raise TypeError("entries must be iterable")
277
278 def _process_action(
279 name,
280 stock_id=None,
281 label=None,
282 accelerator=None,
283 tooltip=None,
284 callback=None,
285 ):
286 action = Action(
287 name=name, label=label, tooltip=tooltip, stock_id=stock_id
288 )
289 if callback is not None:
290 if user_data is None:
291 action.connect("activate", callback)
292 else:
293 action.connect("activate", callback, user_data)
294
295 self.add_action_with_accel(action, accelerator)
296
297 for e in entries:
298 # using inner function above since entries can leave out optional arguments
299 _process_action(*e)
300
301 def add_toggle_actions(self, entries, user_data=None):
302 """The add_toggle_actions() method is a convenience method that creates a
303 number of gtk.ToggleAction objects based on the information in the list
304 of action entry tuples contained in entries and adds them to the action
305 group. The toggle action entry tuples can vary in size from one to seven
306 items with the following information:
307
308 * The name of the action. Must be specified.
309 * The stock id for the action. Optional with a default value of None
310 if a label is specified.
311 * The label for the action. This field should typically be marked
312 for translation, see the set_translation_domain() method. Optional
313 with a default value of None if a stock id is specified.
314 * The accelerator for the action, in the format understood by the
315 gtk.accelerator_parse() function. Optional with a default value of
316 None.
317 * The tooltip for the action. This field should typically be marked
318 for translation, see the set_translation_domain() method. Optional
319 with a default value of None.
320 * The callback function invoked when the action is activated.
321 Optional with a default value of None.
322 * A flag indicating whether the toggle action is active. Optional
323 with a default value of False.
324
325 The "activate" signals of the actions are connected to the callbacks and
326 their accel paths are set to <Actions>/group-name/action-name.
327 """
328 try:
329 iter(entries)
330 except TypeError:
331 raise TypeError("entries must be iterable")
332
333 def _process_action(
334 name,
335 stock_id=None,
336 label=None,
337 accelerator=None,
338 tooltip=None,
339 callback=None,
340 is_active=False,
341 ):
342 action = Gtk.ToggleAction(
343 name=name, label=label, tooltip=tooltip, stock_id=stock_id
344 )
345 action.set_active(is_active)
346 if callback is not None:
347 if user_data is None:
348 action.connect("activate", callback)
349 else:
350 action.connect("activate", callback, user_data)
351
352 self.add_action_with_accel(action, accelerator)
353
354 for e in entries:
355 # using inner function above since entries can leave out optional arguments
356 _process_action(*e)
357
358 def add_radio_actions(
359 self, entries, value=None, on_change=None, user_data=None
360 ):
361 """The add_radio_actions() method is a convenience method that creates a
362 number of gtk.RadioAction objects based on the information in the list
363 of action entry tuples contained in entries and adds them to the action
364 group. The entry tuples can vary in size from one to six items with the
365 following information:
366
367 * The name of the action. Must be specified.
368 * The stock id for the action. Optional with a default value of None
369 if a label is specified.
370 * The label for the action. This field should typically be marked
371 for translation, see the set_translation_domain() method. Optional
372 with a default value of None if a stock id is specified.
373 * The accelerator for the action, in the format understood by the
374 gtk.accelerator_parse() function. Optional with a default value of
375 None.
376 * The tooltip for the action. This field should typically be marked
377 for translation, see the set_translation_domain() method. Optional
378 with a default value of None.
379 * The value to set on the radio action. Optional with a default
380 value of 0. Should be specified in applications.
381
382 The value parameter specifies the radio action that should be set
383 active. The "changed" signal of the first radio action is connected to
384 the on_change callback (if specified and not None) and the accel paths
385 of the actions are set to <Actions>/group-name/action-name.
386 """
387 try:
388 iter(entries)
389 except TypeError:
390 raise TypeError("entries must be iterable")
391
392 first_action = None
393
394 def _process_action(
395 group_source,
396 name,
397 stock_id=None,
398 label=None,
399 accelerator=None,
400 tooltip=None,
401 entry_value=0,
402 ):
403 action = RadioAction(
404 name=name,
405 label=label,
406 tooltip=tooltip,
407 stock_id=stock_id,
408 value=entry_value,
409 )
410
411 if GTK3:
412 action.join_group(group_source)
413
414 if value == entry_value:
415 action.set_active(True)
416
417 self.add_action_with_accel(action, accelerator)
418 return action
419
420 for e in entries:
421 # using inner function above since entries can leave out optional arguments
422 action = _process_action(first_action, *e)
423 if first_action is None:
424 first_action = action
425
426 if first_action is not None and on_change is not None:
427 if user_data is None:
428 first_action.connect("changed", on_change)
429 else:
430 first_action.connect("changed", on_change, user_data)
431
432 ActionGroup = override(ActionGroup)
433 __all__.append("ActionGroup")
434
435 class UIManager(Gtk.UIManager):
436 def add_ui_from_string(self, buffer):
437 if not isinstance(buffer, str):
438 raise TypeError("buffer must be a string")
439
440 length = _get_utf8_length(buffer)
441
442 return Gtk.UIManager.add_ui_from_string(self, buffer, length)
443
444 def insert_action_group(self, buffer, length=-1):
445 return Gtk.UIManager.insert_action_group(self, buffer, length)
446
447 UIManager = override(UIManager)
448 __all__.append("UIManager")
449
450
451 class ComboBox(Gtk.ComboBox, Container):
452 get_active_iter = strip_boolean_result(Gtk.ComboBox.get_active_iter)
453
454
455 ComboBox = override(ComboBox)
456 __all__.append("ComboBox")
457
458
459 if GTK3:
460
461 class Box(Gtk.Box):
462 __init__ = deprecated_init(
463 Gtk.Box.__init__,
464 arg_names=("homogeneous", "spacing"),
465 category=PyGTKDeprecationWarning,
466 )
467
468 Box = override(Box)
469 __all__.append("Box")
470
471
472 if GTK3:
473
474 class SizeGroup(Gtk.SizeGroup):
475 __init__ = deprecated_init(
476 Gtk.SizeGroup.__init__,
477 arg_names=("mode",),
478 deprecated_defaults={"mode": Gtk.SizeGroupMode.VERTICAL},
479 category=PyGTKDeprecationWarning,
480 )
481
482 SizeGroup = override(SizeGroup)
483 __all__.append("SizeGroup")
484
485
486 if GTK3:
487
488 class MenuItem(Gtk.MenuItem):
489 __init__ = deprecated_init(
490 Gtk.MenuItem.__init__,
491 arg_names=("label",),
492 category=PyGTKDeprecationWarning,
493 )
494
495 MenuItem = override(MenuItem)
496 __all__.append("MenuItem")
497
498
499 def _get_utf8_length(string):
500 assert isinstance(string, str)
501 if not isinstance(string, bytes):
502 string = string.encode("utf-8")
503 return len(string)
504
505
506 class Builder(Gtk.Builder):
507 if GTK4:
508 from .._gtktemplate import define_builder_scope
509
510 BuilderScope = define_builder_scope()
511
512 def __init__(self, scope_object_or_map=None):
513 super().__init__()
514 if scope_object_or_map:
515 self.set_scope(Builder.BuilderScope(scope_object_or_map))
516
517 else:
518
519 def connect_signals(self, obj_or_map):
520 """Connect signals specified by this builder to a name, handler mapping.
521
522 Connect signal, name, and handler sets specified in the builder with
523 the given mapping "obj_or_map". The handler/value aspect of the mapping
524 can also contain a tuple in the form of (handler [,arg1 [,argN]])
525 allowing for extra arguments to be passed to the handler. For example:
526
527 .. code-block:: python
528
529 builder.connect_signals({"on_clicked": (on_clicked, arg1, arg2)})
530 """
531 self.connect_signals_full(_builder_connect_callback, obj_or_map)
532
533 def add_from_string(self, buffer):
534 if not isinstance(buffer, str):
535 raise TypeError("buffer must be a string")
536
537 length = _get_utf8_length(buffer)
538
539 return Gtk.Builder.add_from_string(self, buffer, length)
540
541 def add_objects_from_string(self, buffer, object_ids):
542 if not isinstance(buffer, str):
543 raise TypeError("buffer must be a string")
544
545 length = _get_utf8_length(buffer)
546
547 return Gtk.Builder.add_objects_from_string(self, buffer, length, object_ids)
548
549
550 Builder = override(Builder)
551 __all__.append("Builder")
552
553
554 # NOTE: This must come before any other Window/Dialog subclassing, to ensure
555 # that we have a correct inheritance hierarchy.
556
557 if GTK4:
558 _window_init = Gtk.Window.__init__
559 else:
560 _window_init = deprecated_init(
561 Gtk.Window.__init__,
562 arg_names=("type",),
563 category=PyGTKDeprecationWarning,
564 stacklevel=3,
565 )
566
567
568 class Window(Gtk.Window):
569 def __init__(self, *args, **kwargs):
570 if not initialized and get_option("legacy_autoinit"): # TODO: and not GTK5
571 raise RuntimeError(
572 "Gtk couldn't be initialized. "
573 "Use Gtk.init_check() if you want to handle this case."
574 )
575 _window_init(self, *args, **kwargs)
576
577
578 Window = override(Window)
579 __all__.append("Window")
580
581
582 class Dialog(Gtk.Dialog, Container):
583 if GTK3:
584 _old_arg_names = ("title", "parent", "flags", "buttons", "_buttons_property")
585 _init = deprecated_init(
586 Gtk.Dialog.__init__,
587 arg_names=("title", "transient_for", "flags", "add_buttons", "buttons"),
588 ignore=("flags", "add_buttons"),
589 deprecated_aliases={
590 "transient_for": "parent",
591 "buttons": "_buttons_property",
592 },
593 category=PyGTKDeprecationWarning,
594 )
595
596 def __init__(self, *args, **kwargs):
597 new_kwargs = kwargs.copy()
598 old_kwargs = dict(zip(self._old_arg_names, args))
599 old_kwargs.update(kwargs)
600
601 # Increment the warning stacklevel for sub-classes which implement their own __init__.
602 stacklevel = 2
603 if self.__class__ != Dialog and self.__class__.__init__ != Dialog.__init__:
604 stacklevel += 1
605
606 # buttons was overloaded by PyGtk but is needed for Gtk.MessageDialog
607 # as a pass through, so type check the argument and give a deprecation
608 # when it is not of type Gtk.ButtonsType
609 add_buttons = old_kwargs.get("buttons")
610 if add_buttons is not None and not isinstance(add_buttons, Gtk.ButtonsType):
611 warnings.warn(
612 'The "buttons" argument must be a Gtk.ButtonsType enum value. '
613 'Please use the "add_buttons" method for adding buttons. '
614 "See: https://wiki.gnome.org/Projects/PyGObject/InitializerDeprecations",
615 PyGTKDeprecationWarning,
616 stacklevel=stacklevel,
617 )
618 new_kwargs.pop("buttons", None)
619 else:
620 add_buttons = None
621
622 flags = old_kwargs.get("flags", 0)
623 if flags:
624 warnings.warn(
625 'The "flags" argument for dialog construction is deprecated. '
626 "Please use initializer keywords: modal=True and/or destroy_with_parent=True. "
627 "See: https://wiki.gnome.org/Projects/PyGObject/InitializerDeprecations",
628 PyGTKDeprecationWarning,
629 stacklevel=stacklevel,
630 )
631
632 if flags & Gtk.DialogFlags.MODAL:
633 new_kwargs["modal"] = True
634
635 if flags & Gtk.DialogFlags.DESTROY_WITH_PARENT:
636 new_kwargs["destroy_with_parent"] = True
637
638 self._init(*args, **new_kwargs)
639
640 if add_buttons:
641 self.add_buttons(*add_buttons)
642
643 def run(self, *args, **kwargs):
644 with (
645 register_sigint_fallback(self.destroy),
646 get_event_loop(GLib.MainContext.default()).running(self.destroy),
647 ):
648 return Gtk.Dialog.run(self, *args, **kwargs)
649
650 action_area = property(lambda dialog: dialog.get_action_area())
651 vbox = property(lambda dialog: dialog.get_content_area())
652
653 def add_buttons(self, *args):
654 """The add_buttons() method adds several buttons to the Gtk.Dialog using
655 the button data passed as arguments to the method. This method is the
656 same as calling the Gtk.Dialog.add_button() repeatedly. The button data
657 pairs - button text (or stock ID) and a response ID integer are passed
658 individually. For example:
659
660 .. code-block:: python
661
662 dialog.add_buttons(Gtk.STOCK_OPEN, 42, "Close", Gtk.ResponseType.CLOSE)
663
664 will add "Open" and "Close" buttons to dialog.
665 """
666
667 def _button(b):
668 while b:
669 try:
670 t, r = b[0:2]
671 except ValueError:
672 raise ValueError("Must pass an even number of arguments")
673 b = b[2:]
674 yield t, r
675
676 for text, response in _button(args):
677 self.add_button(text, response)
678
679
680 Dialog = override(Dialog)
681 __all__.append("Dialog")
682
683
684 if GTK3:
685
686 class MessageDialog(Gtk.MessageDialog, Dialog):
687 __init__ = deprecated_init(
688 Gtk.MessageDialog.__init__,
689 arg_names=("parent", "flags", "message_type", "buttons", "message_format"),
690 deprecated_aliases={"text": "message_format", "message_type": "type"},
691 category=PyGTKDeprecationWarning,
692 )
693
694 def format_secondary_text(self, message_format):
695 self.set_property("secondary-use-markup", False)
696 self.set_property("secondary-text", message_format)
697
698 def format_secondary_markup(self, message_format):
699 self.set_property("secondary-use-markup", True)
700 self.set_property("secondary-text", message_format)
701
702 MessageDialog = override(MessageDialog)
703 __all__.append("MessageDialog")
704
705
706 if GTK3:
707
708 class ColorSelectionDialog(Gtk.ColorSelectionDialog):
709 __init__ = deprecated_init(
710 Gtk.ColorSelectionDialog.__init__,
711 arg_names=("title",),
712 category=PyGTKDeprecationWarning,
713 )
714
715 ColorSelectionDialog = override(ColorSelectionDialog)
716 __all__.append("ColorSelectionDialog")
717
718 class FileChooserDialog(Gtk.FileChooserDialog):
719 __init__ = deprecated_init(
720 Gtk.FileChooserDialog.__init__,
721 arg_names=("title", "parent", "action", "buttons"),
722 category=PyGTKDeprecationWarning,
723 )
724
725 FileChooserDialog = override(FileChooserDialog)
726 __all__.append("FileChooserDialog")
727
728
729 if GTK3:
730
731 class FontSelectionDialog(Gtk.FontSelectionDialog):
732 __init__ = deprecated_init(
733 Gtk.FontSelectionDialog.__init__,
734 arg_names=("title",),
735 category=PyGTKDeprecationWarning,
736 )
737
738 FontSelectionDialog = override(FontSelectionDialog)
739 __all__.append("FontSelectionDialog")
740
741
742 if GTK3:
743
744 class RecentChooserDialog(Gtk.RecentChooserDialog):
745 # Note, the "manager" keyword must work across the entire 3.x series because
746 # "recent_manager" is not backwards compatible with PyGObject versions prior to 3.10.
747 __init__ = deprecated_init(
748 Gtk.RecentChooserDialog.__init__,
749 arg_names=("title", "parent", "recent_manager", "buttons"),
750 deprecated_aliases={"recent_manager": "manager"},
751 category=PyGTKDeprecationWarning,
752 )
753
754 RecentChooserDialog = override(RecentChooserDialog)
755 __all__.append("RecentChooserDialog")
756
757
758 class IconView(Gtk.IconView):
759 if GTK3:
760 __init__ = deprecated_init(
761 Gtk.IconView.__init__,
762 arg_names=("model",),
763 category=PyGTKDeprecationWarning,
764 )
765
766 get_item_at_pos = strip_boolean_result(Gtk.IconView.get_item_at_pos)
767 get_visible_range = strip_boolean_result(Gtk.IconView.get_visible_range)
768 get_dest_item_at_pos = strip_boolean_result(Gtk.IconView.get_dest_item_at_pos)
769
770
771 IconView = override(IconView)
772 __all__.append("IconView")
773
774
775 if GTK3:
776
777 class ToolButton(Gtk.ToolButton):
778 __init__ = deprecated_init(
779 Gtk.ToolButton.__init__,
780 arg_names=("stock_id",),
781 category=PyGTKDeprecationWarning,
782 )
783
784 ToolButton = override(ToolButton)
785 __all__.append("ToolButton")
786
787
788 class IMContext(Gtk.IMContext):
789 get_surrounding = strip_boolean_result(Gtk.IMContext.get_surrounding)
790
791
792 IMContext = override(IMContext)
793 __all__.append("IMContext")
794
795
796 class RecentInfo(Gtk.RecentInfo):
797 get_application_info = strip_boolean_result(Gtk.RecentInfo.get_application_info)
798
799
800 RecentInfo = override(RecentInfo)
801 __all__.append("RecentInfo")
802
803
804 class TextBuffer(Gtk.TextBuffer):
805 def create_tag(self, tag_name=None, **properties):
806 """Creates a tag and adds it to the tag table of the TextBuffer.
807
808 :param str tag_name:
809 Name of the new tag, or None
810 :param **properties:
811 Keyword list of properties and their values
812
813 This is equivalent to creating a Gtk.TextTag and then adding the
814 tag to the buffer's tag table. The returned tag is owned by
815 the buffer's tag table.
816
817 If ``tag_name`` is None, the tag is anonymous.
818
819 If ``tag_name`` is not None, a tag called ``tag_name`` must not already
820 exist in the tag table for this buffer.
821
822 Properties are passed as a keyword list of names and values (e.g.
823 foreground='DodgerBlue', weight=Pango.Weight.BOLD)
824
825 :returns:
826 A new tag.
827 """
828 tag = Gtk.TextTag(name=tag_name, **properties)
829 self.get_tag_table().add(tag)
830 return tag
831
832 def create_mark(self, mark_name, where, left_gravity=False):
833 return Gtk.TextBuffer.create_mark(self, mark_name, where, left_gravity)
834
835 def set_text(self, text, length=-1):
836 Gtk.TextBuffer.set_text(self, text, length)
837
838 def insert(self, iter, text, length=-1):
839 if not isinstance(text, str):
840 raise TypeError(f"text must be a string, not {type(text)}")
841
842 Gtk.TextBuffer.insert(self, iter, text, length)
843
844 def insert_with_tags(self, iter, text, *tags):
845 start_offset = iter.get_offset()
846 self.insert(iter, text)
847
848 if not tags:
849 return
850
851 start = self.get_iter_at_offset(start_offset)
852
853 for tag in tags:
854 self.apply_tag(tag, start, iter)
855
856 def insert_with_tags_by_name(self, iter, text, *tags):
857 tag_objs = []
858
859 for tag in tags:
860 tag_obj = self.get_tag_table().lookup(tag)
861 if not tag_obj:
862 raise ValueError(f"unknown text tag: {tag}")
863 tag_objs.append(tag_obj)
864
865 self.insert_with_tags(iter, text, *tag_objs)
866
867 def insert_at_cursor(self, text, length=-1):
868 if not isinstance(text, str):
869 raise TypeError(f"text must be a string, not {type(text)}")
870
871 Gtk.TextBuffer.insert_at_cursor(self, text, length)
872
873 get_selection_bounds = strip_boolean_result(
874 Gtk.TextBuffer.get_selection_bounds, fail_ret=()
875 )
876
877
878 TextBuffer = override(TextBuffer)
879 __all__.append("TextBuffer")
880
881
882 class TextIter(Gtk.TextIter):
883 forward_search = strip_boolean_result(Gtk.TextIter.forward_search)
884 backward_search = strip_boolean_result(Gtk.TextIter.backward_search)
885
886
887 TextIter = override(TextIter)
888 __all__.append("TextIter")
889
890
891 class TreeModel(Gtk.TreeModel):
892 def __len__(self):
893 return self.iter_n_children(None)
894
895 def __bool__(self):
896 return True
897
898 def _getiter(self, key):
899 if isinstance(key, Gtk.TreeIter):
900 return key
901 if isinstance(key, int) and key < 0:
902 index = len(self) + key
903 if index < 0:
904 msg = f"row index is out of bounds: {key:d}"
905 raise IndexError(msg)
906 return self.get_iter(index)
907 try:
908 aiter = self.get_iter(key)
909 except ValueError:
910 raise IndexError(f"could not find tree path '{key}'")
911 return aiter
912
913 def sort_new_with_model(self):
914 super_object = super()
915 if hasattr(super_object, "sort_new_with_model"):
916 return super_object.sort_new_with_model()
917 return TreeModelSort.new_with_model(self)
918
919 def _coerce_path(self, path):
920 if isinstance(path, Gtk.TreePath):
921 return path
922 return TreePath(path)
923
924 def __getitem__(self, key):
925 aiter = self._getiter(key)
926 return TreeModelRow(self, aiter)
927
928 def __setitem__(self, key, value):
929 row = self[key]
930 self.set_row(row.iter, value)
931
932 def __delitem__(self, key):
933 aiter = self._getiter(key)
934 self.remove(aiter)
935
936 def __iter__(self):
937 return TreeModelRowIter(self, self.get_iter_first())
938
939 get_iter_first = strip_boolean_result(Gtk.TreeModel.get_iter_first)
940 iter_children = strip_boolean_result(Gtk.TreeModel.iter_children)
941 iter_nth_child = strip_boolean_result(Gtk.TreeModel.iter_nth_child)
942 iter_parent = strip_boolean_result(Gtk.TreeModel.iter_parent)
943 get_iter_from_string = strip_boolean_result(
944 Gtk.TreeModel.get_iter_from_string, ValueError, "invalid tree path"
945 )
946
947 def get_iter(self, path):
948 path = self._coerce_path(path)
949 success, aiter = super().get_iter(path)
950 if not success:
951 raise ValueError(f"invalid tree path '{path}'")
952 return aiter
953
954 def iter_next(self, aiter):
955 next_iter = aiter.copy()
956 success = super().iter_next(next_iter)
957 if success:
958 return next_iter
959 return None
960
961 def iter_previous(self, aiter):
962 prev_iter = aiter.copy()
963 success = super().iter_previous(prev_iter)
964 if success:
965 return prev_iter
966 return None
967
968 def _convert_row(self, row):
969 # TODO: Accept a dictionary for row
970 # model.append(None,{COLUMN_ICON: icon, COLUMN_NAME: name})
971 if isinstance(row, str):
972 raise TypeError("Expected a list or tuple, but got str")
973
974 n_columns = self.get_n_columns()
975 if len(row) != n_columns:
976 raise ValueError("row sequence has the incorrect number of elements")
977
978 result = []
979 columns = []
980 for cur_col, value in enumerate(row):
981 # do not try to set None values, they are causing warnings
982 if value is None:
983 continue
984 result.append(self._convert_value(cur_col, value))
985 columns.append(cur_col)
986 return (result, columns)
987
988 def set_row(self, treeiter, row):
989 _converted_row, columns = self._convert_row(row)
990 for column in columns:
991 self.set_value(treeiter, column, row[column])
992
993 def _convert_value(self, column, value):
994 """Convert value to a GObject.Value of the expected type."""
995 if isinstance(value, GObject.Value):
996 return value
997 return GObject.Value(self.get_column_type(column), value)
998
999 def get(self, treeiter, *columns):
1000 n_columns = self.get_n_columns()
1001
1002 values = []
1003 for col in columns:
1004 if not isinstance(col, int):
1005 raise TypeError("column numbers must be ints")
1006
1007 if col < 0 or col >= n_columns:
1008 raise ValueError("column number is out of range")
1009
1010 values.append(self.get_value(treeiter, col))
1011
1012 return tuple(values)
1013
1014 #
1015 # Signals supporting python iterables as tree paths
1016 #
1017 def row_changed(self, path, iter):
1018 return super().row_changed(self._coerce_path(path), iter)
1019
1020 def row_inserted(self, path, iter):
1021 return super().row_inserted(self._coerce_path(path), iter)
1022
1023 def row_has_child_toggled(self, path, iter):
1024 return super().row_has_child_toggled(self._coerce_path(path), iter)
1025
1026 def row_deleted(self, path):
1027 return super().row_deleted(self._coerce_path(path))
1028
1029 def rows_reordered(self, path, iter, new_order):
1030 return super().rows_reordered(self._coerce_path(path), iter, new_order)
1031
1032
1033 TreeModel = override(TreeModel)
1034 __all__.append("TreeModel")
1035
1036
1037 class TreeSortable(
1038 Gtk.TreeSortable,
1039 ):
1040 get_sort_column_id = strip_boolean_result(
1041 Gtk.TreeSortable.get_sort_column_id, fail_ret=(None, None)
1042 )
1043
1044 def set_sort_func(self, sort_column_id, sort_func, user_data=None):
1045 super().set_sort_func(sort_column_id, sort_func, user_data)
1046
1047 def set_default_sort_func(self, sort_func, user_data=None):
1048 super().set_default_sort_func(sort_func, user_data)
1049
1050
1051 TreeSortable = override(TreeSortable)
1052 __all__.append("TreeSortable")
1053
1054
1055 if GTK3:
1056
1057 class TreeModelSort(Gtk.TreeModelSort):
1058 __init__ = deprecated_init(
1059 Gtk.TreeModelSort.__init__,
1060 arg_names=("model",),
1061 category=PyGTKDeprecationWarning,
1062 )
1063
1064 if not hasattr(Gtk.TreeModelSort, "new_with_model"):
1065
1066 @classmethod
1067 def new_with_model(self, child_model):
1068 return TreeModel.sort_new_with_model(child_model)
1069
1070 TreeModelSort = override(TreeModelSort)
1071 __all__.append("TreeModelSort")
1072
1073
1074 class ListStore(Gtk.ListStore, TreeModel, TreeSortable):
1075 def __init__(self, *column_types):
1076 Gtk.ListStore.__init__(self)
1077 self.set_column_types(column_types)
1078
1079 # insert_with_valuesv got renamed to insert_with_values with 4.1.0
1080 # https://gitlab.gnome.org/GNOME/gtk/-/commit/a1216599ff6b39bca3e9
1081 if not hasattr(Gtk.ListStore, "insert_with_valuesv"):
1082 insert_with_valuesv = Gtk.ListStore.insert_with_values
1083 elif not hasattr(Gtk.ListStore, "insert_with_values"):
1084 insert_with_values = Gtk.ListStore.insert_with_valuesv
1085
1086 def _do_insert(self, position, row):
1087 if row is not None:
1088 row, columns = self._convert_row(row)
1089 treeiter = self.insert_with_values(position, columns, row)
1090 else:
1091 treeiter = Gtk.ListStore.insert(self, position)
1092
1093 return treeiter
1094
1095 def append(self, row=None):
1096 if row:
1097 return self._do_insert(-1, row)
1098 # gtk_list_store_insert() does not know about the "position == -1"
1099 # case, so use append() here
1100 return Gtk.ListStore.append(self)
1101
1102 def prepend(self, row=None):
1103 return self._do_insert(0, row)
1104
1105 def insert(self, position, row=None):
1106 return self._do_insert(position, row)
1107
1108 def insert_before(self, sibling, row=None):
1109 if row is not None:
1110 if sibling is None:
1111 position = -1
1112 else:
1113 position = self.get_path(sibling).get_indices()[-1]
1114 return self._do_insert(position, row)
1115
1116 return Gtk.ListStore.insert_before(self, sibling)
1117
1118 def insert_after(self, sibling, row=None):
1119 if row is not None:
1120 if sibling is None:
1121 position = 0
1122 else:
1123 position = self.get_path(sibling).get_indices()[-1] + 1
1124 return self._do_insert(position, row)
1125
1126 return Gtk.ListStore.insert_after(self, sibling)
1127
1128 def set_value(self, treeiter, column, value):
1129 value = self._convert_value(column, value)
1130 Gtk.ListStore.set_value(self, treeiter, column, value)
1131
1132 def set(self, treeiter, *args):
1133 def _set_lists(cols, vals):
1134 if len(cols) != len(vals):
1135 raise TypeError(
1136 "The number of columns do not match the number of values"
1137 )
1138
1139 columns = []
1140 values = []
1141 for col_num, value in zip(cols, vals):
1142 if not isinstance(col_num, int):
1143 raise TypeError("TypeError: Expected integer argument for column.")
1144
1145 columns.append(col_num)
1146 values.append(self._convert_value(col_num, value))
1147
1148 Gtk.ListStore.set(self, treeiter, columns, values)
1149
1150 if args:
1151 if isinstance(args[0], int):
1152 _set_lists(args[::2], args[1::2])
1153 elif isinstance(args[0], (tuple, list)):
1154 if len(args) != 2:
1155 raise TypeError("Too many arguments")
1156 _set_lists(args[0], args[1])
1157 elif isinstance(args[0], dict):
1158 _set_lists(list(args[0]), args[0].values())
1159 else:
1160 raise TypeError(
1161 "Argument list must be in the form of (column, value, ...), ((columns,...), (values, ...)) or {column: value}. No -1 termination is needed."
1162 )
1163
1164
1165 ListStore = override(ListStore)
1166 __all__.append("ListStore")
1167
1168
1169 class TreeModelRow:
1170 def __init__(self, model, iter_or_path):
1171 if not isinstance(model, Gtk.TreeModel):
1172 raise TypeError(f"expected Gtk.TreeModel, {type(model).__name__} found")
1173 self.model = model
1174 if isinstance(iter_or_path, Gtk.TreePath):
1175 self.iter = model.get_iter(iter_or_path)
1176 elif isinstance(iter_or_path, Gtk.TreeIter):
1177 self.iter = iter_or_path
1178 else:
1179 raise TypeError(
1180 "expected Gtk.TreeIter or Gtk.TreePath, "
1181 f"{type(iter_or_path).__name__} found"
1182 )
1183
1184 @property
1185 def path(self):
1186 return self.model.get_path(self.iter)
1187
1188 @property
1189 def next(self):
1190 return self.get_next()
1191
1192 @property
1193 def previous(self):
1194 return self.get_previous()
1195
1196 @property
1197 def parent(self):
1198 return self.get_parent()
1199
1200 def get_next(self):
1201 next_iter = self.model.iter_next(self.iter)
1202 if next_iter:
1203 return TreeModelRow(self.model, next_iter)
1204 return None
1205
1206 def get_previous(self):
1207 prev_iter = self.model.iter_previous(self.iter)
1208 if prev_iter:
1209 return TreeModelRow(self.model, prev_iter)
1210 return None
1211
1212 def get_parent(self):
1213 parent_iter = self.model.iter_parent(self.iter)
1214 if parent_iter:
1215 return TreeModelRow(self.model, parent_iter)
1216 return None
1217
1218 def __getitem__(self, key):
1219 if isinstance(key, int):
1220 if key >= self.model.get_n_columns():
1221 msg = f"column index is out of bounds: {key:d}"
1222 raise IndexError(msg)
1223 if key < 0:
1224 key = self._convert_negative_index(key)
1225 return self.model.get_value(self.iter, key)
1226 if isinstance(key, slice):
1227 start, stop, step = key.indices(self.model.get_n_columns())
1228 return [
1229 self.model.get_value(self.iter, i) for i in range(start, stop, step)
1230 ]
1231 if isinstance(key, tuple):
1232 return [self[k] for k in key]
1233 raise TypeError(
1234 f"indices must be integers, slice or tuple, not {type(key).__name__}"
1235 )
1236
1237 def __setitem__(self, key, value):
1238 if isinstance(key, int):
1239 if key >= self.model.get_n_columns():
1240 msg = f"column index is out of bounds: {key:d}"
1241 raise IndexError(msg)
1242 if key < 0:
1243 key = self._convert_negative_index(key)
1244 self.model.set_value(self.iter, key, value)
1245 elif isinstance(key, slice):
1246 start, stop, step = key.indices(self.model.get_n_columns())
1247 indexList = range(start, stop, step)
1248 if len(indexList) != len(value):
1249 msg = f"attempt to assign sequence of size {len(value):d} to slice of size {len(indexList):d}d"
1250 raise ValueError(msg)
1251
1252 for i, v in enumerate(indexList):
1253 self.model.set_value(self.iter, v, value[i])
1254 elif isinstance(key, tuple):
1255 if len(key) != len(value):
1256 msg = f"attempt to assign sequence of size {len(value):d} to sequence of size {len(key):d}"
1257 raise ValueError(msg)
1258 for k, v in zip(key, value):
1259 self[k] = v
1260 else:
1261 raise TypeError(
1262 f"indices must be an integer, slice or tuple, not {type(key).__name__}"
1263 )
1264
1265 def _convert_negative_index(self, index):
1266 new_index = self.model.get_n_columns() + index
1267 if new_index < 0:
1268 msg = f"column index is out of bounds: {index:d}"
1269 raise IndexError(msg)
1270 return new_index
1271
1272 def iterchildren(self):
1273 child_iter = self.model.iter_children(self.iter)
1274 return TreeModelRowIter(self.model, child_iter)
1275
1276
1277 __all__.append("TreeModelRow")
1278
1279
1280 class TreeModelRowIter:
1281 def __init__(self, model, aiter):
1282 self.model = model
1283 self.iter = aiter
1284
1285 def __next__(self):
1286 if not self.iter:
1287 raise StopIteration
1288 row = TreeModelRow(self.model, self.iter)
1289 self.iter = self.model.iter_next(self.iter)
1290 return row
1291
1292 def __iter__(self):
1293 return self
1294
1295
1296 __all__.append("TreeModelRowIter")
1297
1298
1299 class TreePath(Gtk.TreePath):
1300 def __new__(cls, path=0):
1301 if isinstance(path, int):
1302 path = str(path)
1303 elif not isinstance(path, str):
1304 path = ":".join(str(val) for val in path)
1305
1306 if len(path) == 0:
1307 raise TypeError(f"could not parse subscript '{path}' as a tree path")
1308 try:
1309 return TreePath.new_from_string(path)
1310 except TypeError:
1311 raise TypeError(f"could not parse subscript '{path}' as a tree path")
1312
1313 def __init__(self, *args, **kwargs):
1314 super().__init__()
1315
1316 def __str__(self):
1317 return self.to_string() or ""
1318
1319 def __lt__(self, other):
1320 return other is not None and self.compare(other) < 0
1321
1322 def __le__(self, other):
1323 return other is not None and self.compare(other) <= 0
1324
1325 def __eq__(self, other):
1326 return other is not None and self.compare(other) == 0
1327
1328 def __ne__(self, other):
1329 return other is None or self.compare(other) != 0
1330
1331 def __gt__(self, other):
1332 return other is None or self.compare(other) > 0
1333
1334 def __ge__(self, other):
1335 return other is None or self.compare(other) >= 0
1336
1337 def __iter__(self):
1338 return iter(self.get_indices())
1339
1340 def __len__(self):
1341 return self.get_depth()
1342
1343 def __getitem__(self, index):
1344 return self.get_indices()[index]
1345
1346
1347 TreePath = override(TreePath)
1348 __all__.append("TreePath")
1349
1350
1351 class TreeStore(Gtk.TreeStore, TreeModel, TreeSortable):
1352 def __init__(self, *column_types):
1353 Gtk.TreeStore.__init__(self)
1354 self.set_column_types(column_types)
1355
1356 def _do_insert(self, parent, position, row):
1357 if row is not None:
1358 row, columns = self._convert_row(row)
1359 treeiter = self.insert_with_values(parent, position, columns, row)
1360 else:
1361 treeiter = Gtk.TreeStore.insert(self, parent, position)
1362
1363 return treeiter
1364
1365 def append(self, parent, row=None):
1366 return self._do_insert(parent, -1, row)
1367
1368 def prepend(self, parent, row=None):
1369 return self._do_insert(parent, 0, row)
1370
1371 def insert(self, parent, position, row=None):
1372 return self._do_insert(parent, position, row)
1373
1374 def insert_before(self, parent, sibling, row=None):
1375 if row is not None:
1376 if sibling is None:
1377 position = -1
1378 else:
1379 if parent is None:
1380 parent = self.iter_parent(sibling)
1381 position = self.get_path(sibling).get_indices()[-1]
1382 return self._do_insert(parent, position, row)
1383
1384 return Gtk.TreeStore.insert_before(self, parent, sibling)
1385
1386 def insert_after(self, parent, sibling, row=None):
1387 if row is not None:
1388 if sibling is None:
1389 position = 0
1390 else:
1391 if parent is None:
1392 parent = self.iter_parent(sibling)
1393 position = self.get_path(sibling).get_indices()[-1] + 1
1394 return self._do_insert(parent, position, row)
1395
1396 return Gtk.TreeStore.insert_after(self, parent, sibling)
1397
1398 def set_value(self, treeiter, column, value):
1399 value = self._convert_value(column, value)
1400 Gtk.TreeStore.set_value(self, treeiter, column, value)
1401
1402 def set(self, treeiter, *args):
1403 def _set_lists(cols, vals):
1404 if len(cols) != len(vals):
1405 raise TypeError(
1406 "The number of columns do not match the number of values"
1407 )
1408
1409 columns = []
1410 values = []
1411 for col_num, value in zip(cols, vals):
1412 if not isinstance(col_num, int):
1413 raise TypeError("TypeError: Expected integer argument for column.")
1414
1415 columns.append(col_num)
1416 values.append(self._convert_value(col_num, value))
1417
1418 Gtk.TreeStore.set(self, treeiter, columns, values)
1419
1420 if args:
1421 if isinstance(args[0], int):
1422 _set_lists(args[::2], args[1::2])
1423 elif isinstance(args[0], (tuple, list)):
1424 if len(args) != 2:
1425 raise TypeError("Too many arguments")
1426 _set_lists(args[0], args[1])
1427 elif isinstance(args[0], dict):
1428 _set_lists(args[0].keys(), args[0].values())
1429 else:
1430 raise TypeError(
1431 "Argument list must be in the form of (column, value, ...), ((columns,...), (values, ...)) or {column: value}. No -1 termination is needed."
1432 )
1433
1434
1435 TreeStore = override(TreeStore)
1436 __all__.append("TreeStore")
1437
1438
1439 class TreeView(Gtk.TreeView, Container):
1440 if GTK3:
1441 __init__ = deprecated_init(
1442 Gtk.TreeView.__init__,
1443 arg_names=("model",),
1444 category=PyGTKDeprecationWarning,
1445 )
1446
1447 get_path_at_pos = strip_boolean_result(Gtk.TreeView.get_path_at_pos)
1448 get_visible_range = strip_boolean_result(Gtk.TreeView.get_visible_range)
1449 get_dest_row_at_pos = strip_boolean_result(Gtk.TreeView.get_dest_row_at_pos)
1450
1451 if GTK3:
1452
1453 def enable_model_drag_source(self, start_button_mask, targets, actions):
1454 target_entries = _construct_target_list(targets)
1455 super().enable_model_drag_source(start_button_mask, target_entries, actions)
1456
1457 if GTK3:
1458
1459 def enable_model_drag_dest(self, targets, actions):
1460 target_entries = _construct_target_list(targets)
1461 super().enable_model_drag_dest(target_entries, actions)
1462
1463 def scroll_to_cell(
1464 self, path, column=None, use_align=False, row_align=0.0, col_align=0.0
1465 ):
1466 if not isinstance(path, Gtk.TreePath):
1467 path = TreePath(path)
1468 super().scroll_to_cell(path, column, use_align, row_align, col_align)
1469
1470 def set_cursor(self, path, column=None, start_editing=False):
1471 if not isinstance(path, Gtk.TreePath):
1472 path = TreePath(path)
1473 super().set_cursor(path, column, start_editing)
1474
1475 def get_cell_area(self, path, column=None):
1476 if not isinstance(path, Gtk.TreePath):
1477 path = TreePath(path)
1478 return super().get_cell_area(path, column)
1479
1480 def insert_column_with_attributes(self, position, title, cell, **kwargs):
1481 column = TreeViewColumn()
1482 column.set_title(title)
1483 column.pack_start(cell, False)
1484 self.insert_column(column, position)
1485 column.set_attributes(cell, **kwargs)
1486
1487
1488 TreeView = override(TreeView)
1489 __all__.append("TreeView")
1490
1491
1492 class TreeViewColumn(Gtk.TreeViewColumn):
1493 def __init__(self, title="", cell_renderer=None, **attributes):
1494 Gtk.TreeViewColumn.__init__(self, title=title)
1495 if cell_renderer:
1496 self.pack_start(cell_renderer, True)
1497
1498 for name, value in attributes.items():
1499 self.add_attribute(cell_renderer, name, value)
1500
1501 cell_get_position = strip_boolean_result(Gtk.TreeViewColumn.cell_get_position)
1502
1503 def set_cell_data_func(self, cell_renderer, func, func_data=None):
1504 super().set_cell_data_func(cell_renderer, func, func_data)
1505
1506 def set_attributes(self, cell_renderer, **attributes):
1507 Gtk.CellLayout.clear_attributes(self, cell_renderer)
1508
1509 for name, value in attributes.items():
1510 Gtk.CellLayout.add_attribute(self, cell_renderer, name, value)
1511
1512
1513 TreeViewColumn = override(TreeViewColumn)
1514 __all__.append("TreeViewColumn")
1515
1516
1517 class TreeSelection(Gtk.TreeSelection):
1518 def select_path(self, path):
1519 if not isinstance(path, Gtk.TreePath):
1520 path = TreePath(path)
1521 super().select_path(path)
1522
1523 def get_selected(self):
1524 success, model, aiter = super().get_selected()
1525 if success:
1526 return (model, aiter)
1527 return (model, None)
1528
1529 # for compatibility with PyGtk
1530
1531 def get_selected_rows(self):
1532 rows, model = super().get_selected_rows()
1533 return (model, rows)
1534
1535
1536 TreeSelection = override(TreeSelection)
1537 __all__.append("TreeSelection")
1538
1539
1540 if GTK3:
1541
1542 class Button(Gtk.Button, Container):
1543 _init = deprecated_init(
1544 Gtk.Button.__init__,
1545 arg_names=("label", "stock", "use_stock", "use_underline"),
1546 ignore=("stock",),
1547 category=PyGTKDeprecationWarning,
1548 stacklevel=3,
1549 )
1550
1551 def __init__(self, *args, **kwargs):
1552 # Doubly deprecated initializer, the stock keyword is non-standard.
1553 # Simply give a warning that stock items are deprecated even though
1554 # we want to deprecate the non-standard keyword as well here from
1555 # the overrides.
1556 if kwargs.get("stock"):
1557 warnings.warn(
1558 "Stock items are deprecated. "
1559 "Please use: Gtk.Button.new_with_mnemonic(label)",
1560 PyGTKDeprecationWarning,
1561 stacklevel=2,
1562 )
1563 new_kwargs = kwargs.copy()
1564 new_kwargs["label"] = new_kwargs["stock"]
1565 new_kwargs["use_stock"] = True
1566 new_kwargs["use_underline"] = True
1567 del new_kwargs["stock"]
1568 Gtk.Button.__init__(self, **new_kwargs)
1569 else:
1570 self._init(*args, **kwargs)
1571
1572 if hasattr(Gtk.Widget, "set_focus_on_click"):
1573
1574 def set_focus_on_click(self, *args, **kwargs):
1575 # Gtk.Widget.set_focus_on_click should be used instead but it's
1576 # no obvious how because of the shadowed method, so override here
1577 return Gtk.Widget.set_focus_on_click(self, *args, **kwargs)
1578
1579 if hasattr(Gtk.Widget, "get_focus_on_click"):
1580
1581 def get_focus_on_click(self, *args, **kwargs):
1582 # Gtk.Widget.get_focus_on_click should be used instead but it's
1583 # no obvious how because of the shadowed method, so override here
1584 return Gtk.Widget.get_focus_on_click(self, *args, **kwargs)
1585
1586 Button = override(Button)
1587 __all__.append("Button")
1588
1589 class LinkButton(Gtk.LinkButton):
1590 __init__ = deprecated_init(
1591 Gtk.LinkButton.__init__,
1592 arg_names=("uri", "label"),
1593 category=PyGTKDeprecationWarning,
1594 )
1595
1596 LinkButton = override(LinkButton)
1597 __all__.append("LinkButton")
1598
1599 class Label(Gtk.Label):
1600 __init__ = deprecated_init(
1601 Gtk.Label.__init__, arg_names=("label",), category=PyGTKDeprecationWarning
1602 )
1603
1604 Label = override(Label)
1605 __all__.append("Label")
1606
1607
1608 class Adjustment(Gtk.Adjustment):
1609 if GTK3:
1610 _init = deprecated_init(
1611 Gtk.Adjustment.__init__,
1612 arg_names=(
1613 "value",
1614 "lower",
1615 "upper",
1616 "step_increment",
1617 "page_increment",
1618 "page_size",
1619 ),
1620 deprecated_aliases={
1621 "page_increment": "page_incr",
1622 "step_increment": "step_incr",
1623 },
1624 category=PyGTKDeprecationWarning,
1625 stacklevel=3,
1626 )
1627
1628 def __init__(self, *args, **kwargs):
1629 if GTK3:
1630 self._init(*args, **kwargs)
1631 # The value property is set between lower and (upper - page_size).
1632 # Just in case lower, upper or page_size was still 0 when value
1633 # was set, we set it again here.
1634 if "value" in kwargs:
1635 self.set_value(kwargs["value"])
1636 elif len(args) >= 1:
1637 self.set_value(args[0])
1638 else:
1639 Gtk.Adjustment.__init__(self, *args, **kwargs)
1640
1641 # The value property is set between lower and (upper - page_size).
1642 # Just in case lower, upper or page_size was still 0 when value
1643 # was set, we set it again here.
1644 if "value" in kwargs:
1645 self.set_value(kwargs["value"])
1646
1647
1648 Adjustment = override(Adjustment)
1649 __all__.append("Adjustment")
1650
1651
1652 if GTK3:
1653
1654 class Table(Gtk.Table, Container):
1655 __init__ = deprecated_init(
1656 Gtk.Table.__init__,
1657 arg_names=("n_rows", "n_columns", "homogeneous"),
1658 deprecated_aliases={"n_rows": "rows", "n_columns": "columns"},
1659 category=PyGTKDeprecationWarning,
1660 )
1661
1662 def attach(
1663 self,
1664 child,
1665 left_attach,
1666 right_attach,
1667 top_attach,
1668 bottom_attach,
1669 xoptions=Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL,
1670 yoptions=Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL,
1671 xpadding=0,
1672 ypadding=0,
1673 ):
1674 Gtk.Table.attach(
1675 self,
1676 child,
1677 left_attach,
1678 right_attach,
1679 top_attach,
1680 bottom_attach,
1681 xoptions,
1682 yoptions,
1683 xpadding,
1684 ypadding,
1685 )
1686
1687 Table = override(Table)
1688 __all__.append("Table")
1689
1690 class ScrolledWindow(Gtk.ScrolledWindow):
1691 __init__ = deprecated_init(
1692 Gtk.ScrolledWindow.__init__,
1693 arg_names=("hadjustment", "vadjustment"),
1694 category=PyGTKDeprecationWarning,
1695 )
1696
1697 ScrolledWindow = override(ScrolledWindow)
1698 __all__.append("ScrolledWindow")
1699
1700
1701 if GTK3:
1702
1703 class HScrollbar(Gtk.HScrollbar):
1704 __init__ = deprecated_init(
1705 Gtk.HScrollbar.__init__,
1706 arg_names=("adjustment",),
1707 category=PyGTKDeprecationWarning,
1708 )
1709
1710 HScrollbar = override(HScrollbar)
1711 __all__.append("HScrollbar")
1712
1713 class VScrollbar(Gtk.VScrollbar):
1714 __init__ = deprecated_init(
1715 Gtk.VScrollbar.__init__,
1716 arg_names=("adjustment",),
1717 category=PyGTKDeprecationWarning,
1718 )
1719
1720 VScrollbar = override(VScrollbar)
1721 __all__.append("VScrollbar")
1722
1723
1724 if GTK3:
1725
1726 class Paned(Gtk.Paned):
1727 def pack1(self, child, resize=False, shrink=True):
1728 super().pack1(child, resize, shrink)
1729
1730 def pack2(self, child, resize=True, shrink=True):
1731 super().pack2(child, resize, shrink)
1732
1733 Paned = override(Paned)
1734 __all__.append("Paned")
1735
1736
1737 if GTK3:
1738
1739 class Arrow(Gtk.Arrow):
1740 __init__ = deprecated_init(
1741 Gtk.Arrow.__init__,
1742 arg_names=("arrow_type", "shadow_type"),
1743 category=PyGTKDeprecationWarning,
1744 )
1745
1746 Arrow = override(Arrow)
1747 __all__.append("Arrow")
1748
1749 class IconSet(Gtk.IconSet):
1750 def __new__(cls, pixbuf=None):
1751 if pixbuf is not None:
1752 warnings.warn(
1753 "Gtk.IconSet(pixbuf) has been deprecated. Please use: "
1754 "Gtk.IconSet.new_from_pixbuf(pixbuf)",
1755 PyGTKDeprecationWarning,
1756 stacklevel=2,
1757 )
1758 iconset = Gtk.IconSet.new_from_pixbuf(pixbuf)
1759 else:
1760 iconset = Gtk.IconSet.__new__(cls)
1761 return iconset
1762
1763 def __init__(self, *args, **kwargs):
1764 return super().__init__()
1765
1766 IconSet = override(IconSet)
1767 __all__.append("IconSet")
1768
1769 class Viewport(Gtk.Viewport):
1770 __init__ = deprecated_init(
1771 Gtk.Viewport.__init__,
1772 arg_names=("hadjustment", "vadjustment"),
1773 category=PyGTKDeprecationWarning,
1774 )
1775
1776 Viewport = override(Viewport)
1777 __all__.append("Viewport")
1778
1779
1780 class TreeModelFilter(Gtk.TreeModelFilter):
1781 def set_visible_func(self, func, data=None):
1782 super().set_visible_func(func, data)
1783
1784 def set_value(self, iter, column, value):
1785 # Delegate to child model
1786 iter = self.convert_iter_to_child_iter(iter)
1787 self.get_model().set_value(iter, column, value)
1788
1789
1790 TreeModelFilter = override(TreeModelFilter)
1791 __all__.append("TreeModelFilter")
1792
1793
1794 if GTK3 or GTK4:
1795
1796 class CssProvider(Gtk.CssProvider):
1797 def load_from_data(self, text, length=-1):
1798 if (Gtk.get_major_version(), Gtk.get_minor_version()) >= (4, 9):
1799 if isinstance(text, bytes):
1800 text = text.decode("utf-8")
1801 super().load_from_data(text, length)
1802 else:
1803 if isinstance(text, str):
1804 text = text.encode("utf-8")
1805 super().load_from_data(text)
1806
1807 CssProvider = override(CssProvider)
1808 __all__.append("CssProvider")
1809
1810 if GTK4:
1811
1812 class CustomSorter(Gtk.CustomSorter):
1813 @classmethod
1814 def new(cls, sort_func, user_data=None):
1815 if sort_func is not None:
1816 compare_func = wrap_list_store_sort_func(sort_func)
1817 else:
1818 compare_func = None
1819
1820 return Gtk.CustomSorter.new(compare_func, user_data)
1821
1822 def set_sort_func(self, sort_func, user_data=None):
1823 if sort_func is not None:
1824 compare_func = wrap_list_store_sort_func(sort_func)
1825 else:
1826 compare_func = None
1827
1828 return super().set_sort_func(compare_func, user_data)
1829
1830 CustomSorter = override(CustomSorter)
1831 __all__.append("CustomSorter")
1832
1833 if GTK3:
1834
1835 class Menu(Gtk.Menu):
1836 def popup(
1837 self, parent_menu_shell, parent_menu_item, func, data, button, activate_time
1838 ):
1839 self.popup_for_device(
1840 None,
1841 parent_menu_shell,
1842 parent_menu_item,
1843 func,
1844 data,
1845 button,
1846 activate_time,
1847 )
1848
1849 Menu = override(Menu)
1850 __all__.append("Menu")
1851
1852 if GTK3:
1853 _Gtk_main_quit = Gtk.main_quit
1854
1855 @override(Gtk.main_quit)
1856 def main_quit(*args):
1857 _Gtk_main_quit()
1858
1859 _Gtk_main = Gtk.main
1860
1861 @override(Gtk.main)
1862 def main(*args, **kwargs):
1863 with (
1864 register_sigint_fallback(Gtk.main_quit),
1865 get_event_loop(GLib.MainContext.default()).running(Gtk.main_quit),
1866 ):
1867 return _Gtk_main(*args, **kwargs)
1868
1869 _Gtk_main_iteration = Gtk.main_iteration
1870 _Gtk_main_iteration_do = Gtk.main_iteration_do
1871
1872 @override(Gtk.main_iteration)
1873 def main_iteration():
1874 with get_event_loop(GLib.MainContext.default()).paused():
1875 return _Gtk_main_iteration()
1876
1877 @override(Gtk.main_iteration)
1878 def main_iteration_do(blocking):
1879 with get_event_loop(GLib.MainContext.default()).paused():
1880 return _Gtk_main_iteration_do(blocking)
1881
1882
1883 if GTK3:
1884 stock_lookup = strip_boolean_result(Gtk.stock_lookup)
1885 __all__.append("stock_lookup")
1886
1887 if not get_option("legacy_autoinit"): # TODO: or GTK5
1888 initialized = False
1889 elif GTK4:
1890 initialized = Gtk.init_check()
1891 else:
1892 initialized, argv = Gtk.init_check(sys.argv)
1893 sys.argv = list(argv)