Split AppList out from AppListBox
[zeroinstall/zeroinstall-mseaborn.git] / zeroinstall / gtkui / applistbox.py
blob602007f9b37825422ff46536d8e52a5543bae9ec
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
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 class AppListBox:
31 """A dialog box which lists applications already added to the menus."""
32 ICON, URI, NAME, MARKUP = range(4)
34 def __init__(self, iface_cache, app_list):
35 """Constructor.
36 @param iface_cache: used to find extra information about programs
37 @type iface_cache: L{zeroinstall.injector.iface_cache.IfaceCache}
38 @param app_list: used to list or remove applications
39 @type app_list: L{AppList}
40 """
41 gladefile = os.path.join(os.path.dirname(__file__), 'desktop.glade')
42 self.iface_cache = iface_cache
43 self.app_list = app_list
45 widgets = gtk.glade.XML(gladefile, 'applist')
46 self.window = widgets.get_widget('applist')
47 tv = widgets.get_widget('treeview')
49 self.model = gtk.ListStore(gtk.gdk.Pixbuf, str, str, str)
51 self.populate_model()
52 tv.set_model(self.model)
53 tv.get_selection().set_mode(gtk.SELECTION_NONE)
55 cell_icon = gtk.CellRendererPixbuf()
56 cell_icon.set_property('xpad', 4)
57 cell_icon.set_property('ypad', 4)
58 column = gtk.TreeViewColumn('Icon', cell_icon, pixbuf = AppListBox.ICON)
59 tv.append_column(column)
61 cell_text = gtk.CellRendererText()
62 column = gtk.TreeViewColumn('Name', cell_text, markup = AppListBox.MARKUP)
63 tv.append_column(column)
65 cell_actions = ActionsRenderer(self, tv)
66 actions_column = gtk.TreeViewColumn('Actions', cell_actions, uri = AppListBox.URI)
67 tv.append_column(actions_column)
69 def redraw_actions(path):
70 if path is not None:
71 area = tv.get_cell_area(path, actions_column)
72 tv.queue_draw_area(*area)
74 def motion(widget, mev):
75 if mev.window == tv.get_bin_window():
76 new_hover = (None, None, None)
77 pos = tv.get_path_at_pos(int(mev.x), int(mev.y))
78 if pos:
79 path, col, x, y = pos
80 if col == actions_column:
81 area = tv.get_cell_area(path, col)
82 iface = self.model[path][AppListBox.URI]
83 action = cell_actions.get_action(area, x, y)
84 if action is not None:
85 new_hover = (path, iface, action)
86 if new_hover != cell_actions.hover:
87 redraw_actions(cell_actions.hover[0])
88 cell_actions.hover = new_hover
89 redraw_actions(cell_actions.hover[0])
90 tv.connect('motion-notify-event', motion)
92 def leave(widget, lev):
93 redraw_actions(cell_actions.hover[0])
94 cell_actions.hover = (None, None, None)
96 tv.connect('leave-notify-event', leave)
98 self.model.set_sort_column_id(AppListBox.NAME, gtk.SORT_ASCENDING)
100 def response(box, resp):
101 box.destroy()
102 self.window.connect('response', response)
104 def populate_model(self):
105 model = self.model
106 model.clear()
108 for uri in self.app_list.get_apps():
109 itr = model.append()
110 model[itr][AppListBox.URI] = uri
112 iface = self.iface_cache.get_interface(uri)
113 name = iface.get_name()
114 summary = iface.summary or 'No information available'
115 summary = summary[:1].capitalize() + summary[1:]
117 model[itr][AppListBox.NAME] = name
118 pixbuf = icon.load_icon(self.iface_cache.get_icon_path(iface))
119 if not pixbuf:
120 pixbuf = self.window.render_icon(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_DIALOG)
121 model[itr][AppListBox.ICON] = pixbuf
123 model[itr][AppListBox.MARKUP] = '<b>%s</b>\n<i>%s</i>' % (_pango_escape(name), _pango_escape(summary))
125 def action_run(self, uri):
126 subprocess.Popen(['0launch', '--', uri])
128 def action_help(self, uri):
129 from zeroinstall.injector import policy, reader, model
130 p = policy.Policy(uri)
131 policy.network_use = model.network_offline
132 if p.need_download():
133 child = subprocess.Popen(['0launch', '-d', '--', uri])
134 child.wait()
135 if child.returncode:
136 return
137 iface = self.iface_cache.get_interface(uri)
138 reader.update_from_cache(iface)
139 p.solve_with_downloads()
140 impl = p.solver.selections[iface]
141 assert impl, "Failed to choose an implementation of " + uri
142 help_dir = impl.metadata.get('doc-dir')
143 path = p.get_implementation_path(impl)
144 assert path, "Chosen implementation is not cached!"
145 if help_dir:
146 path = os.path.join(path, help_dir)
147 subprocess.Popen(['xdg-open', path])
149 def action_properties(self, uri):
150 subprocess.Popen(['0launch', '--gui', '--', uri])
152 def action_remove(self, uri):
153 name = self.iface_cache.get_interface(uri).get_name()
155 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL, "")
156 box.set_markup("Remove <b>%s</b> from the menu?" % _pango_escape(name))
157 box.add_button(gtk.STOCK_DELETE, gtk.RESPONSE_OK)
158 box.set_default_response(gtk.RESPONSE_OK)
159 resp = box.run()
160 box.destroy()
161 if resp == gtk.RESPONSE_OK:
162 try:
163 self.app_list.remove_app(uri)
164 except Exception, ex:
165 box = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Failed to remove %s: %s" % (name, ex))
166 box.run()
167 box.destroy()
168 self.populate_model()
170 class ActionsRenderer(gtk.GenericCellRenderer):
171 __gproperties__ = {
172 "uri": (gobject.TYPE_STRING, "Text", "Text", "-", gobject.PARAM_READWRITE),
175 def __init__(self, applist, widget):
176 "@param widget: widget used for style information"
177 gtk.GenericCellRenderer.__init__(self)
178 self.set_property('mode', gtk.CELL_RENDERER_MODE_ACTIVATABLE)
179 self.padding = 4
181 self.applist = applist
183 self.size = 10
184 def stock_lookup(name):
185 pixbuf = widget.render_icon(name, gtk.ICON_SIZE_BUTTON)
186 self.size = max(self.size, pixbuf.get_width(), pixbuf.get_height())
187 return pixbuf
189 if hasattr(gtk, 'STOCK_MEDIA_PLAY'):
190 self.run = stock_lookup(gtk.STOCK_MEDIA_PLAY)
191 else:
192 self.run = stock_lookup(gtk.STOCK_YES)
193 self.help = stock_lookup(gtk.STOCK_HELP)
194 self.properties = stock_lookup(gtk.STOCK_PROPERTIES)
195 self.remove = stock_lookup(gtk.STOCK_DELETE)
196 self.hover = (None, None, None) # Path, URI, action
198 def do_set_property(self, prop, value):
199 setattr(self, prop.name, value)
201 def on_get_size(self, widget, cell_area, layout = None):
202 total_size = self.size * 2 + self.padding * 4
203 return (0, 0, total_size, total_size)
205 def on_render(self, window, widget, background_area, cell_area, expose_area, flags):
206 hovering = self.uri == self.hover[1]
208 s = self.size
210 cx = cell_area.x + self.padding
211 cy = cell_area.y + (cell_area.height / 2) - s - self.padding
213 ss = s + self.padding * 2
215 b = 0
216 for (x, y), icon in [((0, 0), self.run),
217 ((ss, 0), self.help),
218 ((0, ss), self.properties),
219 ((ss, ss), self.remove)]:
220 if hovering and b == self.hover[2]:
221 widget.style.paint_box(window, gtk.STATE_NORMAL, gtk.SHADOW_OUT,
222 expose_area, widget, None,
223 cx + x - 2, cy + y - 2, s + 4, s + 4)
225 window.draw_pixbuf(widget.style.white_gc, icon,
226 0, 0, # Source x,y
227 cx + x, cy + y)
228 b += 1
230 def on_activate(self, event, widget, path, background_area, cell_area, flags):
231 if event.type != gtk.gdk.BUTTON_PRESS:
232 return False
233 action = self.get_action(cell_area, event.x - cell_area.x, event.y - cell_area.y)
234 if action == 0:
235 self.applist.action_run(self.uri)
236 elif action == 1:
237 self.applist.action_help(self.uri)
238 elif action == 2:
239 self.applist.action_properties(self.uri)
240 elif action == 3:
241 self.applist.action_remove(self.uri)
243 def get_action(self, area, x, y):
244 lower = int(y > (area.height / 2)) * 2
246 s = self.size + self.padding * 2
247 if x > s * 2:
248 return None
249 return int(x > s) + lower
251 if gtk.pygtk_version < (2, 8, 0):
252 # Note sure exactly which versions need this.
253 # 2.8.0 gives a warning if you include it, though.
254 gobject.type_register(ActionsRenderer)