gtkhelpers.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #!/usr/bin/python
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2017 boring-stuff <boring-stuff@users.noreply.github.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. import gi
  22. import os
  23. gi.require_version('Gtk', '3.0')
  24. from gi.repository import Gtk, Gdk, GdkPixbuf, GObject, GLib
  25. import qubes
  26. from qubespolicy.utils import sanitize_domain_name
  27. class GtkIconGetter:
  28. def __init__(self, size):
  29. self._icons = {}
  30. self._size = size
  31. self._theme = Gtk.IconTheme.get_default()
  32. def get_icon(self, name):
  33. if name not in self._icons:
  34. try:
  35. icon = self._theme.load_icon(name, self._size, 0)
  36. except GLib.Error:
  37. icon = self._theme.load_icon("edit-find", self._size, 0)
  38. self._icons[name] = icon
  39. return self._icons[name]
  40. class VMListModeler:
  41. def __init__(self):
  42. self._icon_getter = GtkIconGetter(16)
  43. self._entries = {}
  44. self._create_entries()
  45. def _get_icon(self, vm):
  46. return self._icon_getter.get_icon(vm.label.icon)
  47. def _get_list(self):
  48. collection = qubes.QubesVmCollection()
  49. try:
  50. collection.lock_db_for_reading()
  51. collection.load()
  52. return [vm for vm in collection.values()]
  53. finally:
  54. collection.unlock_db()
  55. def _create_entries(self):
  56. for vm in self._get_list():
  57. sanitize_domain_name(vm.name, assert_sanitized=True)
  58. icon = self._get_icon(vm)
  59. self._entries[vm.name] = {'qid': vm.qid,
  60. 'icon': icon,
  61. 'vm': vm}
  62. def _get_valid_qube_name(self, combo, entry_box, exclusions):
  63. name = None
  64. if combo and combo.get_active_id():
  65. selected = combo.get_active_id()
  66. if selected in self._entries and selected not in exclusions:
  67. name = selected
  68. if not name and entry_box:
  69. typed = entry_box.get_text()
  70. if typed in self._entries and typed not in exclusions:
  71. name = typed
  72. return name
  73. def _combo_change(self, selection_trigger, combo, entry_box, exclusions):
  74. data = None
  75. name = self._get_valid_qube_name(combo, entry_box, exclusions)
  76. if name:
  77. entry = self._entries[name]
  78. data = (entry['qid'], name)
  79. if entry_box:
  80. entry_box.set_icon_from_pixbuf(
  81. Gtk.EntryIconPosition.PRIMARY, entry['icon'])
  82. else:
  83. if entry_box:
  84. entry_box.set_icon_from_stock(
  85. Gtk.EntryIconPosition.PRIMARY, "gtk-find")
  86. if selection_trigger:
  87. selection_trigger(data)
  88. def _entry_activate(self, activation_trigger, combo, entry_box, exclusions):
  89. name = self._get_valid_qube_name(combo, entry_box, exclusions)
  90. if name:
  91. activation_trigger(entry_box)
  92. def apply_model(self, destination_object, vm_filter_list=None,
  93. selection_trigger=None, activation_trigger=None):
  94. if isinstance(destination_object, Gtk.ComboBox):
  95. list_store = Gtk.ListStore(int, str, GdkPixbuf.Pixbuf)
  96. exclusions = []
  97. for vm_name in sorted(self._entries.keys()):
  98. entry = self._entries[vm_name]
  99. matches = True
  100. if vm_filter_list:
  101. for vm_filter in vm_filter_list:
  102. if not vm_filter.matches(entry['vm']):
  103. matches = False
  104. break
  105. if matches:
  106. list_store.append([entry['qid'], vm_name, entry['icon']])
  107. else:
  108. exclusions += [vm_name]
  109. destination_object.set_model(list_store)
  110. destination_object.set_id_column(1)
  111. icon_column = Gtk.CellRendererPixbuf()
  112. destination_object.pack_start(icon_column, False)
  113. destination_object.add_attribute(icon_column, "pixbuf", 2)
  114. destination_object.set_entry_text_column(1)
  115. if destination_object.get_has_entry():
  116. entry_box = destination_object.get_child()
  117. area = Gtk.CellAreaBox()
  118. area.pack_start(icon_column, False, False, False)
  119. area.add_attribute(icon_column, "pixbuf", 2)
  120. completion = Gtk.EntryCompletion.new_with_area(area)
  121. completion.set_inline_selection(True)
  122. completion.set_inline_completion(True)
  123. completion.set_popup_completion(True)
  124. completion.set_popup_single_match(False)
  125. completion.set_model(list_store)
  126. completion.set_text_column(1)
  127. entry_box.set_completion(completion)
  128. if activation_trigger:
  129. entry_box.connect("activate",
  130. lambda entry: self._entry_activate(
  131. activation_trigger,
  132. destination_object,
  133. entry,
  134. exclusions))
  135. # A Combo with an entry has a text column already
  136. text_column = destination_object.get_cells()[0]
  137. destination_object.reorder(text_column, 1)
  138. else:
  139. entry_box = None
  140. text_column = Gtk.CellRendererText()
  141. destination_object.pack_start(text_column, False)
  142. destination_object.add_attribute(text_column, "text", 1)
  143. changed_function = lambda combo: self._combo_change(
  144. selection_trigger,
  145. combo,
  146. entry_box,
  147. exclusions)
  148. destination_object.connect("changed", changed_function)
  149. changed_function(destination_object)
  150. else:
  151. raise TypeError(
  152. "Only expecting Gtk.ComboBox objects to want our model.")
  153. def apply_icon(self, entry, qube_name):
  154. if isinstance(entry, Gtk.Entry):
  155. if qube_name in self._entries:
  156. entry.set_icon_from_pixbuf(
  157. Gtk.EntryIconPosition.PRIMARY,
  158. self._entries[qube_name]['icon'])
  159. else:
  160. raise ValueError("The specified source qube does not exist!")
  161. else:
  162. raise TypeError(
  163. "Only expecting Gtk.Entry objects to want our icon.")
  164. class NameBlacklistFilter:
  165. def __init__(self, avoid_names_list):
  166. self._avoid_names_list = avoid_names_list
  167. def matches(self, vm):
  168. return vm.name not in self._avoid_names_list
  169. class NameWhitelistFilter:
  170. def __init__(self, allowed_names_list):
  171. self._allowed_names_list = allowed_names_list
  172. def matches(self, vm):
  173. return vm.name in self._allowed_names_list
  174. class GtkOneTimerHelper:
  175. def __init__(self, wait_seconds):
  176. self._wait_seconds = wait_seconds
  177. self._current_timer_id = 0
  178. self._timer_completed = False
  179. def _invalidate_timer_completed(self):
  180. self._timer_completed = False
  181. def _invalidate_current_timer(self):
  182. self._current_timer_id += 1
  183. def _timer_check_run(self, timer_id):
  184. if self._current_timer_id == timer_id:
  185. self._timer_run(timer_id)
  186. self._timer_completed = True
  187. else:
  188. pass
  189. def _timer_run(self, timer_id):
  190. raise NotImplementedError("Not yet implemented")
  191. def _timer_schedule(self):
  192. self._invalidate_current_timer()
  193. GObject.timeout_add(int(round(self._wait_seconds * 1000)),
  194. self._timer_check_run,
  195. self._current_timer_id)
  196. def _timer_has_completed(self):
  197. return self._timer_completed
  198. class FocusStealingHelper(GtkOneTimerHelper):
  199. def __init__(self, window, target_button, wait_seconds=1):
  200. GtkOneTimerHelper.__init__(self, wait_seconds)
  201. self._window = window
  202. self._target_button = target_button
  203. self._window.connect("window-state-event", self._window_state_event)
  204. self._target_sensitivity = False
  205. self._target_button.set_sensitive(self._target_sensitivity)
  206. def _window_changed_focus(self, window_is_focused):
  207. self._target_button.set_sensitive(False)
  208. self._invalidate_timer_completed()
  209. if window_is_focused:
  210. self._timer_schedule()
  211. else:
  212. self._invalidate_current_timer()
  213. def _window_state_event(self, window, event):
  214. assert window == self._window, \
  215. 'Window state callback called with wrong window'
  216. changed_focus = event.changed_mask & Gdk.WindowState.FOCUSED
  217. window_focus = event.new_window_state & Gdk.WindowState.FOCUSED
  218. if changed_focus:
  219. self._window_changed_focus(window_focus != 0)
  220. # Propagate event further
  221. return False
  222. def _timer_run(self, timer_id):
  223. self._target_button.set_sensitive(self._target_sensitivity)
  224. def request_sensitivity(self, sensitivity):
  225. if self._timer_has_completed() or not sensitivity:
  226. self._target_button.set_sensitive(sensitivity)
  227. self._target_sensitivity = sensitivity
  228. def can_perform_action(self):
  229. return self._timer_has_completed()