gtkhelpers.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 itertools
  22. # pylint: disable=import-error,wrong-import-position
  23. import gi
  24. gi.require_version('Gtk', '3.0')
  25. from gi.repository import Gtk, Gdk, GdkPixbuf, GObject, GLib
  26. # pylint: enable=import-error
  27. from qubespolicy.utils import sanitize_domain_name
  28. # pylint: enable=wrong-import-position
  29. class VMListModeler:
  30. def __init__(self, domains_info=None):
  31. self._entries = {}
  32. self._domains_info = domains_info
  33. self._icons = {}
  34. self._icon_size = 16
  35. self._theme = Gtk.IconTheme.get_default()
  36. self._create_entries()
  37. def _get_icon(self, name):
  38. if name not in self._icons:
  39. try:
  40. icon = self._theme.load_icon(name, self._icon_size, 0)
  41. except GLib.Error: # pylint: disable=catching-non-exception
  42. icon = self._theme.load_icon("edit-find", self._icon_size, 0)
  43. self._icons[name] = icon
  44. return self._icons[name]
  45. def _create_entries(self):
  46. for name, vm in self._domains_info.items():
  47. if name.startswith('$dispvm:'):
  48. vm_name = name[len('$dispvm:'):]
  49. dispvm = True
  50. else:
  51. vm_name = name
  52. dispvm = False
  53. sanitize_domain_name(vm_name, assert_sanitized=True)
  54. icon = self._get_icon(vm.get('icon', None))
  55. if dispvm:
  56. display_name = 'Disposable VM ({})'.format(vm_name)
  57. else:
  58. display_name = vm_name
  59. self._entries[display_name] = {
  60. 'api_name': name,
  61. 'icon': icon,
  62. 'vm': vm}
  63. def _get_valid_qube_name(self, combo, entry_box, whitelist):
  64. name = None
  65. if combo and combo.get_active_id():
  66. selected = combo.get_active_id()
  67. if selected in self._entries and \
  68. self._entries[selected]['api_name'] in whitelist:
  69. name = selected
  70. if not name and entry_box:
  71. typed = entry_box.get_text()
  72. if typed in self._entries and \
  73. self._entries[typed]['api_name'] in whitelist:
  74. name = typed
  75. return name
  76. def _combo_change(self, selection_trigger, combo, entry_box, whitelist):
  77. data = None
  78. name = self._get_valid_qube_name(combo, entry_box, whitelist)
  79. if name:
  80. entry = self._entries[name]
  81. data = entry['api_name']
  82. if entry_box:
  83. entry_box.set_icon_from_pixbuf(
  84. Gtk.EntryIconPosition.PRIMARY, entry['icon'])
  85. else:
  86. if entry_box:
  87. entry_box.set_icon_from_stock(
  88. Gtk.EntryIconPosition.PRIMARY, "gtk-find")
  89. if selection_trigger:
  90. selection_trigger(data)
  91. def _entry_activate(self, activation_trigger, combo, entry_box, whitelist):
  92. name = self._get_valid_qube_name(combo, entry_box, whitelist)
  93. if name:
  94. activation_trigger(entry_box)
  95. def apply_model(self, destination_object, vm_list,
  96. selection_trigger=None, activation_trigger=None):
  97. if isinstance(destination_object, Gtk.ComboBox):
  98. list_store = Gtk.ListStore(int, str, GdkPixbuf.Pixbuf)
  99. for entry_no, display_name in zip(itertools.count(),
  100. sorted(self._entries)):
  101. entry = self._entries[display_name]
  102. if entry['api_name'] in vm_list:
  103. list_store.append([entry_no, display_name, entry['icon']])
  104. destination_object.set_model(list_store)
  105. destination_object.set_id_column(1)
  106. icon_column = Gtk.CellRendererPixbuf()
  107. destination_object.pack_start(icon_column, False)
  108. destination_object.add_attribute(icon_column, "pixbuf", 2)
  109. destination_object.set_entry_text_column(1)
  110. if destination_object.get_has_entry():
  111. entry_box = destination_object.get_child()
  112. area = Gtk.CellAreaBox()
  113. area.pack_start(icon_column, False, False, False)
  114. area.add_attribute(icon_column, "pixbuf", 2)
  115. completion = Gtk.EntryCompletion.new_with_area(area)
  116. completion.set_inline_selection(True)
  117. completion.set_inline_completion(True)
  118. completion.set_popup_completion(True)
  119. completion.set_popup_single_match(False)
  120. completion.set_model(list_store)
  121. completion.set_text_column(1)
  122. entry_box.set_completion(completion)
  123. if activation_trigger:
  124. entry_box.connect("activate",
  125. lambda entry: self._entry_activate(
  126. activation_trigger,
  127. destination_object,
  128. entry,
  129. vm_list))
  130. # A Combo with an entry has a text column already
  131. text_column = destination_object.get_cells()[0]
  132. destination_object.reorder(text_column, 1)
  133. else:
  134. entry_box = None
  135. text_column = Gtk.CellRendererText()
  136. destination_object.pack_start(text_column, False)
  137. destination_object.add_attribute(text_column, "text", 1)
  138. changed_function = lambda combo: self._combo_change(
  139. selection_trigger,
  140. combo,
  141. entry_box,
  142. vm_list)
  143. destination_object.connect("changed", changed_function)
  144. changed_function(destination_object)
  145. else:
  146. raise TypeError(
  147. "Only expecting Gtk.ComboBox objects to want our model.")
  148. def apply_icon(self, entry, qube_name):
  149. if isinstance(entry, Gtk.Entry):
  150. if qube_name in self._entries:
  151. entry.set_icon_from_pixbuf(
  152. Gtk.EntryIconPosition.PRIMARY,
  153. self._entries[qube_name]['icon'])
  154. else:
  155. raise ValueError("The specified source qube does not exist!")
  156. else:
  157. raise TypeError(
  158. "Only expecting Gtk.Entry objects to want our icon.")
  159. class GtkOneTimerHelper:
  160. # pylint: disable=too-few-public-methods
  161. def __init__(self, wait_seconds):
  162. self._wait_seconds = wait_seconds
  163. self._current_timer_id = 0
  164. self._timer_completed = False
  165. def _invalidate_timer_completed(self):
  166. self._timer_completed = False
  167. def _invalidate_current_timer(self):
  168. self._current_timer_id += 1
  169. def _timer_check_run(self, timer_id):
  170. if self._current_timer_id == timer_id:
  171. self._timer_run(timer_id)
  172. self._timer_completed = True
  173. else:
  174. pass
  175. def _timer_run(self, timer_id):
  176. raise NotImplementedError("Not yet implemented")
  177. def _timer_schedule(self):
  178. self._invalidate_current_timer()
  179. GObject.timeout_add(int(round(self._wait_seconds * 1000)),
  180. self._timer_check_run,
  181. self._current_timer_id)
  182. def _timer_has_completed(self):
  183. return self._timer_completed
  184. class FocusStealingHelper(GtkOneTimerHelper):
  185. def __init__(self, window, target_button, wait_seconds=1):
  186. GtkOneTimerHelper.__init__(self, wait_seconds)
  187. self._window = window
  188. self._target_button = target_button
  189. self._window.connect("window-state-event", self._window_state_event)
  190. self._target_sensitivity = False
  191. self._target_button.set_sensitive(self._target_sensitivity)
  192. def _window_changed_focus(self, window_is_focused):
  193. self._target_button.set_sensitive(False)
  194. self._invalidate_timer_completed()
  195. if window_is_focused:
  196. self._timer_schedule()
  197. else:
  198. self._invalidate_current_timer()
  199. def _window_state_event(self, window, event):
  200. assert window == self._window, \
  201. 'Window state callback called with wrong window'
  202. changed_focus = event.changed_mask & Gdk.WindowState.FOCUSED
  203. window_focus = event.new_window_state & Gdk.WindowState.FOCUSED
  204. if changed_focus:
  205. self._window_changed_focus(window_focus != 0)
  206. # Propagate event further
  207. return False
  208. def _timer_run(self, timer_id):
  209. self._target_button.set_sensitive(self._target_sensitivity)
  210. def request_sensitivity(self, sensitivity):
  211. if self._timer_has_completed() or not sensitivity:
  212. self._target_button.set_sensitive(sensitivity)
  213. self._target_sensitivity = sensitivity
  214. def can_perform_action(self):
  215. return self._timer_has_completed()