New icon for Zero Install
[zeroinstall.git] / zeroinstall / gtkui / applistbox.py
bloba67116d704ef73ac40c5aa6908f0b4f91c8db1c1
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, treetips
12 from zeroinstall.injector import policy, 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 tips = treetips.TreeTips()
88 def motion(widget, mev):
89 if mev.window == tv.get_bin_window():
90 new_hover = (None, None, None)
91 pos = tv.get_path_at_pos(int(mev.x), int(mev.y))
92 if pos:
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 tips.prime(tv, _tooltips.get(cell_actions.hover[2], None))
105 tv.connect('motion-notify-event', motion)
107 def leave(widget, lev):
108 redraw_actions(cell_actions.hover[0])
109 cell_actions.hover = (None, None, None)
110 tips.hide()
112 tv.connect('leave-notify-event', leave)
114 self.model.set_sort_column_id(AppListBox.NAME, gtk.SORT_ASCENDING)
116 show_cache = builder.get_object('show_cache')
117 self.window.action_area.set_child_secondary(show_cache, True)
119 def response(box, resp):
120 if resp == 0:
121 subprocess.Popen(['0store', 'manage'])
122 else:
123 box.destroy()
124 self.window.connect('response', response)
126 def populate_model(self):
127 model = self.model
128 model.clear()
130 for uri in self.app_list.get_apps():
131 itr = model.append()
132 model[itr][AppListBox.URI] = uri
134 iface = self.iface_cache.get_interface(uri)
135 name = iface.get_name()
136 summary = iface.summary or _('No information available')
137 summary = summary[:1].capitalize() + summary[1:]
139 model[itr][AppListBox.NAME] = name
140 icon_width, icon_height = gtk.icon_size_lookup(gtk.ICON_SIZE_DIALOG)
141 pixbuf = icon.load_icon(self.iface_cache.get_icon_path(iface), icon_width, icon_height)
142 if pixbuf is None:
143 pixbuf = self.window.render_icon(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_DIALOG)
144 model[itr][AppListBox.ICON] = pixbuf
146 model[itr][AppListBox.MARKUP] = '<b>%s</b>\n<i>%s</i>' % (_pango_escape(name), _pango_escape(summary))
148 def action_run(self, uri):
149 iface = self.iface_cache.get_interface(uri)
150 reader.update_from_cache(iface)
151 if len(iface.get_metadata(namespaces.XMLNS_IFACE, 'needs-terminal')):
152 for terminal in ['xterm', 'gnome-terminal', 'rxvt', 'konsole']:
153 exe = support.find_in_path(terminal)
154 if exe:
155 if terminal == 'gnome-terminal':
156 flag = '-x'
157 else:
158 flag = '-e'
159 subprocess.Popen([terminal, flag, '0launch', '--', uri])
160 break
161 else:
162 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("Can't find a suitable terminal emulator"))
163 box.run()
164 box.destroy()
165 else:
166 subprocess.Popen(['0launch', '--', uri])
168 def action_help(self, uri):
169 p = policy.Policy(uri)
170 policy.network_use = model.network_offline
171 if p.need_download():
172 child = subprocess.Popen(['0launch', '-d', '--', uri])
173 child.wait()
174 if child.returncode:
175 return
176 iface = self.iface_cache.get_interface(uri)
177 reader.update_from_cache(iface)
178 p.solve_with_downloads()
179 impl = p.solver.selections[iface]
180 assert impl, "Failed to choose an implementation of %s" % uri
181 help_dir = impl.metadata.get('doc-dir')
182 path = p.get_implementation_path(impl)
183 assert path, "Chosen implementation is not cached!"
184 if help_dir:
185 path = os.path.join(path, help_dir)
186 else:
187 main = impl.main
188 if main:
189 # Hack for ROX applications. They should be updated to
190 # set doc-dir.
191 help_dir = os.path.join(path, os.path.dirname(main), 'Help')
192 if os.path.isdir(help_dir):
193 path = help_dir
195 # xdg-open has no "safe" mode, so check we're not "opening" an application.
196 if os.path.exists(os.path.join(path, 'AppRun')):
197 raise Exception(_("Documentation directory '%s' is an AppDir; refusing to open") % path)
199 subprocess.Popen(['xdg-open', path])
201 def action_properties(self, uri):
202 subprocess.Popen(['0launch', '--gui', '--', uri])
204 def action_remove(self, uri):
205 name = self.iface_cache.get_interface(uri).get_name()
207 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL, "")
208 box.set_markup(_("Remove <b>%s</b> from the menu?") % _pango_escape(name))
209 box.add_button(gtk.STOCK_DELETE, gtk.RESPONSE_OK)
210 box.set_default_response(gtk.RESPONSE_OK)
211 resp = box.run()
212 box.destroy()
213 if resp == gtk.RESPONSE_OK:
214 try:
215 self.app_list.remove_app(uri)
216 except Exception, ex:
217 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})
218 box.run()
219 box.destroy()
220 self.populate_model()
222 class ActionsRenderer(gtk.GenericCellRenderer):
223 __gproperties__ = {
224 "uri": (gobject.TYPE_STRING, "Text", "Text", "-", gobject.PARAM_READWRITE),
227 def __init__(self, applist, widget):
228 "@param widget: widget used for style information"
229 gtk.GenericCellRenderer.__init__(self)
230 self.set_property('mode', gtk.CELL_RENDERER_MODE_ACTIVATABLE)
231 self.padding = 4
233 self.applist = applist
235 self.size = 10
236 def stock_lookup(name):
237 pixbuf = widget.render_icon(name, gtk.ICON_SIZE_BUTTON)
238 self.size = max(self.size, pixbuf.get_width(), pixbuf.get_height())
239 return pixbuf
241 if hasattr(gtk, 'STOCK_MEDIA_PLAY'):
242 self.run = stock_lookup(gtk.STOCK_MEDIA_PLAY)
243 else:
244 self.run = stock_lookup(gtk.STOCK_YES)
245 self.help = stock_lookup(gtk.STOCK_HELP)
246 self.properties = stock_lookup(gtk.STOCK_PROPERTIES)
247 self.remove = stock_lookup(gtk.STOCK_DELETE)
248 self.hover = (None, None, None) # Path, URI, action
250 def do_set_property(self, prop, value):
251 setattr(self, prop.name, value)
253 def on_get_size(self, widget, cell_area, layout = None):
254 total_size = self.size * 2 + self.padding * 4
255 return (0, 0, total_size, total_size)
257 def on_render(self, window, widget, background_area, cell_area, expose_area, flags):
258 hovering = self.uri == self.hover[1]
260 s = self.size
262 cx = cell_area.x + self.padding
263 cy = cell_area.y + (cell_area.height / 2) - s - self.padding
265 ss = s + self.padding * 2
267 b = 0
268 for (x, y), icon in [((0, 0), self.run),
269 ((ss, 0), self.help),
270 ((0, ss), self.properties),
271 ((ss, ss), self.remove)]:
272 if hovering and b == self.hover[2]:
273 widget.style.paint_box(window, gtk.STATE_NORMAL, gtk.SHADOW_OUT,
274 expose_area, widget, None,
275 cx + x - 2, cy + y - 2, s + 4, s + 4)
277 window.draw_pixbuf(widget.style.white_gc, icon,
278 0, 0, # Source x,y
279 cx + x, cy + y)
280 b += 1
282 def on_activate(self, event, widget, path, background_area, cell_area, flags):
283 if event.type != gtk.gdk.BUTTON_PRESS:
284 return False
285 action = self.get_action(cell_area, event.x - cell_area.x, event.y - cell_area.y)
286 if action == 0:
287 self.applist.action_run(self.uri)
288 elif action == 1:
289 self.applist.action_help(self.uri)
290 elif action == 2:
291 self.applist.action_properties(self.uri)
292 elif action == 3:
293 self.applist.action_remove(self.uri)
295 def get_action(self, area, x, y):
296 lower = int(y > (area.height / 2)) * 2
298 s = self.size + self.padding * 2
299 if x > s * 2:
300 return None
301 return int(x > s) + lower
303 if gtk.pygtk_version < (2, 8, 0):
304 # Note sure exactly which versions need this.
305 # 2.8.0 gives a warning if you include it, though.
306 gobject.type_register(ActionsRenderer)