In unit-tests, always use StringIO, not io
[zeroinstall.git] / zeroinstall / gtkui / applistbox.py
blob619d7fda4f27323eae863baf3097a442e4c43f79
1 """A GTK dialog which displays a list of Zero Install applications in the menu."""
2 # Copyright (C) 2009, Thomas Leonard
3 # See the README file for details, or visit http://0install.net.
5 from zeroinstall import _
6 import os
7 import gtk, gobject, pango
8 import subprocess
10 from zeroinstall import support
11 from zeroinstall.gtkui import icon, xdgutils
12 from zeroinstall.injector import reader, model, namespaces
14 def _pango_escape(s):
15 return s.replace('&', '&amp;').replace('<', '&lt;')
17 class AppList:
18 """A list of applications which can be displayed in an L{AppListBox}.
19 For example, a program might implement this to display a list of plugins.
20 This default implementation lists applications in the freedesktop.org menus.
21 """
22 def get_apps(self):
23 """Return a list of application URIs."""
24 self.apps = xdgutils.discover_existing_apps()
25 return self.apps.keys()
27 def remove_app(self, uri):
28 """Remove this application from the list."""
29 path = self.apps[uri]
30 os.unlink(path)
32 _tooltips = {
33 0: _("Run the application"),
34 1: _("Show documentation files"),
35 2: _("Upgrade or change versions"),
36 3: _("Remove launcher from the menu"),
39 class AppListBox:
40 """A dialog box which lists applications already added to the menus."""
41 ICON, URI, NAME, MARKUP = range(4)
43 def __init__(self, iface_cache, app_list):
44 """Constructor.
45 @param iface_cache: used to find extra information about programs
46 @type iface_cache: L{zeroinstall.injector.iface_cache.IfaceCache}
47 @param app_list: used to list or remove applications
48 @type app_list: L{AppList}
49 """
50 builderfile = os.path.join(os.path.dirname(__file__), 'desktop.ui')
51 self.iface_cache = iface_cache
52 self.app_list = app_list
54 builder = gtk.Builder()
55 builder.set_translation_domain('zero-install')
56 builder.add_from_file(builderfile)
57 self.window = builder.get_object('applist')
58 tv = builder.get_object('treeview')
60 self.model = gtk.ListStore(gtk.gdk.Pixbuf, str, str, str)
62 self.populate_model()
63 tv.set_model(self.model)
64 tv.get_selection().set_mode(gtk.SELECTION_NONE)
66 cell_icon = gtk.CellRendererPixbuf()
67 cell_icon.set_property('xpad', 4)
68 cell_icon.set_property('ypad', 4)
69 column = gtk.TreeViewColumn('Icon', cell_icon, pixbuf = AppListBox.ICON)
70 tv.append_column(column)
72 cell_text = gtk.CellRendererText()
73 cell_text.set_property('ellipsize', pango.ELLIPSIZE_END)
74 column = gtk.TreeViewColumn('Name', cell_text, markup = AppListBox.MARKUP)
75 column.set_expand(True)
76 tv.append_column(column)
78 cell_actions = ActionsRenderer(self, tv)
79 actions_column = gtk.TreeViewColumn('Actions', cell_actions, uri = AppListBox.URI)
80 tv.append_column(actions_column)
82 def redraw_actions(path):
83 if path is not None:
84 area = tv.get_cell_area(path, actions_column)
85 tv.queue_draw_area(*area)
87 tv.set_property('has-tooltip', True)
88 def query_tooltip(widget, x, y, keyboard_mode, tooltip):
89 x, y = tv.convert_widget_to_bin_window_coords(x, y)
90 pos = tv.get_path_at_pos(x, y)
91 if pos:
92 new_hover = (None, None, None)
93 path, col, x, y = pos
94 if col == actions_column:
95 area = tv.get_cell_area(path, col)
96 iface = self.model[path][AppListBox.URI]
97 action = cell_actions.get_action(area, x, y)
98 if action is not None:
99 new_hover = (path, iface, action)
100 if new_hover != cell_actions.hover:
101 redraw_actions(cell_actions.hover[0])
102 cell_actions.hover = new_hover
103 redraw_actions(cell_actions.hover[0])
104 tv.set_tooltip_cell(tooltip, pos[0], pos[1], None)
106 if new_hover[2] is not None:
107 tooltip.set_text(_tooltips[cell_actions.hover[2]])
108 return True
109 return False
110 tv.connect('query-tooltip', query_tooltip)
112 def leave(widget, lev):
113 redraw_actions(cell_actions.hover[0])
114 cell_actions.hover = (None, None, None)
116 tv.connect('leave-notify-event', leave)
118 self.model.set_sort_column_id(AppListBox.NAME, gtk.SORT_ASCENDING)
120 show_cache = builder.get_object('show_cache')
121 self.window.action_area.set_child_secondary(show_cache, True)
123 def response(box, resp):
124 if resp == 0:
125 subprocess.Popen(['0store', 'manage'])
126 else:
127 box.destroy()
128 self.window.connect('response', response)
130 def populate_model(self):
131 m = self.model
132 m.clear()
134 for uri in self.app_list.get_apps():
135 itr = m.append()
136 m[itr][AppListBox.URI] = uri
138 try:
139 iface = self.iface_cache.get_interface(uri)
140 name = iface.get_name()
141 summary = iface.summary or _('No information available')
142 summary = summary[:1].capitalize() + summary[1:]
143 icon_width, icon_height = gtk.icon_size_lookup(gtk.ICON_SIZE_DIALOG)
144 pixbuf = icon.load_icon(self.iface_cache.get_icon_path(iface), icon_width, icon_height)
145 except model.InvalidInterface as ex:
146 name = uri
147 summary = unicode(ex)
148 pixbuf = None
150 m[itr][AppListBox.NAME] = name
151 if pixbuf is None:
152 pixbuf = self.window.render_icon(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_DIALOG)
153 m[itr][AppListBox.ICON] = pixbuf
155 m[itr][AppListBox.MARKUP] = '<b>%s</b>\n<i>%s</i>' % (_pango_escape(name), _pango_escape(summary))
157 def action_run(self, uri):
158 iface = self.iface_cache.get_interface(uri)
159 reader.update_from_cache(iface)
160 if len(iface.get_metadata(namespaces.XMLNS_IFACE, 'needs-terminal')):
161 if gtk.pygtk_version >= (2,16,0) and gtk.gdk.WINDOWING == 'quartz':
162 script = ['0launch', '--', uri]
163 osascript = support.find_in_path('osascript')
164 subprocess.Popen([osascript, '-e', 'tell app "Terminal"', '-e', 'activate',
165 '-e', 'do script "%s"' % ' '.join(script), '-e', 'end tell'])
166 return
167 for terminal in ['x-terminal-emulator', 'xterm', 'gnome-terminal', 'rxvt', 'konsole']:
168 exe = support.find_in_path(terminal)
169 if exe:
170 if terminal == 'gnome-terminal':
171 flag = '-x'
172 else:
173 flag = '-e'
174 subprocess.Popen([terminal, flag, '0launch', '--', uri])
175 break
176 else:
177 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("Can't find a suitable terminal emulator"))
178 box.run()
179 box.destroy()
180 else:
181 subprocess.Popen(['0launch', '--', uri])
183 def action_help(self, uri):
184 from zeroinstall.injector.config import load_config
185 from zeroinstall import helpers
186 c = load_config()
187 sels = helpers.ensure_cached(uri, config = c)
188 if not sels:
189 return
191 impl = sels.selections[uri]
192 assert impl, "Failed to choose an implementation of %s" % uri
193 help_dir = impl.attrs.get('doc-dir')
195 if impl.id.startswith('package:'):
196 assert os.path.isabs(help_dir), "Package doc-dir must be absolute!"
197 path = help_dir
198 else:
199 path = impl.local_path or c.stores.lookup_any(impl.digests)
201 assert path, "Chosen implementation is not cached!"
202 if help_dir:
203 path = os.path.join(path, help_dir)
204 else:
205 main = impl.main
206 if main:
207 # Hack for ROX applications. They should be updated to
208 # set doc-dir.
209 help_dir = os.path.join(path, os.path.dirname(main), 'Help')
210 if os.path.isdir(help_dir):
211 path = help_dir
213 # xdg-open has no "safe" mode, so check we're not "opening" an application.
214 if os.path.exists(os.path.join(path, 'AppRun')):
215 raise Exception(_("Documentation directory '%s' is an AppDir; refusing to open") % path)
217 subprocess.Popen(['xdg-open', path])
219 def action_properties(self, uri):
220 subprocess.Popen(['0launch', '--gui', '--', uri])
222 def action_remove(self, uri):
223 try:
224 name = self.iface_cache.get_interface(uri).get_name()
225 except model.InvalidInterface:
226 name = uri
228 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL, "")
229 box.set_markup(_("Remove <b>%s</b> from the menu?") % _pango_escape(name))
230 box.add_button(gtk.STOCK_DELETE, gtk.RESPONSE_OK)
231 box.set_default_response(gtk.RESPONSE_OK)
232 resp = box.run()
233 box.destroy()
234 if resp == gtk.RESPONSE_OK:
235 try:
236 self.app_list.remove_app(uri)
237 except Exception as ex:
238 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("Failed to remove %(interface_name)s: %(exception)s") % {'interface_name': name, 'exception': ex})
239 box.run()
240 box.destroy()
241 self.populate_model()
243 class ActionsRenderer(gtk.GenericCellRenderer):
244 __gproperties__ = {
245 "uri": (gobject.TYPE_STRING, "Text", "Text", "-", gobject.PARAM_READWRITE),
248 def __init__(self, applist, widget):
249 "@param widget: widget used for style information"
250 gtk.GenericCellRenderer.__init__(self)
251 self.set_property('mode', gtk.CELL_RENDERER_MODE_ACTIVATABLE)
252 self.padding = 4
254 self.applist = applist
256 self.size = 10
257 def stock_lookup(name):
258 pixbuf = widget.render_icon(name, gtk.ICON_SIZE_BUTTON)
259 self.size = max(self.size, pixbuf.get_width(), pixbuf.get_height())
260 return pixbuf
262 if hasattr(gtk, 'STOCK_MEDIA_PLAY'):
263 self.run = stock_lookup(gtk.STOCK_MEDIA_PLAY)
264 else:
265 self.run = stock_lookup(gtk.STOCK_YES)
266 self.help = stock_lookup(gtk.STOCK_HELP)
267 self.properties = stock_lookup(gtk.STOCK_PROPERTIES)
268 self.remove = stock_lookup(gtk.STOCK_DELETE)
269 self.hover = (None, None, None) # Path, URI, action
271 def do_set_property(self, prop, value):
272 setattr(self, prop.name, value)
274 def on_get_size(self, widget, cell_area, layout = None):
275 total_size = self.size * 2 + self.padding * 4
276 return (0, 0, total_size, total_size)
278 def on_render(self, window, widget, background_area, cell_area, expose_area, flags):
279 hovering = self.uri == self.hover[1]
281 s = self.size
283 cx = cell_area.x + self.padding
284 cy = cell_area.y + (cell_area.height / 2) - s - self.padding
286 ss = s + self.padding * 2
288 b = 0
289 for (x, y), icon in [((0, 0), self.run),
290 ((ss, 0), self.help),
291 ((0, ss), self.properties),
292 ((ss, ss), self.remove)]:
293 if hovering and b == self.hover[2]:
294 widget.style.paint_box(window, gtk.STATE_NORMAL, gtk.SHADOW_OUT,
295 expose_area, widget, None,
296 cx + x - 2, cy + y - 2, s + 4, s + 4)
298 window.draw_pixbuf(widget.style.white_gc, icon,
299 0, 0, # Source x,y
300 cx + x, cy + y)
301 b += 1
303 def on_activate(self, event, widget, path, background_area, cell_area, flags):
304 if event.type != gtk.gdk.BUTTON_PRESS:
305 return False
306 action = self.get_action(cell_area, event.x - cell_area.x, event.y - cell_area.y)
307 if action == 0:
308 self.applist.action_run(self.uri)
309 elif action == 1:
310 self.applist.action_help(self.uri)
311 elif action == 2:
312 self.applist.action_properties(self.uri)
313 elif action == 3:
314 self.applist.action_remove(self.uri)
316 def get_action(self, area, x, y):
317 lower = int(y > (area.height / 2)) * 2
319 s = self.size + self.padding * 2
320 if x > s * 2:
321 return None
322 return int(x > s) + lower