Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 88
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 215
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 216
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 217
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 218
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 219
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 220
PK ! 1 1 __init__.pynu [ import types
import warnings
import importlib
import sys
from pkgutil import get_loader
from gi import PyGIDeprecationWarning
from gi._gi import CallableInfo
from gi._constants import \
TYPE_NONE, \
TYPE_INVALID
# support overrides in different directories than our gi module
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
# namespace -> (attr, replacement)
_deprecated_attrs = {}
def wraps(wrapped):
def assign(wrapper):
wrapper.__name__ = wrapped.__name__
wrapper.__module__ = wrapped.__module__
return wrapper
return assign
class OverridesProxyModule(types.ModuleType):
"""Wraps a introspection module and contains all overrides"""
def __init__(self, introspection_module):
super(OverridesProxyModule, self).__init__(
introspection_module.__name__)
self._introspection_module = introspection_module
def __getattr__(self, name):
return getattr(self._introspection_module, name)
def __dir__(self):
result = set(dir(self.__class__))
result.update(self.__dict__.keys())
result.update(dir(self._introspection_module))
return sorted(result)
def __repr__(self):
return "<%s %r>" % (type(self).__name__, self._introspection_module)
class _DeprecatedAttribute(object):
"""A deprecation descriptor for OverridesProxyModule subclasses.
Emits a PyGIDeprecationWarning on every access and tries to act as a
normal instance attribute (can be replaced and deleted).
"""
def __init__(self, namespace, attr, value, replacement):
self._attr = attr
self._value = value
self._warning = PyGIDeprecationWarning(
'%s.%s is deprecated; use %s instead' % (
namespace, attr, replacement))
def __get__(self, instance, owner):
if instance is None:
raise AttributeError(self._attr)
warnings.warn(self._warning, stacklevel=2)
return self._value
def __set__(self, instance, value):
attr = self._attr
# delete the descriptor, then set the instance value
delattr(type(instance), attr)
setattr(instance, attr, value)
def __delete__(self, instance):
# delete the descriptor
delattr(type(instance), self._attr)
def load_overrides(introspection_module):
"""Loads overrides for an introspection module.
Either returns the same module again in case there are no overrides or a
proxy module including overrides. Doesn't cache the result.
"""
namespace = introspection_module.__name__.rsplit(".", 1)[-1]
module_key = 'gi.repository.' + namespace
# We use sys.modules so overrides can import from gi.repository
# but restore everything at the end so this doesn't have any side effects
has_old = module_key in sys.modules
old_module = sys.modules.get(module_key)
# Create a new sub type, so we can separate descriptors like
# _DeprecatedAttribute for each namespace.
proxy_type = type(namespace + "ProxyModule", (OverridesProxyModule, ), {})
proxy = proxy_type(introspection_module)
sys.modules[module_key] = proxy
# backwards compat:
# gedit uses gi.importer.modules['Gedit']._introspection_module
from ..importer import modules
assert hasattr(proxy, "_introspection_module")
modules[namespace] = proxy
try:
override_package_name = 'gi.overrides.' + namespace
# http://bugs.python.org/issue14710
try:
override_loader = get_loader(override_package_name)
except AttributeError:
override_loader = None
# Avoid checking for an ImportError, an override might
# depend on a missing module thus causing an ImportError
if override_loader is None:
return introspection_module
override_mod = importlib.import_module(override_package_name)
finally:
del modules[namespace]
del sys.modules[module_key]
if has_old:
sys.modules[module_key] = old_module
# backwards compat: for gst-python/gstmodule.c,
# which tries to access Gst.Fraction through
# Gst._overrides_module.Fraction. We assign the proxy instead as that
# contains all overridden classes like Fraction during import anyway and
# there is no need to keep the real override module alive.
proxy._overrides_module = proxy
override_all = []
if hasattr(override_mod, "__all__"):
override_all = override_mod.__all__
for var in override_all:
try:
item = getattr(override_mod, var)
except (AttributeError, TypeError):
# Gedit puts a non-string in __all__, so catch TypeError here
continue
setattr(proxy, var, item)
# Replace deprecated module level attributes with a descriptor
# which emits a warning when accessed.
for attr, replacement in _deprecated_attrs.pop(namespace, []):
try:
value = getattr(proxy, attr)
except AttributeError:
raise AssertionError(
"%s was set deprecated but wasn't added to __all__" % attr)
delattr(proxy, attr)
deprecated_attr = _DeprecatedAttribute(
namespace, attr, value, replacement)
setattr(proxy_type, attr, deprecated_attr)
return proxy
def override(type_):
"""Decorator for registering an override.
Other than objects added to __all__, these can get referenced in the same
override module via the gi.repository module (get_parent_for_object() does
for example), so they have to be added to the module immediately.
"""
if isinstance(type_, CallableInfo):
func = type_
namespace = func.__module__.rsplit('.', 1)[-1]
module = sys.modules["gi.repository." + namespace]
def wrapper(func):
setattr(module, func.__name__, func)
return func
return wrapper
elif isinstance(type_, types.FunctionType):
raise TypeError("func must be a gi function, got %s" % type_)
else:
try:
info = getattr(type_, '__info__')
except AttributeError:
raise TypeError(
'Can not override a type %s, which is not in a gobject '
'introspection typelib' % type_.__name__)
if not type_.__module__.startswith('gi.overrides'):
raise KeyError(
'You have tried override outside of the overrides module. '
'This is not allowed (%s, %s)' % (type_, type_.__module__))
g_type = info.get_g_type()
assert g_type != TYPE_NONE
if g_type != TYPE_INVALID:
g_type.pytype = type_
namespace = type_.__module__.rsplit(".", 1)[-1]
module = sys.modules["gi.repository." + namespace]
setattr(module, type_.__name__, type_)
return type_
overridefunc = override
"""Deprecated"""
def deprecated(fn, replacement):
"""Decorator for marking methods and classes as deprecated"""
@wraps(fn)
def wrapped(*args, **kwargs):
warnings.warn('%s is deprecated; use %s instead' % (fn.__name__, replacement),
PyGIDeprecationWarning, stacklevel=2)
return fn(*args, **kwargs)
return wrapped
def deprecated_attr(namespace, attr, replacement):
"""Marks a module level attribute as deprecated. Accessing it will emit
a PyGIDeprecationWarning warning.
e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")``
accessing GObject.STATUS_FOO will emit:
"GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead"
:param str namespace:
The namespace of the override this is called in.
:param str namespace:
The attribute name (which gets added to __all__).
:param str replacement:
The replacement text which will be included in the warning.
"""
_deprecated_attrs.setdefault(namespace, []).append((attr, replacement))
def deprecated_init(super_init_func, arg_names, ignore=tuple(),
deprecated_aliases={}, deprecated_defaults={},
category=PyGIDeprecationWarning,
stacklevel=2):
"""Wrapper for deprecating GObject based __init__ methods which specify
defaults already available or non-standard defaults.
:param callable super_init_func:
Initializer to wrap.
:param list arg_names:
Ordered argument name list.
:param list ignore:
List of argument names to ignore when calling the wrapped function.
This is useful for function which take a non-standard keyword that is munged elsewhere.
:param dict deprecated_aliases:
Dictionary mapping a keyword alias to the actual g_object_newv keyword.
:param dict deprecated_defaults:
Dictionary of non-standard defaults that will be used when the
keyword is not explicitly passed.
:param Exception category:
Exception category of the error.
:param int stacklevel:
Stack level for the deprecation passed on to warnings.warn
:returns: Wrapped version of ``super_init_func`` which gives a deprecation
warning when non-keyword args or aliases are used.
:rtype: callable
"""
# We use a list of argument names to maintain order of the arguments
# being deprecated. This allows calls with positional arguments to
# continue working but with a deprecation message.
def new_init(self, *args, **kwargs):
"""Initializer for a GObject based classes with support for property
sets through the use of explicit keyword arguments.
"""
# Print warnings for calls with positional arguments.
if args:
warnings.warn('Using positional arguments with the GObject constructor has been deprecated. '
'Please specify keyword(s) for "%s" or use a class specific constructor. '
'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' %
', '.join(arg_names[:len(args)]),
category, stacklevel=stacklevel)
new_kwargs = dict(zip(arg_names, args))
else:
new_kwargs = {}
new_kwargs.update(kwargs)
# Print warnings for alias usage and transfer them into the new key.
aliases_used = []
for key, alias in deprecated_aliases.items():
if alias in new_kwargs:
new_kwargs[key] = new_kwargs.pop(alias)
aliases_used.append(key)
if aliases_used:
warnings.warn('The keyword(s) "%s" have been deprecated in favor of "%s" respectively. '
'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' %
(', '.join(deprecated_aliases[k] for k in sorted(aliases_used)),
', '.join(sorted(aliases_used))),
category, stacklevel=stacklevel)
# Print warnings for defaults different than what is already provided by the property
defaults_used = []
for key, value in deprecated_defaults.items():
if key not in new_kwargs:
new_kwargs[key] = deprecated_defaults[key]
defaults_used.append(key)
if defaults_used:
warnings.warn('Initializer is relying on deprecated non-standard '
'defaults. Please update to explicitly use: %s '
'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' %
', '.join('%s=%s' % (k, deprecated_defaults[k]) for k in sorted(defaults_used)),
category, stacklevel=stacklevel)
# Remove keywords that should be ignored.
for key in ignore:
if key in new_kwargs:
new_kwargs.pop(key)
return super_init_func(self, **new_kwargs)
return new_init
def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None):
"""Translate method's return value for stripping off success flag.
There are a lot of methods which return a "success" boolean and have
several out arguments. Translate such a method to return the out arguments
on success and None on failure.
"""
@wraps(method)
def wrapped(*args, **kwargs):
ret = method(*args, **kwargs)
if ret[0]:
if len(ret) == 2:
return ret[1]
else:
return ret[1:]
else:
if exc_type:
raise exc_type(exc_str or 'call failed')
return fail_ret
return wrapped
PK ! 5a Gtk.pynu [ # -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2009 Johan Dahlin
# 2010 Simon van der Linden
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
import collections
import sys
import warnings
from gi.repository import GObject
from .._ossighelper import wakeup_on_signal, register_sigint_fallback
from ..overrides import override, strip_boolean_result, deprecated_init
from ..module import get_introspection_module
from gi import PyGIDeprecationWarning
if sys.version_info >= (3, 0):
_basestring = str
else:
_basestring = basestring
Gtk = get_introspection_module('Gtk')
__all__ = []
if Gtk._version == '2.0':
warn_msg = "You have imported the Gtk 2.0 module. Because Gtk 2.0 \
was not designed for use with introspection some of the \
interfaces and API will fail. As such this is not supported \
by the pygobject development team and we encourage you to \
port your app to Gtk 3 or greater. PyGTK is the recomended \
python module to use with Gtk 2.0"
warnings.warn(warn_msg, RuntimeWarning)
class PyGTKDeprecationWarning(PyGIDeprecationWarning):
pass
__all__.append('PyGTKDeprecationWarning')
def _construct_target_list(targets):
"""Create a list of TargetEntry items from a list of tuples in the form (target, flags, info)
The list can also contain existing TargetEntry items in which case the existing entry
is re-used in the return list.
"""
target_entries = []
for entry in targets:
if not isinstance(entry, Gtk.TargetEntry):
entry = Gtk.TargetEntry.new(*entry)
target_entries.append(entry)
return target_entries
__all__.append('_construct_target_list')
def _extract_handler_and_args(obj_or_map, handler_name):
handler = None
if isinstance(obj_or_map, collections.Mapping):
handler = obj_or_map.get(handler_name, None)
else:
handler = getattr(obj_or_map, handler_name, None)
if handler is None:
raise AttributeError('Handler %s not found' % handler_name)
args = ()
if isinstance(handler, collections.Sequence):
if len(handler) == 0:
raise TypeError("Handler %s tuple can not be empty" % handler)
args = handler[1:]
handler = handler[0]
elif not callable(handler):
raise TypeError('Handler %s is not a method, function or tuple' % handler)
return handler, args
# Exposed for unit-testing.
__all__.append('_extract_handler_and_args')
def _builder_connect_callback(builder, gobj, signal_name, handler_name, connect_obj, flags, obj_or_map):
handler, args = _extract_handler_and_args(obj_or_map, handler_name)
after = flags & GObject.ConnectFlags.AFTER
if connect_obj is not None:
if after:
gobj.connect_object_after(signal_name, handler, connect_obj, *args)
else:
gobj.connect_object(signal_name, handler, connect_obj, *args)
else:
if after:
gobj.connect_after(signal_name, handler, *args)
else:
gobj.connect(signal_name, handler, *args)
class Widget(Gtk.Widget):
translate_coordinates = strip_boolean_result(Gtk.Widget.translate_coordinates)
def drag_dest_set_target_list(self, target_list):
if (target_list is not None) and (not isinstance(target_list, Gtk.TargetList)):
target_list = Gtk.TargetList.new(_construct_target_list(target_list))
super(Widget, self).drag_dest_set_target_list(target_list)
def drag_source_set_target_list(self, target_list):
if (target_list is not None) and (not isinstance(target_list, Gtk.TargetList)):
target_list = Gtk.TargetList.new(_construct_target_list(target_list))
super(Widget, self).drag_source_set_target_list(target_list)
def style_get_property(self, property_name, value=None):
if value is None:
prop = self.find_style_property(property_name)
if prop is None:
raise ValueError('Class "%s" does not contain style property "%s"' %
(self, property_name))
value = GObject.Value(prop.value_type)
Gtk.Widget.style_get_property(self, property_name, value)
return value.get_value()
Widget = override(Widget)
__all__.append('Widget')
class Container(Gtk.Container, Widget):
def __len__(self):
return len(self.get_children())
def __contains__(self, child):
return child in self.get_children()
def __iter__(self):
return iter(self.get_children())
def __bool__(self):
return True
# alias for Python 2.x object protocol
__nonzero__ = __bool__
get_focus_chain = strip_boolean_result(Gtk.Container.get_focus_chain)
def child_get_property(self, child, property_name, value=None):
if value is None:
prop = self.find_child_property(property_name)
if prop is None:
raise ValueError('Class "%s" does not contain child property "%s"' %
(self, property_name))
value = GObject.Value(prop.value_type)
Gtk.Container.child_get_property(self, child, property_name, value)
return value.get_value()
def child_get(self, child, *prop_names):
"""Returns a list of child property values for the given names."""
return [self.child_get_property(child, name) for name in prop_names]
def child_set(self, child, **kwargs):
"""Set a child properties on the given child to key/value pairs."""
for name, value in kwargs.items():
name = name.replace('_', '-')
self.child_set_property(child, name, value)
Container = override(Container)
__all__.append('Container')
class Editable(Gtk.Editable):
def insert_text(self, text, position):
return super(Editable, self).insert_text(text, -1, position)
get_selection_bounds = strip_boolean_result(Gtk.Editable.get_selection_bounds, fail_ret=())
Editable = override(Editable)
__all__.append("Editable")
if Gtk._version in ("2.0", "3.0"):
class Action(Gtk.Action):
__init__ = deprecated_init(Gtk.Action.__init__,
arg_names=('name', 'label', 'tooltip', 'stock_id'),
category=PyGTKDeprecationWarning)
Action = override(Action)
__all__.append("Action")
class RadioAction(Gtk.RadioAction):
__init__ = deprecated_init(Gtk.RadioAction.__init__,
arg_names=('name', 'label', 'tooltip', 'stock_id', 'value'),
category=PyGTKDeprecationWarning)
RadioAction = override(RadioAction)
__all__.append("RadioAction")
class ActionGroup(Gtk.ActionGroup):
__init__ = deprecated_init(Gtk.ActionGroup.__init__,
arg_names=('name',),
category=PyGTKDeprecationWarning)
def add_actions(self, entries, user_data=None):
"""
The add_actions() method is a convenience method that creates a number
of gtk.Action objects based on the information in the list of action
entry tuples contained in entries and adds them to the action group.
The entry tuples can vary in size from one to six items with the
following information:
* The name of the action. Must be specified.
* The stock id for the action. Optional with a default value of None
if a label is specified.
* The label for the action. This field should typically be marked
for translation, see the set_translation_domain() method. Optional
with a default value of None if a stock id is specified.
* The accelerator for the action, in the format understood by the
gtk.accelerator_parse() function. Optional with a default value of
None.
* The tooltip for the action. This field should typically be marked
for translation, see the set_translation_domain() method. Optional
with a default value of None.
* The callback function invoked when the action is activated.
Optional with a default value of None.
The "activate" signals of the actions are connected to the callbacks and
their accel paths are set to /group-name/action-name.
"""
try:
iter(entries)
except (TypeError):
raise TypeError('entries must be iterable')
def _process_action(name, stock_id=None, label=None, accelerator=None, tooltip=None, callback=None):
action = Action(name=name, label=label, tooltip=tooltip, stock_id=stock_id)
if callback is not None:
if user_data is None:
action.connect('activate', callback)
else:
action.connect('activate', callback, user_data)
self.add_action_with_accel(action, accelerator)
for e in entries:
# using inner function above since entries can leave out optional arguments
_process_action(*e)
def add_toggle_actions(self, entries, user_data=None):
"""
The add_toggle_actions() method is a convenience method that creates a
number of gtk.ToggleAction objects based on the information in the list
of action entry tuples contained in entries and adds them to the action
group. The toggle action entry tuples can vary in size from one to seven
items with the following information:
* The name of the action. Must be specified.
* The stock id for the action. Optional with a default value of None
if a label is specified.
* The label for the action. This field should typically be marked
for translation, see the set_translation_domain() method. Optional
with a default value of None if a stock id is specified.
* The accelerator for the action, in the format understood by the
gtk.accelerator_parse() function. Optional with a default value of
None.
* The tooltip for the action. This field should typically be marked
for translation, see the set_translation_domain() method. Optional
with a default value of None.
* The callback function invoked when the action is activated.
Optional with a default value of None.
* A flag indicating whether the toggle action is active. Optional
with a default value of False.
The "activate" signals of the actions are connected to the callbacks and
their accel paths are set to /group-name/action-name.
"""
try:
iter(entries)
except (TypeError):
raise TypeError('entries must be iterable')
def _process_action(name, stock_id=None, label=None, accelerator=None, tooltip=None, callback=None, is_active=False):
action = Gtk.ToggleAction(name=name, label=label, tooltip=tooltip, stock_id=stock_id)
action.set_active(is_active)
if callback is not None:
if user_data is None:
action.connect('activate', callback)
else:
action.connect('activate', callback, user_data)
self.add_action_with_accel(action, accelerator)
for e in entries:
# using inner function above since entries can leave out optional arguments
_process_action(*e)
def add_radio_actions(self, entries, value=None, on_change=None, user_data=None):
"""
The add_radio_actions() method is a convenience method that creates a
number of gtk.RadioAction objects based on the information in the list
of action entry tuples contained in entries and adds them to the action
group. The entry tuples can vary in size from one to six items with the
following information:
* The name of the action. Must be specified.
* The stock id for the action. Optional with a default value of None
if a label is specified.
* The label for the action. This field should typically be marked
for translation, see the set_translation_domain() method. Optional
with a default value of None if a stock id is specified.
* The accelerator for the action, in the format understood by the
gtk.accelerator_parse() function. Optional with a default value of
None.
* The tooltip for the action. This field should typically be marked
for translation, see the set_translation_domain() method. Optional
with a default value of None.
* The value to set on the radio action. Optional with a default
value of 0. Should be specified in applications.
The value parameter specifies the radio action that should be set
active. The "changed" signal of the first radio action is connected to
the on_change callback (if specified and not None) and the accel paths
of the actions are set to /group-name/action-name.
"""
try:
iter(entries)
except (TypeError):
raise TypeError('entries must be iterable')
first_action = None
def _process_action(group_source, name, stock_id=None, label=None, accelerator=None, tooltip=None, entry_value=0):
action = RadioAction(name=name, label=label, tooltip=tooltip, stock_id=stock_id, value=entry_value)
# FIXME: join_group is a patch to Gtk+ 3.0
# otherwise we can't effectively add radio actions to a
# group. Should we depend on 3.0 and error out here
# or should we offer the functionality via a compat
# C module?
if hasattr(action, 'join_group'):
action.join_group(group_source)
if value == entry_value:
action.set_active(True)
self.add_action_with_accel(action, accelerator)
return action
for e in entries:
# using inner function above since entries can leave out optional arguments
action = _process_action(first_action, *e)
if first_action is None:
first_action = action
if first_action is not None and on_change is not None:
if user_data is None:
first_action.connect('changed', on_change)
else:
first_action.connect('changed', on_change, user_data)
ActionGroup = override(ActionGroup)
__all__.append('ActionGroup')
class UIManager(Gtk.UIManager):
def add_ui_from_string(self, buffer):
if not isinstance(buffer, _basestring):
raise TypeError('buffer must be a string')
length = len(buffer.encode('UTF-8'))
return Gtk.UIManager.add_ui_from_string(self, buffer, length)
def insert_action_group(self, buffer, length=-1):
return Gtk.UIManager.insert_action_group(self, buffer, length)
UIManager = override(UIManager)
__all__.append('UIManager')
class ComboBox(Gtk.ComboBox, Container):
get_active_iter = strip_boolean_result(Gtk.ComboBox.get_active_iter)
ComboBox = override(ComboBox)
__all__.append('ComboBox')
class Box(Gtk.Box):
__init__ = deprecated_init(Gtk.Box.__init__,
arg_names=('homogeneous', 'spacing'),
category=PyGTKDeprecationWarning)
Box = override(Box)
__all__.append('Box')
class SizeGroup(Gtk.SizeGroup):
__init__ = deprecated_init(Gtk.SizeGroup.__init__,
arg_names=('mode',),
deprecated_defaults={'mode': Gtk.SizeGroupMode.VERTICAL},
category=PyGTKDeprecationWarning)
SizeGroup = override(SizeGroup)
__all__.append('SizeGroup')
class MenuItem(Gtk.MenuItem):
__init__ = deprecated_init(Gtk.MenuItem.__init__,
arg_names=('label',),
category=PyGTKDeprecationWarning)
MenuItem = override(MenuItem)
__all__.append('MenuItem')
class Builder(Gtk.Builder):
def connect_signals(self, obj_or_map):
"""Connect signals specified by this builder to a name, handler mapping.
Connect signal, name, and handler sets specified in the builder with
the given mapping "obj_or_map". The handler/value aspect of the mapping
can also contain a tuple in the form of (handler [,arg1 [,argN]])
allowing for extra arguments to be passed to the handler. For example:
.. code-block:: python
builder.connect_signals({'on_clicked': (on_clicked, arg1, arg2)})
"""
self.connect_signals_full(_builder_connect_callback, obj_or_map)
def add_from_string(self, buffer):
if not isinstance(buffer, _basestring):
raise TypeError('buffer must be a string')
length = len(buffer)
return Gtk.Builder.add_from_string(self, buffer, length)
def add_objects_from_string(self, buffer, object_ids):
if not isinstance(buffer, _basestring):
raise TypeError('buffer must be a string')
length = len(buffer)
return Gtk.Builder.add_objects_from_string(self, buffer, length, object_ids)
Builder = override(Builder)
__all__.append('Builder')
# NOTE: This must come before any other Window/Dialog subclassing, to ensure
# that we have a correct inheritance hierarchy.
class Window(Gtk.Window):
__init__ = deprecated_init(Gtk.Window.__init__,
arg_names=('type',),
category=PyGTKDeprecationWarning)
Window = override(Window)
__all__.append('Window')
class Dialog(Gtk.Dialog, Container):
_old_arg_names = ('title', 'parent', 'flags', 'buttons', '_buttons_property')
_init = deprecated_init(Gtk.Dialog.__init__,
arg_names=('title', 'transient_for', 'flags',
'add_buttons', 'buttons'),
ignore=('flags', 'add_buttons'),
deprecated_aliases={'transient_for': 'parent',
'buttons': '_buttons_property'},
category=PyGTKDeprecationWarning)
def __init__(self, *args, **kwargs):
new_kwargs = kwargs.copy()
old_kwargs = dict(zip(self._old_arg_names, args))
old_kwargs.update(kwargs)
# Increment the warning stacklevel for sub-classes which implement their own __init__.
stacklevel = 2
if self.__class__ != Dialog and self.__class__.__init__ != Dialog.__init__:
stacklevel += 1
# buttons was overloaded by PyGtk but is needed for Gtk.MessageDialog
# as a pass through, so type check the argument and give a deprecation
# when it is not of type Gtk.ButtonsType
add_buttons = old_kwargs.get('buttons', None)
if add_buttons is not None and not isinstance(add_buttons, Gtk.ButtonsType):
warnings.warn('The "buttons" argument must be a Gtk.ButtonsType enum value. '
'Please use the "add_buttons" method for adding buttons. '
'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
PyGTKDeprecationWarning, stacklevel=stacklevel)
if 'buttons' in new_kwargs:
del new_kwargs['buttons']
else:
add_buttons = None
flags = old_kwargs.get('flags', 0)
if flags:
warnings.warn('The "flags" argument for dialog construction is deprecated. '
'Please use initializer keywords: modal=True and/or destroy_with_parent=True. '
'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
PyGTKDeprecationWarning, stacklevel=stacklevel)
if flags & Gtk.DialogFlags.MODAL:
new_kwargs['modal'] = True
if flags & Gtk.DialogFlags.DESTROY_WITH_PARENT:
new_kwargs['destroy_with_parent'] = True
self._init(*args, **new_kwargs)
if add_buttons:
self.add_buttons(*add_buttons)
def run(self, *args, **kwargs):
with register_sigint_fallback(self.destroy):
with wakeup_on_signal():
return Gtk.Dialog.run(self, *args, **kwargs)
action_area = property(lambda dialog: dialog.get_action_area())
vbox = property(lambda dialog: dialog.get_content_area())
def add_buttons(self, *args):
"""
The add_buttons() method adds several buttons to the Gtk.Dialog using
the button data passed as arguments to the method. This method is the
same as calling the Gtk.Dialog.add_button() repeatedly. The button data
pairs - button text (or stock ID) and a response ID integer are passed
individually. For example:
.. code-block:: python
dialog.add_buttons(Gtk.STOCK_OPEN, 42, "Close", Gtk.ResponseType.CLOSE)
will add "Open" and "Close" buttons to dialog.
"""
def _button(b):
while b:
t, r = b[0:2]
b = b[2:]
yield t, r
try:
for text, response in _button(args):
self.add_button(text, response)
except (IndexError):
raise TypeError('Must pass an even number of arguments')
Dialog = override(Dialog)
__all__.append('Dialog')
class MessageDialog(Gtk.MessageDialog, Dialog):
__init__ = deprecated_init(Gtk.MessageDialog.__init__,
arg_names=('parent', 'flags', 'message_type',
'buttons', 'message_format'),
deprecated_aliases={'text': 'message_format',
'message_type': 'type'},
category=PyGTKDeprecationWarning)
def format_secondary_text(self, message_format):
self.set_property('secondary-use-markup', False)
self.set_property('secondary-text', message_format)
def format_secondary_markup(self, message_format):
self.set_property('secondary-use-markup', True)
self.set_property('secondary-text', message_format)
MessageDialog = override(MessageDialog)
__all__.append('MessageDialog')
if Gtk._version in ("2.0", "3.0"):
class ColorSelectionDialog(Gtk.ColorSelectionDialog):
__init__ = deprecated_init(Gtk.ColorSelectionDialog.__init__,
arg_names=('title',),
category=PyGTKDeprecationWarning)
ColorSelectionDialog = override(ColorSelectionDialog)
__all__.append('ColorSelectionDialog')
class FileChooserDialog(Gtk.FileChooserDialog):
__init__ = deprecated_init(Gtk.FileChooserDialog.__init__,
arg_names=('title', 'parent', 'action', 'buttons'),
category=PyGTKDeprecationWarning)
FileChooserDialog = override(FileChooserDialog)
__all__.append('FileChooserDialog')
if Gtk._version in ("2.0", "3.0"):
class FontSelectionDialog(Gtk.FontSelectionDialog):
__init__ = deprecated_init(Gtk.FontSelectionDialog.__init__,
arg_names=('title',),
category=PyGTKDeprecationWarning)
FontSelectionDialog = override(FontSelectionDialog)
__all__.append('FontSelectionDialog')
class RecentChooserDialog(Gtk.RecentChooserDialog):
# Note, the "manager" keyword must work across the entire 3.x series because
# "recent_manager" is not backwards compatible with PyGObject versions prior to 3.10.
__init__ = deprecated_init(Gtk.RecentChooserDialog.__init__,
arg_names=('title', 'parent', 'recent_manager', 'buttons'),
deprecated_aliases={'recent_manager': 'manager'},
category=PyGTKDeprecationWarning)
RecentChooserDialog = override(RecentChooserDialog)
__all__.append('RecentChooserDialog')
class IconView(Gtk.IconView):
__init__ = deprecated_init(Gtk.IconView.__init__,
arg_names=('model',),
category=PyGTKDeprecationWarning)
get_item_at_pos = strip_boolean_result(Gtk.IconView.get_item_at_pos)
get_visible_range = strip_boolean_result(Gtk.IconView.get_visible_range)
get_dest_item_at_pos = strip_boolean_result(Gtk.IconView.get_dest_item_at_pos)
IconView = override(IconView)
__all__.append('IconView')
class ToolButton(Gtk.ToolButton):
__init__ = deprecated_init(Gtk.ToolButton.__init__,
arg_names=('stock_id',),
category=PyGTKDeprecationWarning)
ToolButton = override(ToolButton)
__all__.append('ToolButton')
class IMContext(Gtk.IMContext):
get_surrounding = strip_boolean_result(Gtk.IMContext.get_surrounding)
IMContext = override(IMContext)
__all__.append('IMContext')
class RecentInfo(Gtk.RecentInfo):
get_application_info = strip_boolean_result(Gtk.RecentInfo.get_application_info)
RecentInfo = override(RecentInfo)
__all__.append('RecentInfo')
class TextBuffer(Gtk.TextBuffer):
def _get_or_create_tag_table(self):
table = self.get_tag_table()
if table is None:
table = Gtk.TextTagTable()
self.set_tag_table(table)
return table
def create_tag(self, tag_name=None, **properties):
"""Creates a tag and adds it to the tag table of the TextBuffer.
:param str tag_name:
Name of the new tag, or None
:param **properties:
Keyword list of properties and their values
This is equivalent to creating a Gtk.TextTag and then adding the
tag to the buffer's tag table. The returned tag is owned by
the buffer's tag table.
If ``tag_name`` is None, the tag is anonymous.
If ``tag_name`` is not None, a tag called ``tag_name`` must not already
exist in the tag table for this buffer.
Properties are passed as a keyword list of names and values (e.g.
foreground='DodgerBlue', weight=Pango.Weight.BOLD)
:returns:
A new tag.
"""
tag = Gtk.TextTag(name=tag_name, **properties)
self._get_or_create_tag_table().add(tag)
return tag
def create_mark(self, mark_name, where, left_gravity=False):
return Gtk.TextBuffer.create_mark(self, mark_name, where, left_gravity)
def set_text(self, text, length=-1):
Gtk.TextBuffer.set_text(self, text, length)
def insert(self, iter, text, length=-1):
if not isinstance(text, _basestring):
raise TypeError('text must be a string, not %s' % type(text))
Gtk.TextBuffer.insert(self, iter, text, length)
def insert_with_tags(self, iter, text, *tags):
start_offset = iter.get_offset()
self.insert(iter, text)
if not tags:
return
start = self.get_iter_at_offset(start_offset)
for tag in tags:
self.apply_tag(tag, start, iter)
def insert_with_tags_by_name(self, iter, text, *tags):
tag_objs = []
for tag in tags:
tag_obj = self.get_tag_table().lookup(tag)
if not tag_obj:
raise ValueError('unknown text tag: %s' % tag)
tag_objs.append(tag_obj)
self.insert_with_tags(iter, text, *tag_objs)
def insert_at_cursor(self, text, length=-1):
if not isinstance(text, _basestring):
raise TypeError('text must be a string, not %s' % type(text))
Gtk.TextBuffer.insert_at_cursor(self, text, length)
get_selection_bounds = strip_boolean_result(Gtk.TextBuffer.get_selection_bounds, fail_ret=())
TextBuffer = override(TextBuffer)
__all__.append('TextBuffer')
class TextIter(Gtk.TextIter):
forward_search = strip_boolean_result(Gtk.TextIter.forward_search)
backward_search = strip_boolean_result(Gtk.TextIter.backward_search)
TextIter = override(TextIter)
__all__.append('TextIter')
class TreeModel(Gtk.TreeModel):
def __len__(self):
return self.iter_n_children(None)
def __bool__(self):
return True
# alias for Python 2.x object protocol
__nonzero__ = __bool__
def _getiter(self, key):
if isinstance(key, Gtk.TreeIter):
return key
elif isinstance(key, int) and key < 0:
index = len(self) + key
if index < 0:
raise IndexError("row index is out of bounds: %d" % key)
try:
aiter = self.get_iter(index)
except ValueError:
raise IndexError("could not find tree path '%s'" % key)
return aiter
else:
try:
aiter = self.get_iter(key)
except ValueError:
raise IndexError("could not find tree path '%s'" % key)
return aiter
def _coerce_path(self, path):
if isinstance(path, Gtk.TreePath):
return path
else:
return TreePath(path)
def __getitem__(self, key):
aiter = self._getiter(key)
return TreeModelRow(self, aiter)
def __setitem__(self, key, value):
row = self[key]
self.set_row(row.iter, value)
def __delitem__(self, key):
aiter = self._getiter(key)
self.remove(aiter)
def __iter__(self):
return TreeModelRowIter(self, self.get_iter_first())
get_iter_first = strip_boolean_result(Gtk.TreeModel.get_iter_first)
iter_children = strip_boolean_result(Gtk.TreeModel.iter_children)
iter_nth_child = strip_boolean_result(Gtk.TreeModel.iter_nth_child)
iter_parent = strip_boolean_result(Gtk.TreeModel.iter_parent)
get_iter_from_string = strip_boolean_result(Gtk.TreeModel.get_iter_from_string,
ValueError, 'invalid tree path')
def get_iter(self, path):
path = self._coerce_path(path)
success, aiter = super(TreeModel, self).get_iter(path)
if not success:
raise ValueError("invalid tree path '%s'" % path)
return aiter
def iter_next(self, aiter):
next_iter = aiter.copy()
success = super(TreeModel, self).iter_next(next_iter)
if success:
return next_iter
def iter_previous(self, aiter):
prev_iter = aiter.copy()
success = super(TreeModel, self).iter_previous(prev_iter)
if success:
return prev_iter
def _convert_row(self, row):
# TODO: Accept a dictionary for row
# model.append(None,{COLUMN_ICON: icon, COLUMN_NAME: name})
if isinstance(row, str):
raise TypeError('Expected a list or tuple, but got str')
n_columns = self.get_n_columns()
if len(row) != n_columns:
raise ValueError('row sequence has the incorrect number of elements')
result = []
columns = []
for cur_col, value in enumerate(row):
# do not try to set None values, they are causing warnings
if value is None:
continue
result.append(self._convert_value(cur_col, value))
columns.append(cur_col)
return (result, columns)
def set_row(self, treeiter, row):
converted_row, columns = self._convert_row(row)
for column in columns:
value = row[column]
if value is None:
continue # None means skip this row
self.set_value(treeiter, column, value)
def _convert_value(self, column, value):
'''Convert value to a GObject.Value of the expected type'''
if isinstance(value, GObject.Value):
return value
return GObject.Value(self.get_column_type(column), value)
def get(self, treeiter, *columns):
n_columns = self.get_n_columns()
values = []
for col in columns:
if not isinstance(col, int):
raise TypeError("column numbers must be ints")
if col < 0 or col >= n_columns:
raise ValueError("column number is out of range")
values.append(self.get_value(treeiter, col))
return tuple(values)
#
# Signals supporting python iterables as tree paths
#
def row_changed(self, path, iter):
return super(TreeModel, self).row_changed(self._coerce_path(path), iter)
def row_inserted(self, path, iter):
return super(TreeModel, self).row_inserted(self._coerce_path(path), iter)
def row_has_child_toggled(self, path, iter):
return super(TreeModel, self).row_has_child_toggled(self._coerce_path(path),
iter)
def row_deleted(self, path):
return super(TreeModel, self).row_deleted(self._coerce_path(path))
def rows_reordered(self, path, iter, new_order):
return super(TreeModel, self).rows_reordered(self._coerce_path(path),
iter, new_order)
TreeModel = override(TreeModel)
__all__.append('TreeModel')
class TreeSortable(Gtk.TreeSortable, ):
get_sort_column_id = strip_boolean_result(Gtk.TreeSortable.get_sort_column_id, fail_ret=(None, None))
def set_sort_func(self, sort_column_id, sort_func, user_data=None):
super(TreeSortable, self).set_sort_func(sort_column_id, sort_func, user_data)
def set_default_sort_func(self, sort_func, user_data=None):
super(TreeSortable, self).set_default_sort_func(sort_func, user_data)
TreeSortable = override(TreeSortable)
__all__.append('TreeSortable')
class TreeModelSort(Gtk.TreeModelSort):
__init__ = deprecated_init(Gtk.TreeModelSort.__init__,
arg_names=('model',),
category=PyGTKDeprecationWarning)
TreeModelSort = override(TreeModelSort)
__all__.append('TreeModelSort')
class ListStore(Gtk.ListStore, TreeModel, TreeSortable):
def __init__(self, *column_types):
Gtk.ListStore.__init__(self)
self.set_column_types(column_types)
def _do_insert(self, position, row):
if row is not None:
row, columns = self._convert_row(row)
treeiter = self.insert_with_valuesv(position, columns, row)
else:
treeiter = Gtk.ListStore.insert(self, position)
return treeiter
def append(self, row=None):
if row:
return self._do_insert(-1, row)
# gtk_list_store_insert() does not know about the "position == -1"
# case, so use append() here
else:
return Gtk.ListStore.append(self)
def prepend(self, row=None):
return self._do_insert(0, row)
def insert(self, position, row=None):
return self._do_insert(position, row)
# FIXME: sends two signals; check if this can use an atomic
# insert_with_valuesv()
def insert_before(self, sibling, row=None):
treeiter = Gtk.ListStore.insert_before(self, sibling)
if row is not None:
self.set_row(treeiter, row)
return treeiter
# FIXME: sends two signals; check if this can use an atomic
# insert_with_valuesv()
def insert_after(self, sibling, row=None):
treeiter = Gtk.ListStore.insert_after(self, sibling)
if row is not None:
self.set_row(treeiter, row)
return treeiter
def set_value(self, treeiter, column, value):
value = self._convert_value(column, value)
Gtk.ListStore.set_value(self, treeiter, column, value)
def set(self, treeiter, *args):
def _set_lists(cols, vals):
if len(cols) != len(vals):
raise TypeError('The number of columns do not match the number of values')
columns = []
values = []
for col_num, value in zip(cols, vals):
if not isinstance(col_num, int):
raise TypeError('TypeError: Expected integer argument for column.')
columns.append(col_num)
values.append(self._convert_value(col_num, value))
Gtk.ListStore.set(self, treeiter, columns, values)
if args:
if isinstance(args[0], int):
_set_lists(args[::2], args[1::2])
elif isinstance(args[0], (tuple, list)):
if len(args) != 2:
raise TypeError('Too many arguments')
_set_lists(args[0], args[1])
elif isinstance(args[0], dict):
_set_lists(list(args[0]), args[0].values())
else:
raise TypeError('Argument list must be in the form of (column, value, ...), ((columns,...), (values, ...)) or {column: value}. No -1 termination is needed.')
ListStore = override(ListStore)
__all__.append('ListStore')
class TreeModelRow(object):
def __init__(self, model, iter_or_path):
if not isinstance(model, Gtk.TreeModel):
raise TypeError("expected Gtk.TreeModel, %s found" % type(model).__name__)
self.model = model
if isinstance(iter_or_path, Gtk.TreePath):
self.iter = model.get_iter(iter_or_path)
elif isinstance(iter_or_path, Gtk.TreeIter):
self.iter = iter_or_path
else:
raise TypeError("expected Gtk.TreeIter or Gtk.TreePath, \
%s found" % type(iter_or_path).__name__)
@property
def path(self):
return self.model.get_path(self.iter)
@property
def next(self):
return self.get_next()
@property
def previous(self):
return self.get_previous()
@property
def parent(self):
return self.get_parent()
def get_next(self):
next_iter = self.model.iter_next(self.iter)
if next_iter:
return TreeModelRow(self.model, next_iter)
def get_previous(self):
prev_iter = self.model.iter_previous(self.iter)
if prev_iter:
return TreeModelRow(self.model, prev_iter)
def get_parent(self):
parent_iter = self.model.iter_parent(self.iter)
if parent_iter:
return TreeModelRow(self.model, parent_iter)
def __getitem__(self, key):
if isinstance(key, int):
if key >= self.model.get_n_columns():
raise IndexError("column index is out of bounds: %d" % key)
elif key < 0:
key = self._convert_negative_index(key)
return self.model.get_value(self.iter, key)
elif isinstance(key, slice):
start, stop, step = key.indices(self.model.get_n_columns())
alist = []
for i in range(start, stop, step):
alist.append(self.model.get_value(self.iter, i))
return alist
elif isinstance(key, tuple):
return [self[k] for k in key]
else:
raise TypeError("indices must be integers, slice or tuple, not %s"
% type(key).__name__)
def __setitem__(self, key, value):
if isinstance(key, int):
if key >= self.model.get_n_columns():
raise IndexError("column index is out of bounds: %d" % key)
elif key < 0:
key = self._convert_negative_index(key)
self.model.set_value(self.iter, key, value)
elif isinstance(key, slice):
start, stop, step = key.indices(self.model.get_n_columns())
indexList = range(start, stop, step)
if len(indexList) != len(value):
raise ValueError(
"attempt to assign sequence of size %d to slice of size %d"
% (len(value), len(indexList)))
for i, v in enumerate(indexList):
self.model.set_value(self.iter, v, value[i])
elif isinstance(key, tuple):
if len(key) != len(value):
raise ValueError(
"attempt to assign sequence of size %d to sequence of size %d"
% (len(value), len(key)))
for k, v in zip(key, value):
self[k] = v
else:
raise TypeError("indices must be an integer, slice or tuple, not %s"
% type(key).__name__)
def _convert_negative_index(self, index):
new_index = self.model.get_n_columns() + index
if new_index < 0:
raise IndexError("column index is out of bounds: %d" % index)
return new_index
def iterchildren(self):
child_iter = self.model.iter_children(self.iter)
return TreeModelRowIter(self.model, child_iter)
__all__.append('TreeModelRow')
class TreeModelRowIter(object):
def __init__(self, model, aiter):
self.model = model
self.iter = aiter
def __next__(self):
if not self.iter:
raise StopIteration
row = TreeModelRow(self.model, self.iter)
self.iter = self.model.iter_next(self.iter)
return row
# alias for Python 2.x object protocol
next = __next__
def __iter__(self):
return self
__all__.append('TreeModelRowIter')
class TreePath(Gtk.TreePath):
def __new__(cls, path=0):
if isinstance(path, int):
path = str(path)
elif not isinstance(path, _basestring):
path = ":".join(str(val) for val in path)
if len(path) == 0:
raise TypeError("could not parse subscript '%s' as a tree path" % path)
try:
return TreePath.new_from_string(path)
except TypeError:
raise TypeError("could not parse subscript '%s' as a tree path" % path)
def __init__(self, *args, **kwargs):
super(TreePath, self).__init__()
def __str__(self):
return self.to_string() or ""
def __lt__(self, other):
return other is not None and self.compare(other) < 0
def __le__(self, other):
return other is not None and self.compare(other) <= 0
def __eq__(self, other):
return other is not None and self.compare(other) == 0
def __ne__(self, other):
return other is None or self.compare(other) != 0
def __gt__(self, other):
return other is None or self.compare(other) > 0
def __ge__(self, other):
return other is None or self.compare(other) >= 0
def __iter__(self):
return iter(self.get_indices())
def __len__(self):
return self.get_depth()
def __getitem__(self, index):
return self.get_indices()[index]
TreePath = override(TreePath)
__all__.append('TreePath')
class TreeStore(Gtk.TreeStore, TreeModel, TreeSortable):
def __init__(self, *column_types):
Gtk.TreeStore.__init__(self)
self.set_column_types(column_types)
def _do_insert(self, parent, position, row):
if row is not None:
row, columns = self._convert_row(row)
treeiter = self.insert_with_values(parent, position, columns, row)
else:
treeiter = Gtk.TreeStore.insert(self, parent, position)
return treeiter
def append(self, parent, row=None):
return self._do_insert(parent, -1, row)
def prepend(self, parent, row=None):
return self._do_insert(parent, 0, row)
def insert(self, parent, position, row=None):
return self._do_insert(parent, position, row)
# FIXME: sends two signals; check if this can use an atomic
# insert_with_valuesv()
def insert_before(self, parent, sibling, row=None):
treeiter = Gtk.TreeStore.insert_before(self, parent, sibling)
if row is not None:
self.set_row(treeiter, row)
return treeiter
# FIXME: sends two signals; check if this can use an atomic
# insert_with_valuesv()
def insert_after(self, parent, sibling, row=None):
treeiter = Gtk.TreeStore.insert_after(self, parent, sibling)
if row is not None:
self.set_row(treeiter, row)
return treeiter
def set_value(self, treeiter, column, value):
value = self._convert_value(column, value)
Gtk.TreeStore.set_value(self, treeiter, column, value)
def set(self, treeiter, *args):
def _set_lists(cols, vals):
if len(cols) != len(vals):
raise TypeError('The number of columns do not match the number of values')
columns = []
values = []
for col_num, value in zip(cols, vals):
if not isinstance(col_num, int):
raise TypeError('TypeError: Expected integer argument for column.')
columns.append(col_num)
values.append(self._convert_value(col_num, value))
Gtk.TreeStore.set(self, treeiter, columns, values)
if args:
if isinstance(args[0], int):
_set_lists(args[::2], args[1::2])
elif isinstance(args[0], (tuple, list)):
if len(args) != 2:
raise TypeError('Too many arguments')
_set_lists(args[0], args[1])
elif isinstance(args[0], dict):
_set_lists(args[0].keys(), args[0].values())
else:
raise TypeError('Argument list must be in the form of (column, value, ...), ((columns,...), (values, ...)) or {column: value}. No -1 termination is needed.')
TreeStore = override(TreeStore)
__all__.append('TreeStore')
class TreeView(Gtk.TreeView, Container):
__init__ = deprecated_init(Gtk.TreeView.__init__,
arg_names=('model',),
category=PyGTKDeprecationWarning)
get_path_at_pos = strip_boolean_result(Gtk.TreeView.get_path_at_pos)
get_visible_range = strip_boolean_result(Gtk.TreeView.get_visible_range)
get_dest_row_at_pos = strip_boolean_result(Gtk.TreeView.get_dest_row_at_pos)
def enable_model_drag_source(self, start_button_mask, targets, actions):
target_entries = _construct_target_list(targets)
super(TreeView, self).enable_model_drag_source(start_button_mask,
target_entries,
actions)
def enable_model_drag_dest(self, targets, actions):
target_entries = _construct_target_list(targets)
super(TreeView, self).enable_model_drag_dest(target_entries,
actions)
def scroll_to_cell(self, path, column=None, use_align=False, row_align=0.0, col_align=0.0):
if not isinstance(path, Gtk.TreePath):
path = TreePath(path)
super(TreeView, self).scroll_to_cell(path, column, use_align, row_align, col_align)
def set_cursor(self, path, column=None, start_editing=False):
if not isinstance(path, Gtk.TreePath):
path = TreePath(path)
super(TreeView, self).set_cursor(path, column, start_editing)
def get_cell_area(self, path, column=None):
if not isinstance(path, Gtk.TreePath):
path = TreePath(path)
return super(TreeView, self).get_cell_area(path, column)
def insert_column_with_attributes(self, position, title, cell, **kwargs):
column = TreeViewColumn()
column.set_title(title)
column.pack_start(cell, False)
self.insert_column(column, position)
column.set_attributes(cell, **kwargs)
TreeView = override(TreeView)
__all__.append('TreeView')
class TreeViewColumn(Gtk.TreeViewColumn):
def __init__(self, title='',
cell_renderer=None,
**attributes):
Gtk.TreeViewColumn.__init__(self, title=title)
if cell_renderer:
self.pack_start(cell_renderer, True)
for (name, value) in attributes.items():
self.add_attribute(cell_renderer, name, value)
cell_get_position = strip_boolean_result(Gtk.TreeViewColumn.cell_get_position)
def set_cell_data_func(self, cell_renderer, func, func_data=None):
super(TreeViewColumn, self).set_cell_data_func(cell_renderer, func, func_data)
def set_attributes(self, cell_renderer, **attributes):
Gtk.CellLayout.clear_attributes(self, cell_renderer)
for (name, value) in attributes.items():
Gtk.CellLayout.add_attribute(self, cell_renderer, name, value)
TreeViewColumn = override(TreeViewColumn)
__all__.append('TreeViewColumn')
class TreeSelection(Gtk.TreeSelection):
def select_path(self, path):
if not isinstance(path, Gtk.TreePath):
path = TreePath(path)
super(TreeSelection, self).select_path(path)
def get_selected(self):
success, model, aiter = super(TreeSelection, self).get_selected()
if success:
return (model, aiter)
else:
return (model, None)
# for compatibility with PyGtk
def get_selected_rows(self):
rows, model = super(TreeSelection, self).get_selected_rows()
return (model, rows)
TreeSelection = override(TreeSelection)
__all__.append('TreeSelection')
class Button(Gtk.Button, Container):
_init = deprecated_init(Gtk.Button.__init__,
arg_names=('label', 'stock', 'use_stock', 'use_underline'),
ignore=('stock',),
category=PyGTKDeprecationWarning,
stacklevel=3)
def __init__(self, *args, **kwargs):
# Doubly deprecated initializer, the stock keyword is non-standard.
# Simply give a warning that stock items are deprecated even though
# we want to deprecate the non-standard keyword as well here from
# the overrides.
if 'stock' in kwargs and kwargs['stock']:
warnings.warn('Stock items are deprecated. '
'Please use: Gtk.Button.new_with_mnemonic(label)',
PyGTKDeprecationWarning, stacklevel=2)
new_kwargs = kwargs.copy()
new_kwargs['label'] = new_kwargs['stock']
new_kwargs['use_stock'] = True
new_kwargs['use_underline'] = True
del new_kwargs['stock']
Gtk.Button.__init__(self, **new_kwargs)
else:
self._init(*args, **kwargs)
Button = override(Button)
__all__.append('Button')
class LinkButton(Gtk.LinkButton):
__init__ = deprecated_init(Gtk.LinkButton.__init__,
arg_names=('uri', 'label'),
category=PyGTKDeprecationWarning)
LinkButton = override(LinkButton)
__all__.append('LinkButton')
class Label(Gtk.Label):
__init__ = deprecated_init(Gtk.Label.__init__,
arg_names=('label',),
category=PyGTKDeprecationWarning)
Label = override(Label)
__all__.append('Label')
class Adjustment(Gtk.Adjustment):
_init = deprecated_init(Gtk.Adjustment.__init__,
arg_names=('value', 'lower', 'upper',
'step_increment', 'page_increment', 'page_size'),
deprecated_aliases={'page_increment': 'page_incr',
'step_increment': 'step_incr'},
category=PyGTKDeprecationWarning,
stacklevel=3)
def __init__(self, *args, **kwargs):
self._init(*args, **kwargs)
# The value property is set between lower and (upper - page_size).
# Just in case lower, upper or page_size was still 0 when value
# was set, we set it again here.
if 'value' in kwargs:
self.set_value(kwargs['value'])
elif len(args) >= 1:
self.set_value(args[0])
Adjustment = override(Adjustment)
__all__.append('Adjustment')
if Gtk._version in ("2.0", "3.0"):
class Table(Gtk.Table, Container):
__init__ = deprecated_init(Gtk.Table.__init__,
arg_names=('n_rows', 'n_columns', 'homogeneous'),
deprecated_aliases={'n_rows': 'rows', 'n_columns': 'columns'},
category=PyGTKDeprecationWarning)
def attach(self, child, left_attach, right_attach, top_attach, bottom_attach, xoptions=Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, yoptions=Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, xpadding=0, ypadding=0):
Gtk.Table.attach(self, child, left_attach, right_attach, top_attach, bottom_attach, xoptions, yoptions, xpadding, ypadding)
Table = override(Table)
__all__.append('Table')
class ScrolledWindow(Gtk.ScrolledWindow):
__init__ = deprecated_init(Gtk.ScrolledWindow.__init__,
arg_names=('hadjustment', 'vadjustment'),
category=PyGTKDeprecationWarning)
ScrolledWindow = override(ScrolledWindow)
__all__.append('ScrolledWindow')
if Gtk._version in ("2.0", "3.0"):
class HScrollbar(Gtk.HScrollbar):
__init__ = deprecated_init(Gtk.HScrollbar.__init__,
arg_names=('adjustment',),
category=PyGTKDeprecationWarning)
HScrollbar = override(HScrollbar)
__all__.append('HScrollbar')
class VScrollbar(Gtk.VScrollbar):
__init__ = deprecated_init(Gtk.VScrollbar.__init__,
arg_names=('adjustment',),
category=PyGTKDeprecationWarning)
VScrollbar = override(VScrollbar)
__all__.append('VScrollbar')
class Paned(Gtk.Paned):
def pack1(self, child, resize=False, shrink=True):
super(Paned, self).pack1(child, resize, shrink)
def pack2(self, child, resize=True, shrink=True):
super(Paned, self).pack2(child, resize, shrink)
Paned = override(Paned)
__all__.append('Paned')
if Gtk._version in ("2.0", "3.0"):
class Arrow(Gtk.Arrow):
__init__ = deprecated_init(Gtk.Arrow.__init__,
arg_names=('arrow_type', 'shadow_type'),
category=PyGTKDeprecationWarning)
Arrow = override(Arrow)
__all__.append('Arrow')
class IconSet(Gtk.IconSet):
def __new__(cls, pixbuf=None):
if pixbuf is not None:
warnings.warn('Gtk.IconSet(pixbuf) has been deprecated. Please use: '
'Gtk.IconSet.new_from_pixbuf(pixbuf)',
PyGTKDeprecationWarning, stacklevel=2)
iconset = Gtk.IconSet.new_from_pixbuf(pixbuf)
else:
iconset = Gtk.IconSet.__new__(cls)
return iconset
def __init__(self, *args, **kwargs):
return super(IconSet, self).__init__()
IconSet = override(IconSet)
__all__.append('IconSet')
class Viewport(Gtk.Viewport):
__init__ = deprecated_init(Gtk.Viewport.__init__,
arg_names=('hadjustment', 'vadjustment'),
category=PyGTKDeprecationWarning)
Viewport = override(Viewport)
__all__.append('Viewport')
class TreeModelFilter(Gtk.TreeModelFilter):
def set_visible_func(self, func, data=None):
super(TreeModelFilter, self).set_visible_func(func, data)
def set_value(self, iter, column, value):
# Delegate to child model
iter = self.convert_iter_to_child_iter(iter)
self.get_model().set_value(iter, column, value)
TreeModelFilter = override(TreeModelFilter)
__all__.append('TreeModelFilter')
if Gtk._version != '2.0':
class Menu(Gtk.Menu):
def popup(self, parent_menu_shell, parent_menu_item, func, data, button, activate_time):
self.popup_for_device(None, parent_menu_shell, parent_menu_item, func, data, button, activate_time)
Menu = override(Menu)
__all__.append('Menu')
_Gtk_main_quit = Gtk.main_quit
@override(Gtk.main_quit)
def main_quit(*args):
_Gtk_main_quit()
_Gtk_main = Gtk.main
@override(Gtk.main)
def main(*args, **kwargs):
with register_sigint_fallback(Gtk.main_quit):
with wakeup_on_signal():
return _Gtk_main(*args, **kwargs)
if Gtk._version in ("2.0", "3.0"):
stock_lookup = strip_boolean_result(Gtk.stock_lookup)
__all__.append('stock_lookup')
if Gtk._version == "4.0":
Gtk.init_check()
else:
initialized, argv = Gtk.init_check(sys.argv)
sys.argv = list(argv)
PK ! 78S~># ># Gio.pynu [ # -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2010 Ignacio Casal Quinteiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
import warnings
from .._ossighelper import wakeup_on_signal, register_sigint_fallback
from ..overrides import override, deprecated_init
from ..module import get_introspection_module
from gi import PyGIWarning
from gi.repository import GLib
import sys
Gio = get_introspection_module('Gio')
__all__ = []
class Application(Gio.Application):
def run(self, *args, **kwargs):
with register_sigint_fallback(self.quit):
with wakeup_on_signal():
return Gio.Application.run(self, *args, **kwargs)
Application = override(Application)
__all__.append('Application')
class VolumeMonitor(Gio.VolumeMonitor):
def __init__(self, *args, **kwargs):
super(VolumeMonitor, self).__init__(*args, **kwargs)
# https://bugzilla.gnome.org/show_bug.cgi?id=744690
warnings.warn(
"Gio.VolumeMonitor shouldn't be instantiated directly, "
"use Gio.VolumeMonitor.get() instead.",
PyGIWarning, stacklevel=2)
VolumeMonitor = override(VolumeMonitor)
__all__.append('VolumeMonitor')
class FileEnumerator(Gio.FileEnumerator):
def __iter__(self):
return self
def __next__(self):
file_info = self.next_file(None)
if file_info is not None:
return file_info
else:
raise StopIteration
# python 2 compat for the iter protocol
next = __next__
FileEnumerator = override(FileEnumerator)
__all__.append('FileEnumerator')
class MenuItem(Gio.MenuItem):
def set_attribute(self, attributes):
for (name, format_string, value) in attributes:
self.set_attribute_value(name, GLib.Variant(format_string, value))
MenuItem = override(MenuItem)
__all__.append('MenuItem')
class Settings(Gio.Settings):
'''Provide dictionary-like access to GLib.Settings.'''
__init__ = deprecated_init(Gio.Settings.__init__,
arg_names=('schema', 'path', 'backend'))
def __contains__(self, key):
return key in self.list_keys()
def __len__(self):
return len(self.list_keys())
def __bool__(self):
# for "if mysettings" we don't want a dictionary-like test here, just
# if the object isn't None
return True
# alias for Python 2.x object protocol
__nonzero__ = __bool__
def __getitem__(self, key):
# get_value() aborts the program on an unknown key
if key not in self:
raise KeyError('unknown key: %r' % (key,))
return self.get_value(key).unpack()
def __setitem__(self, key, value):
# set_value() aborts the program on an unknown key
if key not in self:
raise KeyError('unknown key: %r' % (key,))
# determine type string of this key
range = self.get_range(key)
type_ = range.get_child_value(0).get_string()
v = range.get_child_value(1)
if type_ == 'type':
# v is boxed empty array, type of its elements is the allowed value type
type_str = v.get_child_value(0).get_type_string()
assert type_str.startswith('a')
type_str = type_str[1:]
elif type_ == 'enum':
# v is an array with the allowed values
assert v.get_child_value(0).get_type_string().startswith('a')
type_str = v.get_child_value(0).get_child_value(0).get_type_string()
allowed = v.unpack()
if value not in allowed:
raise ValueError('value %s is not an allowed enum (%s)' % (value, allowed))
else:
raise NotImplementedError('Cannot handle allowed type range class ' + str(type_))
self.set_value(key, GLib.Variant(type_str, value))
def keys(self):
return self.list_keys()
Settings = override(Settings)
__all__.append('Settings')
class _DBusProxyMethodCall:
'''Helper class to implement DBusProxy method calls.'''
def __init__(self, dbus_proxy, method_name):
self.dbus_proxy = dbus_proxy
self.method_name = method_name
def __async_result_handler(self, obj, result, user_data):
(result_callback, error_callback, real_user_data) = user_data
try:
ret = obj.call_finish(result)
except Exception:
etype, e = sys.exc_info()[:2]
# return exception as value
if error_callback:
error_callback(obj, e, real_user_data)
else:
result_callback(obj, e, real_user_data)
return
result_callback(obj, self._unpack_result(ret), real_user_data)
def __call__(self, *args, **kwargs):
# the first positional argument is the signature, unless we are calling
# a method without arguments; then signature is implied to be '()'.
if args:
signature = args[0]
args = args[1:]
if not isinstance(signature, str):
raise TypeError('first argument must be the method signature string: %r' % signature)
else:
signature = '()'
arg_variant = GLib.Variant(signature, tuple(args))
if 'result_handler' in kwargs:
# asynchronous call
user_data = (kwargs['result_handler'],
kwargs.get('error_handler'),
kwargs.get('user_data'))
self.dbus_proxy.call(self.method_name, arg_variant,
kwargs.get('flags', 0), kwargs.get('timeout', -1), None,
self.__async_result_handler, user_data)
else:
# synchronous call
result = self.dbus_proxy.call_sync(self.method_name, arg_variant,
kwargs.get('flags', 0),
kwargs.get('timeout', -1),
None)
return self._unpack_result(result)
@classmethod
def _unpack_result(klass, result):
'''Convert a D-BUS return variant into an appropriate return value'''
result = result.unpack()
# to be compatible with standard Python behaviour, unbox
# single-element tuples and return None for empty result tuples
if len(result) == 1:
result = result[0]
elif len(result) == 0:
result = None
return result
class DBusProxy(Gio.DBusProxy):
'''Provide comfortable and pythonic method calls.
This marshalls the method arguments into a GVariant, invokes the
call_sync() method on the DBusProxy object, and unmarshalls the result
GVariant back into a Python tuple.
The first argument always needs to be the D-Bus signature tuple of the
method call. Example:
proxy = Gio.DBusProxy.new_sync(...)
result = proxy.MyMethod('(is)', 42, 'hello')
The exception are methods which take no arguments, like
proxy.MyMethod('()'). For these you can omit the signature and just write
proxy.MyMethod().
Optional keyword arguments:
- timeout: timeout for the call in milliseconds (default to D-Bus timeout)
- flags: Combination of Gio.DBusCallFlags.*
- result_handler: Do an asynchronous method call and invoke
result_handler(proxy_object, result, user_data) when it finishes.
- error_handler: If the asynchronous call raises an exception,
error_handler(proxy_object, exception, user_data) is called when it
finishes. If error_handler is not given, result_handler is called with
the exception object as result instead.
- user_data: Optional user data to pass to result_handler for
asynchronous calls.
Example for asynchronous calls:
def mymethod_done(proxy, result, user_data):
if isinstance(result, Exception):
# handle error
else:
# do something with result
proxy.MyMethod('(is)', 42, 'hello',
result_handler=mymethod_done, user_data='data')
'''
def __getattr__(self, name):
return _DBusProxyMethodCall(self, name)
DBusProxy = override(DBusProxy)
__all__.append('DBusProxy')
PK ! ?HB_= _= Gdk.pynu [ # -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2009 Johan Dahlin
# 2010 Simon van der Linden
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
import sys
import warnings
from ..overrides import override, strip_boolean_result
from ..module import get_introspection_module
from gi import PyGIDeprecationWarning, require_version
Gdk = get_introspection_module('Gdk')
__all__ = []
# https://bugzilla.gnome.org/show_bug.cgi?id=673396
try:
require_version("GdkX11", Gdk._version)
from gi.repository import GdkX11
GdkX11 # pyflakes
except (ValueError, ImportError):
pass
if hasattr(Gdk, 'Color'):
# Gdk.Color was deprecated since 3.14 and dropped in Gtk+-4.0
class Color(Gdk.Color):
MAX_VALUE = 65535
def __init__(self, red, green, blue):
Gdk.Color.__init__(self)
self.red = red
self.green = green
self.blue = blue
def __eq__(self, other):
return self.equal(other)
def __repr__(self):
return 'Gdk.Color(red=%d, green=%d, blue=%d)' % (self.red, self.green, self.blue)
red_float = property(fget=lambda self: self.red / float(self.MAX_VALUE),
fset=lambda self, v: setattr(self, 'red', int(v * self.MAX_VALUE)))
green_float = property(fget=lambda self: self.green / float(self.MAX_VALUE),
fset=lambda self, v: setattr(self, 'green', int(v * self.MAX_VALUE)))
blue_float = property(fget=lambda self: self.blue / float(self.MAX_VALUE),
fset=lambda self, v: setattr(self, 'blue', int(v * self.MAX_VALUE)))
def to_floats(self):
"""Return (red_float, green_float, blue_float) triple."""
return (self.red_float, self.green_float, self.blue_float)
@staticmethod
def from_floats(red, green, blue):
"""Return a new Color object from red/green/blue values from 0.0 to 1.0."""
return Color(int(red * Color.MAX_VALUE),
int(green * Color.MAX_VALUE),
int(blue * Color.MAX_VALUE))
Color = override(Color)
__all__.append('Color')
if hasattr(Gdk, 'RGBA'):
# Introduced since Gtk+-3.0
class RGBA(Gdk.RGBA):
def __init__(self, red=1.0, green=1.0, blue=1.0, alpha=1.0):
Gdk.RGBA.__init__(self)
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
def __eq__(self, other):
return self.equal(other)
def __repr__(self):
return 'Gdk.RGBA(red=%f, green=%f, blue=%f, alpha=%f)' % (self.red, self.green, self.blue, self.alpha)
def __iter__(self):
"""Iterator which allows easy conversion to tuple and list types."""
yield self.red
yield self.green
yield self.blue
yield self.alpha
def to_color(self):
"""Converts this RGBA into a Color instance which excludes alpha."""
return Color(int(self.red * Color.MAX_VALUE),
int(self.green * Color.MAX_VALUE),
int(self.blue * Color.MAX_VALUE))
@classmethod
def from_color(cls, color):
"""Returns a new RGBA instance given a Color instance."""
return cls(color.red_float, color.green_float, color.blue_float)
RGBA = override(RGBA)
__all__.append('RGBA')
if Gdk._version == '2.0':
class Rectangle(Gdk.Rectangle):
def __init__(self, x, y, width, height):
Gdk.Rectangle.__init__(self)
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return 'Gdk.Rectangle(x=%d, y=%d, width=%d, height=%d)' % (self.x, self.y, self.height, self.width)
Rectangle = override(Rectangle)
__all__.append('Rectangle')
else:
# Newer GTK+/gobject-introspection (3.17.x) include GdkRectangle in the
# typelib. See https://bugzilla.gnome.org/show_bug.cgi?id=748832 and
# https://bugzilla.gnome.org/show_bug.cgi?id=748833
if not hasattr(Gdk, 'Rectangle'):
from gi.repository import cairo as _cairo
Rectangle = _cairo.RectangleInt
__all__.append('Rectangle')
else:
# https://bugzilla.gnome.org/show_bug.cgi?id=756364
# These methods used to be functions, keep aliases for backwards compat
rectangle_intersect = Gdk.Rectangle.intersect
rectangle_union = Gdk.Rectangle.union
__all__.append('rectangle_intersect')
__all__.append('rectangle_union')
if Gdk._version == '2.0':
class Drawable(Gdk.Drawable):
def cairo_create(self):
return Gdk.cairo_create(self)
Drawable = override(Drawable)
__all__.append('Drawable')
else:
class Window(Gdk.Window):
def __new__(cls, parent, attributes, attributes_mask):
# Gdk.Window had to be made abstract,
# this override allows using the standard constructor
return Gdk.Window.new(parent, attributes, attributes_mask)
def __init__(self, parent, attributes, attributes_mask):
pass
def cairo_create(self):
return Gdk.cairo_create(self)
Window = override(Window)
__all__.append('Window')
Gdk.EventType._2BUTTON_PRESS = getattr(Gdk.EventType, "2BUTTON_PRESS")
Gdk.EventType._3BUTTON_PRESS = getattr(Gdk.EventType, "3BUTTON_PRESS")
class Event(Gdk.Event):
_UNION_MEMBERS = {
Gdk.EventType.DELETE: 'any',
Gdk.EventType.DESTROY: 'any',
Gdk.EventType.EXPOSE: 'expose',
Gdk.EventType.MOTION_NOTIFY: 'motion',
Gdk.EventType.BUTTON_PRESS: 'button',
Gdk.EventType._2BUTTON_PRESS: 'button',
Gdk.EventType._3BUTTON_PRESS: 'button',
Gdk.EventType.BUTTON_RELEASE: 'button',
Gdk.EventType.KEY_PRESS: 'key',
Gdk.EventType.KEY_RELEASE: 'key',
Gdk.EventType.ENTER_NOTIFY: 'crossing',
Gdk.EventType.LEAVE_NOTIFY: 'crossing',
Gdk.EventType.FOCUS_CHANGE: 'focus_change',
Gdk.EventType.CONFIGURE: 'configure',
Gdk.EventType.MAP: 'any',
Gdk.EventType.UNMAP: 'any',
Gdk.EventType.PROPERTY_NOTIFY: 'property',
Gdk.EventType.SELECTION_CLEAR: 'selection',
Gdk.EventType.SELECTION_REQUEST: 'selection',
Gdk.EventType.SELECTION_NOTIFY: 'selection',
Gdk.EventType.PROXIMITY_IN: 'proximity',
Gdk.EventType.PROXIMITY_OUT: 'proximity',
Gdk.EventType.DRAG_ENTER: 'dnd',
Gdk.EventType.DRAG_LEAVE: 'dnd',
Gdk.EventType.DRAG_MOTION: 'dnd',
Gdk.EventType.DRAG_STATUS: 'dnd',
Gdk.EventType.DROP_START: 'dnd',
Gdk.EventType.DROP_FINISHED: 'dnd',
Gdk.EventType.CLIENT_EVENT: 'client',
Gdk.EventType.VISIBILITY_NOTIFY: 'visibility',
}
if Gdk._version == '2.0':
_UNION_MEMBERS[Gdk.EventType.NO_EXPOSE] = 'no_expose'
if hasattr(Gdk.EventType, 'TOUCH_BEGIN'):
_UNION_MEMBERS.update(
{
Gdk.EventType.TOUCH_BEGIN: 'touch',
Gdk.EventType.TOUCH_UPDATE: 'touch',
Gdk.EventType.TOUCH_END: 'touch',
Gdk.EventType.TOUCH_CANCEL: 'touch',
})
def __getattr__(self, name):
real_event = getattr(self, '_UNION_MEMBERS').get(self.type)
if real_event:
return getattr(getattr(self, real_event), name)
else:
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
def __setattr__(self, name, value):
real_event = getattr(self, '_UNION_MEMBERS').get(self.type)
if real_event:
setattr(getattr(self, real_event), name, value)
else:
Gdk.Event.__setattr__(self, name, value)
def __repr__(self):
base_repr = Gdk.Event.__repr__(self).strip("><")
return "<%s type=%r>" % (base_repr, self.type)
Event = override(Event)
__all__.append('Event')
# manually bind GdkEvent members to GdkEvent
modname = globals()['__name__']
module = sys.modules[modname]
# right now we can't get the type_info from the
# field info so manually list the class names
event_member_classes = ['EventAny',
'EventExpose',
'EventVisibility',
'EventMotion',
'EventButton',
'EventScroll',
'EventKey',
'EventCrossing',
'EventFocus',
'EventConfigure',
'EventProperty',
'EventSelection',
'EventOwnerChange',
'EventProximity',
'EventDND',
'EventWindowState',
'EventSetting',
'EventGrabBroken']
if Gdk._version == '2.0':
event_member_classes.append('EventNoExpose')
if hasattr(Gdk, 'EventTouch'):
event_member_classes.append('EventTouch')
# whitelist all methods that have a success return we want to mask
gsuccess_mask_funcs = ['get_state',
'get_axis',
'get_coords',
'get_root_coords']
for event_class in event_member_classes:
override_class = type(event_class, (getattr(Gdk, event_class),), {})
# add the event methods
for method_info in Gdk.Event.__info__.get_methods():
name = method_info.get_name()
event_method = getattr(Gdk.Event, name)
# python2 we need to use the __func__ attr to avoid internal
# instance checks
event_method = getattr(event_method, '__func__', event_method)
# use the _gsuccess_mask decorator if this method is whitelisted
if name in gsuccess_mask_funcs:
event_method = strip_boolean_result(event_method)
setattr(override_class, name, event_method)
setattr(module, event_class, override_class)
__all__.append(event_class)
# end GdkEvent overrides
class DragContext(Gdk.DragContext):
def finish(self, success, del_, time):
Gtk = get_introspection_module('Gtk')
Gtk.drag_finish(self, success, del_, time)
DragContext = override(DragContext)
__all__.append('DragContext')
class Cursor(Gdk.Cursor):
def __new__(cls, *args, **kwds):
arg_len = len(args)
kwd_len = len(kwds)
total_len = arg_len + kwd_len
if total_len == 1:
if Gdk._version == "4.0":
raise ValueError("Wrong number of parameters")
# Since g_object_newv (super.__new__) does not seem valid for
# direct use with GdkCursor, we must assume usage of at least
# one of the C constructors to be valid.
return cls.new(*args, **kwds)
elif total_len == 2:
warnings.warn('Calling "Gdk.Cursor(display, cursor_type)" has been deprecated. '
'Please use Gdk.Cursor.new_for_display(display, cursor_type). '
'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
PyGIDeprecationWarning)
return cls.new_for_display(*args, **kwds)
elif total_len == 4:
warnings.warn('Calling "Gdk.Cursor(display, pixbuf, x, y)" has been deprecated. '
'Please use Gdk.Cursor.new_from_pixbuf(display, pixbuf, x, y). '
'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
PyGIDeprecationWarning)
return cls.new_from_pixbuf(*args, **kwds)
elif total_len == 6:
if Gdk._version != '2.0':
# pixmaps don't exist in Gdk 3.0
raise ValueError("Wrong number of parameters")
warnings.warn('Calling "Gdk.Cursor(source, mask, fg, bg, x, y)" has been deprecated. '
'Please use Gdk.Cursor.new_from_pixmap(source, mask, fg, bg, x, y). '
'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
PyGIDeprecationWarning)
return cls.new_from_pixmap(*args, **kwds)
else:
raise ValueError("Wrong number of parameters")
Cursor = override(Cursor)
__all__.append('Cursor')
if hasattr(Gdk, 'color_parse'):
# Gdk.Color was deprecated since 3.14 and dropped in Gtk+-4.0
color_parse = strip_boolean_result(Gdk.color_parse)
__all__.append('color_parse')
# Note, we cannot override the entire class as Gdk.Atom has no gtype, so just
# hack some individual methods
def _gdk_atom_str(atom):
n = atom.name()
if n:
return n
# fall back to atom index
return 'Gdk.Atom<%i>' % hash(atom)
def _gdk_atom_repr(atom):
n = atom.name()
if n:
return 'Gdk.Atom.intern("%s", False)' % n
# fall back to atom index
return '' % hash(atom)
Gdk.Atom.__str__ = _gdk_atom_str
Gdk.Atom.__repr__ = _gdk_atom_repr
# constants
if Gdk._version >= '3.0':
SELECTION_PRIMARY = Gdk.atom_intern('PRIMARY', True)
__all__.append('SELECTION_PRIMARY')
SELECTION_SECONDARY = Gdk.atom_intern('SECONDARY', True)
__all__.append('SELECTION_SECONDARY')
SELECTION_CLIPBOARD = Gdk.atom_intern('CLIPBOARD', True)
__all__.append('SELECTION_CLIPBOARD')
TARGET_BITMAP = Gdk.atom_intern('BITMAP', True)
__all__.append('TARGET_BITMAP')
TARGET_COLORMAP = Gdk.atom_intern('COLORMAP', True)
__all__.append('TARGET_COLORMAP')
TARGET_DRAWABLE = Gdk.atom_intern('DRAWABLE', True)
__all__.append('TARGET_DRAWABLE')
TARGET_PIXMAP = Gdk.atom_intern('PIXMAP', True)
__all__.append('TARGET_PIXMAP')
TARGET_STRING = Gdk.atom_intern('STRING', True)
__all__.append('TARGET_STRING')
SELECTION_TYPE_ATOM = Gdk.atom_intern('ATOM', True)
__all__.append('SELECTION_TYPE_ATOM')
SELECTION_TYPE_BITMAP = Gdk.atom_intern('BITMAP', True)
__all__.append('SELECTION_TYPE_BITMAP')
SELECTION_TYPE_COLORMAP = Gdk.atom_intern('COLORMAP', True)
__all__.append('SELECTION_TYPE_COLORMAP')
SELECTION_TYPE_DRAWABLE = Gdk.atom_intern('DRAWABLE', True)
__all__.append('SELECTION_TYPE_DRAWABLE')
SELECTION_TYPE_INTEGER = Gdk.atom_intern('INTEGER', True)
__all__.append('SELECTION_TYPE_INTEGER')
SELECTION_TYPE_PIXMAP = Gdk.atom_intern('PIXMAP', True)
__all__.append('SELECTION_TYPE_PIXMAP')
SELECTION_TYPE_WINDOW = Gdk.atom_intern('WINDOW', True)
__all__.append('SELECTION_TYPE_WINDOW')
SELECTION_TYPE_STRING = Gdk.atom_intern('STRING', True)
__all__.append('SELECTION_TYPE_STRING')
if Gdk._version in ('2.0', '3.0'):
import sys
initialized, argv = Gdk.init_check(sys.argv)
PK ! ?d " __pycache__/keysyms.cpython-36.pycnu [ 3
<_ @ s d dl Z d dlZddlmZ edZejde e d Ze j e Z
xPeeD ]DZej
drNedd Zed d kr|d
e ZeeeZee
ee qNW dZdZd
ZdZdZdZdZdZdZdZdZdS ) N )get_introspection_moduleGdkz?keysyms has been deprecated. Please use Gdk.KEY_ instead.__name__ZKEY_
0123456789_i i i i i i i i i i )syswarningsmoduler r warnRuntimeWarningglobalsZ_modnamemodulesZ_keysymsdirname
startswithtargetgetattrvaluesetattrZArmenian_eternityZArmenian_section_signZArmenian_parenleftZArmenian_guillemotrightZArmenian_guillemotleftZArmenian_em_dashZArmenian_dotZArmenian_mijaketZArmenian_commaZArmenian_en_dashZArmenian_ellipsis r r /usr/lib64/python3.6/keysyms.py s2
PK ! CI CI " __pycache__/GObject.cpython-36.pycnu [ 3
<_e * @ s~ d dl Z d dlZd dlmZ d dlZd dlZd dlmZmZ d dl m
Z
d dlmZ d dlmZ
d dlmZ d dlmZ ejjd Zg Zd d
lmZ eZx6dD ].Zee
ee e<