gtkhelpers.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 itertools
  23. gi.require_version('Gtk', '3.0')
  24. from gi.repository import Gtk, Gdk, GdkPixbuf, GObject, GLib
  25. from qubespolicy.utils import sanitize_domain_name
  26. class GtkIconGetter:
  27. def __init__(self, size):
  28. self._icons = {}
  29. self._size = size
  30. self._theme = Gtk.IconTheme.get_default()
  31. def get_icon(self, name):
  32. if name not in self._icons:
  33. try:
  34. icon = self._theme.load_icon(name, self._size, 0)
  35. except GLib.Error:
  36. icon = self._theme.load_icon("edit-find", self._size, 0)
  37. self._icons[name] = icon
  38. return self._icons[name]
  39. class VMListModeler:
  40. def __init__(self, domains_info=None):
  41. self._icon_getter = GtkIconGetter(16)
  42. self._entries = {}
  43. self._domains_info = domains_info
  44. self._create_entries()
  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._icon_getter.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.keys())):
  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. def __init__(self, wait_seconds):
  161. self._wait_seconds = wait_seconds
  162. self._current_timer_id = 0
  163. self._timer_completed = False
  164. def _invalidate_timer_completed(self):
  165. self._timer_completed = False
  166. def _invalidate_current_timer(self):
  167. self._current_timer_id += 1
  168. def _timer_check_run(self, timer_id):
  169. if self._current_timer_id == timer_id:
  170. self._timer_run(timer_id)
  171. self._timer_completed = True
  172. else:
  173. pass
  174. def _timer_run(self, timer_id):
  175. raise NotImplementedError("Not yet implemented")
  176. def _timer_schedule(self):
  177. self._invalidate_current_timer()
  178. GObject.timeout_add(int(round(self._wait_seconds * 1000)),
  179. self._timer_check_run,
  180. self._current_timer_id)
  181. def _timer_has_completed(self):
  182. return self._timer_completed
  183. class FocusStealingHelper(GtkOneTimerHelper):
  184. def __init__(self, window, target_button, wait_seconds=1):
  185. GtkOneTimerHelper.__init__(self, wait_seconds)
  186. self._window = window
  187. self._target_button = target_button
  188. self._window.connect("window-state-event", self._window_state_event)
  189. self._target_sensitivity = False
  190. self._target_button.set_sensitive(self._target_sensitivity)
  191. def _window_changed_focus(self, window_is_focused):
  192. self._target_button.set_sensitive(False)
  193. self._invalidate_timer_completed()
  194. if window_is_focused:
  195. self._timer_schedule()
  196. else:
  197. self._invalidate_current_timer()
  198. def _window_state_event(self, window, event):
  199. assert window == self._window, \
  200. 'Window state callback called with wrong window'
  201. changed_focus = event.changed_mask & Gdk.WindowState.FOCUSED
  202. window_focus = event.new_window_state & Gdk.WindowState.FOCUSED
  203. if changed_focus:
  204. self._window_changed_focus(window_focus != 0)
  205. # Propagate event further
  206. return False
  207. def _timer_run(self, timer_id):
  208. self._target_button.set_sensitive(self._target_sensitivity)
  209. def request_sensitivity(self, sensitivity):
  210. if self._timer_has_completed() or not sensitivity:
  211. self._target_button.set_sensitive(sensitivity)
  212. self._target_sensitivity = sensitivity
  213. def can_perform_action(self):
  214. return self._timer_has_completed()