def async_call(func, *args, callback=None):
'''Call `func` in background thread, and then call `callback` in Gtk main thread.
If error occurs in `func`, error will keep the traceback and passed to
`callback` as second parameter. Always check `error` is not None.
'''
def do_call():
result = None
error = None
try:
result = func(*args)
except Exception:
error = traceback.format_exc()
logger.error(error)
if callback:
GLib.idle_add(callback, result, error)
thread = threading.Thread(target=do_call)
thread.daemon = True
thread.start()
python类Gtk()的实例源码
def getAllApps():
AppList.apps.clear()
iconTheme = Gtk.IconTheme.get_default()
appList = Gio.AppInfo.get_all()
for app in appList:
name = Gio.AppInfo.get_display_name(app)
executable = Gio.AppInfo.get_executable(app)
iconName = None
icon = Gio.AppInfo.get_icon(app)
if icon:
iconInfo = Gtk.IconTheme.lookup_by_gicon(iconTheme, icon, 256, Gtk.IconLookupFlags.USE_BUILTIN)
if iconInfo:
iconName = iconInfo.get_filename()
AppList.apps.append(AppCmd().set(name=name, executable=executable, iconName=iconName))
# ??
AppList.apps = reduce(lambda x, y: x if y in x else x + [y], [[], ] + AppList.apps)
AppList.apps.sort(key=lambda x: x.name.lower())
return AppList.apps
def getAppIcon(name):
global appList
iconTheme = Gtk.IconTheme.get_default()
if not appList:
appList = Gio.AppInfo.get_all()
for app in appList:
if name == Gio.AppInfo.get_display_name(app) or \
name == Gio.AppInfo.get_executable(app) or \
os.path.basename(name) == Gio.AppInfo.get_display_name(app) or \
os.path.basename(name) == os.path.basename(Gio.AppInfo.get_executable(app)):
icon = Gio.AppInfo.get_icon(app)
if icon:
iconInfo = Gtk.IconTheme.lookup_by_gicon(iconTheme, icon, 256, Gtk.IconLookupFlags.USE_BUILTIN)
if iconInfo:
return iconInfo.get_filename()
return 'app.png'
def getAppIcon(name):
global appList
iconTheme = Gtk.IconTheme.get_default()
if not appList:
appList = Gio.AppInfo.get_all()
for app in appList:
if name == Gio.AppInfo.get_display_name(app) or \
name == Gio.AppInfo.get_executable(app) or \
os.path.basename(name) == Gio.AppInfo.get_display_name(app) or \
os.path.basename(name) == os.path.basename(Gio.AppInfo.get_executable(app)):
icon = Gio.AppInfo.get_icon(app)
if icon:
iconInfo = Gtk.IconTheme.lookup_by_gicon(iconTheme, icon, 256, Gtk.IconLookupFlags.USE_BUILTIN)
if iconInfo:
return iconInfo.get_filename()
return 'app.png'
def find_child_by_id(root, name):
"""
Searches through a hierarchy of Gtk widgets for the `name`d
Returns None if no such child was found.
"""
# We do a breadth-first search
next_level = [root]
while next_level:
children = next_level
next_level = []
for child in children:
if child is None:
continue
if Gtk.Buildable.get_name(child) == name:
# Bingo
return child
if hasattr(child, 'get_children'):
next_level.extend(child.get_children())
# Hierarchy exhausted. Ho hum.
def get_clipboard_html():
"""returns html in clipboard, if any"""
if 'darwin' in sys.platform:
if NSPasteboard is None:
raise Exception('AppKit not found, first run `pip install pyobjc`')
pb = NSPasteboard.generalPasteboard()
return pb.stringForType_('public.html')
elif 'linux' in sys.platform:
if Gtk is None:
raise Exception('Could not import GTK, is it installed on this system?')
cb = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
html_target = Gdk.Atom.intern('text/html', False)
targets = cb.wait_for_targets()[1]
if html_target not in targets:
return None
return cb.wait_for_contents(html_target).get_data()
else:
raise Exception('Platform "{}" is not supported'.format(sys.platform))
def __init__(self, parent):
self.builder = Gtk.Builder.new_from_resource('/org/gnome/Authenticator/settings.ui')
self.builder.connect_signals({
"on_change_password" : self.__new_password_window,
'on_password_toggle': self.__on_password_activated,
"on_change_auto_lock_time" : self.__on_auto_lock_time_changed,
"on_key_press": self.__on_key_press,
"on_close_window": self.close_window
})
self.window = self.builder.get_object("SettingsWindow")
self.window.set_transient_for(parent)
logging.debug("Settings Window created")
self.auto_lock_check = self.builder.get_object("AutoLockCheck")
self.auto_lock_spin = self.builder.get_object("AutoLockSpin")
self.password_check = self.builder.get_object("PasswordCheck")
self.password_button = self.builder.get_object("PasswordButton")
settings.bind('state', self.password_check, 'active', Gio.SettingsBindFlags.DEFAULT)
settings.bind('state', self.password_button, 'sensitive', Gio.SettingsBindFlags.INVERT_BOOLEAN)
settings.bind('state', self.auto_lock_check, 'sensitive', Gio.SettingsBindFlags.GET)
settings.bind('auto-lock', self.auto_lock_check, 'active', Gio.SettingsBindFlags.DEFAULT)
settings.bind('auto-lock', self.auto_lock_spin, 'sensitive', Gio.SettingsBindFlags.GET)
# Restore settings
_auto_lock_time = settings.get_auto_lock_time()
self.auto_lock_spin.set_value(_auto_lock_time)
def read_clipboard(self):
"""
@description: A function to make mama reads the selected
text
"""
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY)
text = clipboard.wait_for_text()
if text:
text = text.replace("'", ' ')
TextToSpeech(self.config, text)
else:
TextToSpeech('Nothing in the clipboard')
def getFileIconName(fileName):
iconTheme = Gtk.IconTheme.get_default()
file = Gio.File.new_for_path(fileName)
file_info = file.query_info('standard::icon', Gio.FileQueryInfoFlags.NONE, None)
icon = Gio.FileInfo.get_icon(file_info)
iconInfo = Gtk.IconTheme.lookup_by_gicon(iconTheme, icon, 256, Gtk.IconLookupFlags.USE_BUILTIN)
if iconInfo:
return iconInfo.get_filename()
return None
def _get_plugin_imports():
# We want to import all relevent GUI modules into the namespace of each plugin.
# We do this once for all - in order to centralize and minimize error handling.
result = {key: None for key in ("gtk", "gdk", "gdkpixbuf", "gdkobject", "GL", "GLU", "GLUT")}
try:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import GObject
result["gtk"] = Gtk
result["gdk"] = Gdk
result["gdkpixbuf"] = GdkPixbuf
result["gobject"] = GObject
except ImportError:
_log.warning("Failed to import GTK3 module. Maybe you want to install 'python3-gi' "
"for pycam's graphical user interface.")
if result["gtk"]:
try:
import OpenGL.GL
import OpenGL.GLU
import OpenGL.GLUT
result["GL"] = OpenGL.GL
result["GLU"] = OpenGL.GLU
result["GLUT"] = OpenGL.GLUT
except ImportError:
# OpenGL-related plugins will complain later about the missing dependency
_log.warning("Failed to import OpenGL module. Maybe you want to install "
"'python3-opengl' for the 3D visualization.")
return result
def get_mainloop(use_gtk=False):
"""create new or return an existing mainloop
@param use_gtk: supply Gtk with timeslots for event handling (active if this parameter is True
at least once)
"""
try:
mainloop = __mainloop[0]
except IndexError:
mainloop = GtkMainLoop()
__mainloop.append(mainloop)
return mainloop
def __init__(self):
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
self._gtk = Gtk
def main():
# T1 = time.time()
setting = Gtk.Settings.get_default()
if Const.THEME1:
setting.set_property("gtk-theme-name","FlatPlat")
elif Const.THEME2:
setting.set_property("gtk-theme-name","Adapta")
elif Const.THEME3:
setting.set_property("gtk-theme-name","Numix")
gtk = MyGtk("GPU-Viewer v1.3")
setScreenSize(gtk, Const.WIDTH_RATIO, Const.HEIGHT_RATIO1)
openGlTab = gtk.createTab(Const.OPEN_GL_PNG, Const.ICON_WIDTH, Const.ICON_HEIGHT, True)
t1=threading.Thread(target=OpenGL,args=(openGlTab,))
t1.start()
if isVulkanSupported():
vulkanTab = gtk.createTab(Const.VULKAN_PNG, Const.ICON_WIDTH, Const.ICON_HEIGHT, True)
t2=threading.Thread(target=Vulkan,args=(vulkanTab,))
t2.start()
t2.join()
if isOpenclSupported():
openclTab = gtk.createTab(Const.OPEN_CL_PNG, 100, Const.ICON_HEIGHT,False)
t4=threading.Thread(target=openCL,args=(openclTab,))
t4.start()
aboutTab = gtk.createTab(Const.ABOUT_US_PNG, Const.ICON_WIDTH, Const.ICON_HEIGHT, False)
t3=threading.Thread(target=about,args=(aboutTab,))
t3.start()
t3.join()
# print(time.time()-T1)
gtk.connect("delete-event", quit)
gtk.show_all()
gtk.mainLoop()
def do_activate(self):
self._settings = Gtk.Settings.get_default()
self._settings.set_property('gtk-application-prefer-dark-theme', True)
def __init__(self, useGtk=False):
_gtk = None
if useGtk is True:
from gi.repository import Gtk as _gtk
_glibbase.GlibReactorBase.__init__(self, GLib, _gtk, useGtk=useGtk)
def __init__(self, useGtk=False):
_gtk = None
if useGtk is True:
from gi.repository import Gtk as _gtk
_glibbase.PortableGlibReactorBase.__init__(self, GLib, _gtk,
useGtk=useGtk)
def get_icon_informations(self):
theme = Gtk.IconTheme.get_default()
self.is_hardcoded_icon()
self.icon_path = ""
icon_name = self.getIcon()
self.is_supported = self.get_is_supported()
self.supported_icons = None
full_path = False
if self.is_hardcoded:
self.icon_path = icon_name
if len(self.icon_path.split("/")) == 1:
icon_name = path.splitext(self.getIcon())[0]
else:
self.icon_path = self.getIcon()
full_path = True
icon = theme.lookup_icon(icon_name, 48, 0)
if icon and not full_path:
self.icon_path = icon.get_filename()
if self.is_hardcoded:
self.is_supported = True
if not self.icon_path or not path.exists(self.icon_path):
icon = theme.lookup_icon(
"image-missing", 48, 0)
if icon:
self.icon_path = icon.get_filename()
def is_app_menu():
"""
Check if the top application menu is enabled or not.
"""
default = True
try:
gsettings = Gio.Settings.new('org.gnome.settings-daemon.plugins.xsettings')
overrides = gsettings.get_value('overrides')['Gtk/ShellShowsAppMenu']
show_app_menu = not bool(GLib.Variant.new_int32(overrides))
except Exception:
show_app_menu = default
return show_app_menu
def data(self, index, role):
if not index.isValid():
return None
cat = self._categories[index.row()]
role = self.COLUMNS[role]
if role == "_name":
return unicode(cat.name, "utf8", "ignore")
elif role == "_iconname":
# funny, but it appears like Qt does not have something
# to lookup the icon path in QIcon
icons = Gtk.IconTheme.get_default()
info = icons.lookup_icon(cat.iconname, 48, 0)
if info:
return info.get_filename()
return ""
def data(self, index, role):
if not index.isValid():
return None
cat = self._categories[index.row()]
role = self.COLUMNS[role]
if role == "_name":
return unicode(cat.name, "utf8", "ignore")
elif role == "_iconname":
# funny, but it appears like Qt does not have something
# to lookup the icon path in QIcon
icons = Gtk.IconTheme.get_default()
info = icons.lookup_icon(cat.iconname, 48, 0)
if info:
return info.get_filename()
return ""