Added "Show Cache" button to "0desktop --manage" window.
[zeroinstall/zeroinstall-rsl.git] / zeroinstall / gtkui / applistbox.py
blob27dd0743501de1fb44198deecaf9eb9523dc779f
1 """A GTK dialog which displays a list of Zero Install applications in the menu."""
2 # Copyright (C) 2008, Thomas Leonard
3 # See the README file for details, or visit http://0install.net.
5 import os
6 import gtk, gobject
7 import gtk.glade
8 import subprocess
10 from zeroinstall.gtkui import icon, xdgutils, treetips
12 def _pango_escape(s):
13 return s.replace('&', '&amp;').replace('<', '&lt;')
15 class AppList:
16 """A list of applications which can be displayed in an L{AppListBox}.
17 For example, a program might implement this to display a list of plugins.
18 This default implementation lists applications in the freedesktop.org menus.
19 """
20 def get_apps(self):
21 """Return a list of application URIs."""
22 self.apps = xdgutils.discover_existing_apps()
23 return self.apps.keys()
25 def remove_app(self, uri):
26 """Remove this application from the list."""
27 path = self.apps[uri]
28 os.unlink(path)
30 _tooltips = {
31 0: "Run the application",
32 1: "Show documentation files",
33 2: "Upgrade or change versions",
34 3: "Remove launcher from the menu",
37 class AppListBox:
38 """A dialog box which lists applications already added to the menus."""
39 ICON, URI, NAME, MARKUP = range(4)
41 def __init__(self, iface_cache, app_list):
42 """Constructor.
43 @param iface_cache: used to find extra information about programs
44 @type iface_cache: L{zeroinstall.injector.iface_cache.IfaceCache}
45 @param app_list: used to list or remove applications
46 @type app_list: L{AppList}
47 """
48 gladefile = os.path.join(os.path.dirname(__file__), 'desktop.glade')
49 self.iface_cache = iface_cache
50 self.app_list = app_list
52 widgets = gtk.glade.XML(gladefile, 'applist')
53 self.window = widgets.get_widget('applist')
54 tv = widgets.get_widget('treeview')
56 self.model = gtk.ListStore(gtk.gdk.Pixbuf, str, str, str)
58 self.populate_model()
59 tv.set_model(self.model)
60 tv.get_selection().set_mode(gtk.SELECTION_NONE)
62 cell_icon = gtk.CellRendererPixbuf()
63 cell_icon.set_property('xpad', 4)
64 cell_icon.set_property('ypad', 4)
65 column = gtk.TreeViewColumn('Icon', cell_icon, pixbuf = AppListBox.ICON)
66 tv.append_column(column)
68 cell_text = gtk.CellRendererText()
69 column = gtk.TreeViewColumn('Name', cell_text, markup = AppListBox.MARKUP)
70 tv.append_column(column)
72 cell_actions = ActionsRenderer(self, tv)
73 actions_column = gtk.TreeViewColumn('Actions', cell_actions, uri = AppListBox.URI)
74 tv.append_column(actions_column)
76 def redraw_actions(path):
77 if path is not None:
78 area = tv.get_cell_area(path, actions_column)
79 tv.queue_draw_area(*area)
81 tips = treetips.TreeTips()
82 def motion(widget, mev):
83 if mev.window == tv.get_bin_window():
84 new_hover = (None, None, None)
85 pos = tv.get_path_at_pos(int(mev.x), int(mev.y))
86 if pos:
87 path, col, x, y = pos
88 if col == actions_column:
89 area = tv.get_cell_area(path, col)
90 iface = self.model[path][AppListBox.URI]
91 action = cell_actions.get_action(area, x, y)
92 if action is not None:
93 new_hover = (path, iface, action)
94 if new_hover != cell_actions.hover:
95 redraw_actions(cell_actions.hover[0])
96 cell_actions.hover = new_hover
97 redraw_actions(cell_actions.hover[0])
98 tips.prime(tv, _tooltips.get(cell_actions.hover[2], None))
99 tv.connect('motion-notify-event', motion)
101 def leave(widget, lev):
102 redraw_actions(cell_actions.hover[0])
103 cell_actions.hover = (None, None, None)
104 tips.hide()
106 tv.connect('leave-notify-event', leave)
108 self.model.set_sort_column_id(AppListBox.NAME, gtk.SORT_ASCENDING)
110 show_cache = widgets.get_widget('show_cache')
111 self.window.action_area.set_child_secondary(show_cache, True)
113 def response(box, resp):
114 if resp == 0:
115 subprocess.Popen(['0store', 'manage'])
116 else:
117 box.destroy()
118 self.window.connect('response', response)
120 def populate_model(self):
121 model = self.model
122 model.clear()
124 for uri in self.app_list.get_apps():
125 itr = model.append()
126 model[itr][AppListBox.URI] = uri
128 iface = self.iface_cache.get_interface(uri)
129 name = iface.get_name()
130 summary = iface.summary or 'No information available'
131 summary = summary[:1].capitalize() + summary[1:]
133 model[itr][AppListBox.NAME] = name
134 pixbuf = icon.load_icon(self.iface_cache.get_icon_path(iface))
135 if not pixbuf:
136 pixbuf = self.window.render_icon(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_DIALOG)
137 model[itr][AppListBox.ICON] = pixbuf
139 model[itr][AppListBox.MARKUP] = '<b>%s</b>\n<i>%s</i>' % (_pango_escape(name), _pango_escape(summary))
141 def action_run(self, uri):
142 subprocess.Popen(['0launch', '--', uri])
144 def action_help(self, uri):
145 from zeroinstall.injector import policy, reader, model
146 p = policy.Policy(uri)
147 policy.network_use = model.network_offline
148 if p.need_download():
149 child = subprocess.Popen(['0launch', '-d', '--', uri])
150 child.wait()
151 if child.returncode:
152 return
153 iface = self.iface_cache.get_interface(uri)
154 reader.update_from_cache(iface)
155 p.solve_with_downloads()
156 impl = p.solver.selections[iface]
157 assert impl, "Failed to choose an implementation of " + uri
158 help_dir = impl.metadata.get('doc-dir')
159 path = p.get_implementation_path(impl)
160 assert path, "Chosen implementation is not cached!"
161 if help_dir:
162 path = os.path.join(path, help_dir)
163 else:
164 main = impl.main
165 if main:
166 # Hack for ROX applications. They should be updated to
167 # set doc-dir.
168 help_dir = os.path.join(path, os.path.dirname(main), 'Help')
169 if os.path.isdir(help_dir):
170 path = help_dir
172 # xdg-open has no "safe" mode, so check we're not "opening" an application.
173 if os.path.exists(os.path.join(path, 'AppRun')):
174 raise Exception("Documentation directory '%s' is an AppDir; refusing to open" % path)
176 subprocess.Popen(['xdg-open', path])
178 def action_properties(self, uri):
179 subprocess.Popen(['0launch', '--gui', '--', uri])
181 def action_remove(self, uri):
182 name = self.iface_cache.get_interface(uri).get_name()
184 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL, "")
185 box.set_markup("Remove <b>%s</b> from the menu?" % _pango_escape(name))
186 box.add_button(gtk.STOCK_DELETE, gtk.RESPONSE_OK)
187 box.set_default_response(gtk.RESPONSE_OK)
188 resp = box.run()
189 box.destroy()
190 if resp == gtk.RESPONSE_OK:
191 try:
192 self.app_list.remove_app(uri)
193 except Exception, ex:
194 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Failed to remove %s: %s" % (name, ex))
195 box.run()
196 box.destroy()
197 self.populate_model()
199 class ActionsRenderer(gtk.GenericCellRenderer):
200 __gproperties__ = {
201 "uri": (gobject.TYPE_STRING, "Text", "Text", "-", gobject.PARAM_READWRITE),
204 def __init__(self, applist, widget):
205 "@param widget: widget used for style information"
206 gtk.GenericCellRenderer.__init__(self)
207 self.set_property('mode', gtk.CELL_RENDERER_MODE_ACTIVATABLE)
208 self.padding = 4
210 self.applist = applist
212 self.size = 10
213 def stock_lookup(name):
214 pixbuf = widget.render_icon(name, gtk.ICON_SIZE_BUTTON)
215 self.size = max(self.size, pixbuf.get_width(), pixbuf.get_height())
216 return pixbuf
218 if hasattr(gtk, 'STOCK_MEDIA_PLAY'):
219 self.run = stock_lookup(gtk.STOCK_MEDIA_PLAY)
220 else:
221 self.run = stock_lookup(gtk.STOCK_YES)
222 self.help = stock_lookup(gtk.STOCK_HELP)
223 self.properties = stock_lookup(gtk.STOCK_PROPERTIES)
224 self.remove = stock_lookup(gtk.STOCK_DELETE)
225 self.hover = (None, None, None) # Path, URI, action
227 def do_set_property(self, prop, value):
228 setattr(self, prop.name, value)
230 def on_get_size(self, widget, cell_area, layout = None):
231 total_size = self.size * 2 + self.padding * 4
232 return (0, 0, total_size, total_size)
234 def on_render(self, window, widget, background_area, cell_area, expose_area, flags):
235 hovering = self.uri == self.hover[1]
237 s = self.size
239 cx = cell_area.x + self.padding
240 cy = cell_area.y + (cell_area.height / 2) - s - self.padding
242 ss = s + self.padding * 2
244 b = 0
245 for (x, y), icon in [((0, 0), self.run),
246 ((ss, 0), self.help),
247 ((0, ss), self.properties),
248 ((ss, ss), self.remove)]:
249 if hovering and b == self.hover[2]:
250 widget.style.paint_box(window, gtk.STATE_NORMAL, gtk.SHADOW_OUT,
251 expose_area, widget, None,
252 cx + x - 2, cy + y - 2, s + 4, s + 4)
254 window.draw_pixbuf(widget.style.white_gc, icon,
255 0, 0, # Source x,y
256 cx + x, cy + y)
257 b += 1
259 def on_activate(self, event, widget, path, background_area, cell_area, flags):
260 if event.type != gtk.gdk.BUTTON_PRESS:
261 return False
262 action = self.get_action(cell_area, event.x - cell_area.x, event.y - cell_area.y)
263 if action == 0:
264 self.applist.action_run(self.uri)
265 elif action == 1:
266 self.applist.action_help(self.uri)
267 elif action == 2:
268 self.applist.action_properties(self.uri)
269 elif action == 3:
270 self.applist.action_remove(self.uri)
272 def get_action(self, area, x, y):
273 lower = int(y > (area.height / 2)) * 2
275 s = self.size + self.padding * 2
276 if x > s * 2:
277 return None
278 return int(x > s) + lower
280 if gtk.pygtk_version < (2, 8, 0):
281 # Note sure exactly which versions need this.
282 # 2.8.0 gives a warning if you include it, though.
283 gobject.type_register(ActionsRenderer)