Large-scale API cleanup
[zeroinstall/zeroinstall-afb.git] / zeroinstall / 0launch-gui / properties.py
blob2f93af0d309df026433c5dcecf05cec1ceb2ecd0
1 # Copyright (C) 2009, Thomas Leonard
2 # See the README file for details, or visit http://0install.net.
4 import zeroinstall
5 import os
6 from zeroinstall.support import tasks
7 from zeroinstall.injector.model import Interface, Feed, stable, testing, developer, stability_levels
8 from zeroinstall.injector import writer, namespaces, gpg
9 from zeroinstall.gtkui import help_box
11 import gtk
12 from logging import warn
14 from dialog import DialogResponse, Template
15 from impl_list import ImplementationList
16 import time
17 import dialog
19 _dialogs = {} # Interface -> Properties
21 def enumerate(items):
22 x = 0
23 for i in items:
24 yield x, i
25 x += 1
27 def format_para(para):
28 lines = [l.strip() for l in para.split('\n')]
29 return ' '.join(lines)
31 def have_source_for(policy, interface):
32 iface_cache = policy.config.iface_cache
33 # Note: we don't want to actually fetch the source interfaces at
34 # this point, so we check whether:
35 # - We have a feed of type 'src' (not fetched), or
36 # - We have a source implementation in a regular feed
37 for f in iface_cache.get_feed_imports(interface):
38 if f.machine == 'src':
39 return True
40 # Don't have any src feeds. Do we have a source implementation
41 # as part of a regular feed?
42 for x in iface_cache.get_implementations(interface):
43 if x.machine == 'src':
44 return True
45 return False
47 class Description:
48 def __init__(self, widgets):
49 description = widgets.get_widget('description')
50 description.connect('button-press-event', self.button_press)
52 self.buffer = description.get_buffer()
53 self.heading_style = self.buffer.create_tag(underline = True, scale = 1.2)
54 self.link_style = self.buffer.create_tag(underline = True, foreground = 'blue')
55 description.set_size_request(-1, 100)
57 def button_press(self, tv, bev):
58 if bev.type == gtk.gdk.BUTTON_PRESS and bev.button == 1:
59 x, y = tv.window_to_buffer_coords(tv.get_window_type(bev.window),
60 int(bev.x), int(bev.y))
61 itr = tv.get_iter_at_location(x, y)
62 if itr and self.link_style in itr.get_tags():
63 if not itr.begins_tag(self.link_style):
64 itr.backward_to_tag_toggle(self.link_style)
65 end = itr.copy()
66 end.forward_to_tag_toggle(self.link_style)
67 target = itr.get_text(end).strip()
68 import browser
69 browser.open_in_browser(target)
71 def strtime(self, secs):
72 try:
73 from locale import nl_langinfo, D_T_FMT
74 return time.strftime(nl_langinfo(D_T_FMT), time.localtime(secs))
75 except (ImportError, ValueError):
76 return time.ctime(secs)
78 def set_details(self, iface_cache, feed):
79 buffer = self.buffer
80 heading_style = self.heading_style
82 buffer.delete(buffer.get_start_iter(), buffer.get_end_iter())
84 iter = buffer.get_start_iter()
86 if feed is None:
87 buffer.insert(iter, 'Not yet downloaded.')
88 return
90 if isinstance(feed, Exception):
91 buffer.insert(iter, unicode(feed))
92 return
94 buffer.insert_with_tags(iter,
95 '%s ' % feed.get_name(), heading_style)
96 buffer.insert(iter, '(%s)' % feed.summary)
98 buffer.insert(iter, '\n%s\n' % feed.url)
100 # (converts to local time)
101 if feed.last_modified:
102 buffer.insert(iter, '\n' + _('Last upstream change: %s') % self.strtime(feed.last_modified))
104 if feed.last_checked:
105 buffer.insert(iter, '\n' + _('Last checked: %s') % self.strtime(feed.last_checked))
107 last_check_attempt = iface_cache.get_last_check_attempt(feed.url)
108 if last_check_attempt:
109 if feed.last_checked and feed.last_checked >= last_check_attempt:
110 pass # Don't bother reporting successful attempts
111 else:
112 buffer.insert(iter, '\n' + _('Last check attempt: %s (failed or in progress)') %
113 self.strtime(last_check_attempt))
115 buffer.insert_with_tags(iter, '\n\n' + _('Description') + '\n', heading_style)
117 paragraphs = [format_para(p) for p in (feed.description or "-").split('\n\n')]
119 buffer.insert(iter, '\n\n'.join(paragraphs))
120 buffer.insert(iter, '\n')
122 need_gap = True
123 for x in feed.get_metadata(namespaces.XMLNS_IFACE, 'homepage'):
124 if need_gap:
125 buffer.insert(iter, '\n')
126 need_gap = False
127 buffer.insert(iter, _('Homepage: '))
128 buffer.insert_with_tags(iter, '%s\n' % x.content, self.link_style)
130 buffer.insert_with_tags(iter, '\n' + _('Signatures') + '\n', heading_style)
131 sigs = iface_cache.get_cached_signatures(feed.url)
132 if sigs:
133 for sig in sigs:
134 if isinstance(sig, gpg.ValidSig):
135 name = _('<unknown>')
136 details = sig.get_details()
137 for item in details:
138 if item[0] == 'uid' and len(item) > 9:
139 name = item[9]
140 break
141 buffer.insert_with_tags(iter, _('Valid signature by "%(name)s"\n- Dated: %(sig_date)s\n- Fingerprint: %(sig_fingerprint)s\n') %
142 {'name': name, 'sig_date': time.strftime('%c', time.localtime(sig.get_timestamp())), 'sig_fingerprint': sig.fingerprint})
143 if not sig.is_trusted():
144 if os.path.isabs(feed.url):
145 buffer.insert_with_tags(iter, _('WARNING: This key is not in the trusted list') + '\n')
146 else:
147 buffer.insert_with_tags(iter, _('WARNING: This key is not in the trusted list (either you removed it, or '
148 'you trust one of the other signatures)') + '\n')
149 else:
150 buffer.insert_with_tags(iter, '%s\n' % sig)
151 else:
152 buffer.insert_with_tags(iter, _('No signature information (old style feed or out-of-date cache)') + '\n')
154 class Feeds:
155 URI = 0
156 ARCH = 1
157 USED = 2
159 def __init__(self, policy, interface, widgets):
160 self.policy = policy
161 self.interface = interface
163 self.model = gtk.ListStore(str, str, bool)
165 self.description = Description(widgets)
167 self.lines = self.build_model()
168 for line in self.lines:
169 self.model.append(line)
171 add_remote_feed_button = widgets.get_widget('add_remote_feed')
172 add_remote_feed_button.connect('clicked', lambda b: add_remote_feed(policy, widgets.get_widget(), interface))
174 add_local_feed_button = widgets.get_widget('add_local_feed')
175 add_local_feed_button.connect('clicked', lambda b: add_local_feed(policy, interface))
177 self.remove_feed_button = widgets.get_widget('remove_feed')
178 def remove_feed(button):
179 model, iter = self.tv.get_selection().get_selected()
180 feed_uri = model[iter][Feeds.URI]
181 for x in interface.extra_feeds:
182 if x.uri == feed_uri:
183 if x.user_override:
184 interface.extra_feeds.remove(x)
185 writer.save_interface(interface)
186 import main
187 main.recalculate()
188 return
189 else:
190 dialog.alert(self.get_toplevel(),
191 _("Can't remove '%s' as you didn't add it.") % feed_uri)
192 return
193 raise Exception(_("Missing feed '%s'!") % feed_uri)
194 self.remove_feed_button.connect('clicked', remove_feed)
196 self.tv = widgets.get_widget('feeds_list')
197 self.tv.set_model(self.model)
198 text = gtk.CellRendererText()
199 self.tv.append_column(gtk.TreeViewColumn(_('Source'), text, text = Feeds.URI, sensitive = Feeds.USED))
200 self.tv.append_column(gtk.TreeViewColumn(_('Arch'), text, text = Feeds.ARCH, sensitive = Feeds.USED))
202 sel = self.tv.get_selection()
203 sel.set_mode(gtk.SELECTION_BROWSE)
204 sel.connect('changed', self.sel_changed)
205 sel.select_path((0,))
207 def build_model(self):
208 iface_cache = self.policy.config.iface_cache
210 usable_feeds = frozenset(self.policy.usable_feeds(self.interface))
211 unusable_feeds = frozenset(iface_cache.get_feed_imports(self.interface)) - usable_feeds
213 out = [[self.interface.uri, None, True]]
215 for feed in usable_feeds:
216 out.append([feed.uri, feed.arch, True])
217 for feed in unusable_feeds:
218 out.append([feed.uri, feed.arch, False])
219 return out
221 def sel_changed(self, sel):
222 iface_cache = self.policy.config.iface_cache
224 model, miter = sel.get_selected()
225 if not miter: return # build in progress
226 feed_url = model[miter][Feeds.URI]
227 # Only enable removing user_override feeds
228 enable_remove = False
229 for x in self.interface.extra_feeds:
230 if x.uri == feed_url:
231 if x.user_override:
232 enable_remove = True
233 self.remove_feed_button.set_sensitive( enable_remove )
234 try:
235 self.description.set_details(iface_cache, iface_cache.get_feed(feed_url))
236 except zeroinstall.SafeException, ex:
237 self.description.set_details(iface_cache, ex)
239 def updated(self):
240 new_lines = self.build_model()
241 if new_lines != self.lines:
242 self.lines = new_lines
243 self.model.clear()
244 for line in self.lines:
245 self.model.append(line)
246 self.tv.get_selection().select_path((0,))
247 else:
248 self.sel_changed(self.tv.get_selection())
250 class Properties:
251 interface = None
252 use_list = None
253 window = None
254 policy = None
256 def __init__(self, policy, interface, compile, show_versions = False):
257 self.policy = policy
259 widgets = Template('interface_properties')
261 self.interface = interface
263 window = widgets.get_widget('interface_properties')
264 self.window = window
265 window.set_title(_('Properties for %s') % interface.get_name())
266 window.set_default_size(-1, gtk.gdk.screen_height() / 3)
268 self.compile_button = widgets.get_widget('compile')
269 self.compile_button.connect('clicked', lambda b: compile(interface))
270 window.set_default_response(gtk.RESPONSE_CANCEL)
272 def response(dialog, resp):
273 if resp == gtk.RESPONSE_CANCEL:
274 window.destroy()
275 elif resp == gtk.RESPONSE_HELP:
276 properties_help.display()
277 window.connect('response', response)
279 notebook = widgets.get_widget('interface_notebook')
280 assert notebook
282 feeds = Feeds(policy, interface, widgets)
284 stability = widgets.get_widget('preferred_stability')
285 stability.set_active(0)
286 if interface.stability_policy:
287 i = [stable, testing, developer].index(interface.stability_policy)
288 i += 1
289 if i == 0:
290 warn(_("Unknown stability policy %s"), interface.stability_policy)
291 else:
292 i = 0
293 stability.set_active(i)
295 def set_stability_policy(combo, stability = stability): # (pygtk bug?)
296 i = stability.get_active()
297 if i == 0:
298 new_stability = None
299 else:
300 name = ['stable', 'testing', 'developer'][i-1]
301 new_stability = stability_levels[name]
302 interface.set_stability_policy(new_stability)
303 writer.save_interface(interface)
304 import main
305 main.recalculate()
306 stability.connect('changed', set_stability_policy)
308 self.use_list = ImplementationList(policy, interface, widgets)
310 self.update_list()
312 feeds.tv.grab_focus()
314 def updated():
315 self.update_list()
316 feeds.updated()
317 self.shade_compile()
318 window.connect('destroy', lambda s: policy.watchers.remove(updated))
319 policy.watchers.append(updated)
320 self.shade_compile()
322 if show_versions:
323 notebook.next_page()
325 def show(self):
326 self.window.show()
328 def destroy(self):
329 self.window.destroy()
331 def shade_compile(self):
332 self.compile_button.set_sensitive(have_source_for(self.policy, self.interface))
334 def update_list(self):
335 ranked_items = self.policy.solver.details.get(self.interface, None)
336 if ranked_items is None:
337 # The Solver didn't get this far, but we should still display them!
338 ranked_items = [(impl, _("(solve aborted before here)"))
339 for impl in self.interface.implementations.values()]
340 # Always sort by version
341 ranked_items.sort()
342 self.use_list.set_items(ranked_items)
344 @tasks.async
345 def add_remote_feed(policy, parent, interface):
346 try:
347 iface_cache = policy.config.iface_cache
349 d = gtk.MessageDialog(parent, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL,
350 _('Enter the URL of the new source of implementations of this interface:'))
351 d.add_button(gtk.STOCK_ADD, gtk.RESPONSE_OK)
352 d.set_default_response(gtk.RESPONSE_OK)
353 entry = gtk.Entry()
355 align = gtk.VBox(False, 0)
356 align.set_border_width(4)
357 align.add(entry)
358 d.vbox.pack_start(align)
359 entry.set_activates_default(True)
361 entry.set_text('')
363 d.vbox.show_all()
365 error_label = gtk.Label('')
366 error_label.set_padding(4, 4)
367 align.pack_start(error_label)
369 d.show()
371 def error(message):
372 if message:
373 error_label.set_text(message)
374 error_label.show()
375 else:
376 error_label.hide()
378 while True:
379 got_response = DialogResponse(d)
380 yield got_response
381 tasks.check(got_response)
382 resp = got_response.response
384 error(None)
385 if resp == gtk.RESPONSE_OK:
386 try:
387 url = entry.get_text()
388 if not url:
389 raise zeroinstall.SafeException(_('Enter a URL'))
390 fetch = policy.fetcher.download_and_import_feed(url, iface_cache)
391 if fetch:
392 d.set_sensitive(False)
393 yield fetch
394 d.set_sensitive(True)
395 tasks.check(fetch)
397 iface = iface_cache.get_interface(url)
399 d.set_sensitive(True)
400 if not iface.name:
401 error(_('Failed to read interface'))
402 return
403 if not iface.feed_for:
404 error(_("Feed '%(feed)s' is not a feed for '%(feed_for)s'.") % {'feed': iface.get_name(), 'feed_for': interface.get_name()})
405 elif interface.uri not in iface.feed_for:
406 error(_("This is not a feed for '%(uri)s'.\nOnly for:\n%(feed_for)s") %
407 {'uri': interface.uri, 'feed_for': '\n'.join(iface.feed_for)})
408 elif iface.uri in [f.uri for f in interface.extra_feeds]:
409 error(_("Feed from '%s' has already been added!") % iface.uri)
410 else:
411 interface.extra_feeds.append(Feed(iface.uri, arch = None, user_override = True))
412 writer.save_interface(interface)
413 d.destroy()
414 import main
415 main.recalculate()
416 except zeroinstall.SafeException, ex:
417 error(str(ex))
418 else:
419 d.destroy()
420 return
421 except Exception, ex:
422 import traceback
423 traceback.print_exc()
424 policy.handler.report_error(ex)
426 def add_local_feed(policy, interface):
427 chooser = gtk.FileChooserDialog(_('Select XML feed file'), action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
428 def ok(feed):
429 from zeroinstall.injector import reader
430 try:
431 feed_targets = policy.get_feed_targets(feed)
432 if interface not in feed_targets:
433 raise Exception(_("Not a valid feed for '%(uri)s'; this is a feed for:\n%(feed_for)s") %
434 {'uri': interface.uri,
435 'feed_for': '\n'.join([f.uri for f in feed_targets])})
436 if feed in [f.uri for f in interface.extra_feeds]:
437 dialog.alert(None, _('This feed is already registered.'))
438 else:
439 interface.extra_feeds.append(Feed(feed, user_override = True, arch = None))
441 writer.save_interface(interface)
442 chooser.destroy()
443 reader.update_from_cache(interface)
444 import main
445 main.recalculate()
446 except Exception, ex:
447 dialog.alert(None, _("Error in feed file '%(feed)s':\n\n%(exception)s") % {'feed': feed, 'exception': str(ex)})
449 def check_response(widget, response):
450 if response == gtk.RESPONSE_OK:
451 ok(widget.get_filename())
452 elif response == gtk.RESPONSE_CANCEL:
453 widget.destroy()
455 chooser.connect('response', check_response)
456 chooser.show()
458 def edit(policy, interface, compile, show_versions = False):
459 assert isinstance(interface, Interface)
460 if interface in _dialogs:
461 _dialogs[interface].destroy()
462 _dialogs[interface] = Properties(policy, interface, compile, show_versions = show_versions)
463 _dialogs[interface].show()
465 properties_help = help_box.HelpBox(_("Injector Properties Help"),
466 (_('Interface properties'), '\n' +
467 _("""This window displays information about an interface. There are two tabs at the top: \
468 Feeds shows the places where the injector looks for implementations of the interface, while \
469 Versions shows the list of implementations found (from all feeds) in order of preference.""")),
471 (_('The Feeds tab'), '\n' +
472 _("""At the top is a list of feeds. By default, the injector uses the full name of the interface \
473 as the default feed location (so if you ask it to run the program "http://foo/bar.xml" then it will \
474 by default get the list of versions by downloading "http://foo/bar.xml".
476 You can add and remove feeds using the buttons on the right. The main feed may also add \
477 some extra feeds itself. If you've checked out a developer version of a program, you can use \
478 the 'Add Local Feed...' button to let the injector know about it, for example.
480 Below the list of feeds is a box describing the selected one:
482 - At the top is its short name.
483 - Below that is the address (a URL or filename).
484 - 'Last upstream change' shows the version of the cached copy of the interface file.
485 - 'Last checked' is the last time a fresh copy of the upstream interface file was \
486 downloaded.
487 - Then there is a longer description of the interface.""")),
489 (_('The Versions tab'), '\n' +
490 _("""This tab shows a list of all known implementations of the interface, from all the feeds. \
491 The columns have the following meanings:
493 Version gives the version number. High-numbered versions are considered to be \
494 better than low-numbered ones.
496 Released gives the date this entry was added to the feed.
498 Stability is 'stable' if the implementation is believed to be stable, 'buggy' if \
499 it is known to contain serious bugs, and 'testing' if its stability is not yet \
500 known. This information is normally supplied and updated by the author of the \
501 software, but you can override their rating by right-clicking here (overridden \
502 values are shown in upper-case). You can also use the special level 'preferred'.
504 Fetch indicates how much data needs to be downloaded to get this version if you don't \
505 have it. If the implementation has already been downloaded to your computer, \
506 it will say (cached). (local) means that you installed this version manually and \
507 told Zero Install about it by adding a feed. (package) means that this version \
508 is provided by your distribution's package manager, not by Zero Install. \
509 In off-line mode, only cached implementations are considered for use.
511 Arch indicates what kind of computer system the implementation is for, or 'any' \
512 if it works with all types of system.""") + '\n'),
513 (_('Sort order'), '\n' +
514 _("""The implementations are ordered by version number (highest first), with the \
515 currently selected one in bold. This is the "best" usable version.
517 Unusable ones are those for incompatible \
518 architectures, those marked as 'buggy' or 'insecure', versions explicitly marked as incompatible with \
519 another interface you are using and, in off-line mode, uncached implementations. Unusable \
520 implementations are shown crossed out.
522 For the usable implementations, the order is as follows:
524 - Preferred implementations come first.
526 - Then, if network use is set to 'Minimal', cached implementations come before \
527 non-cached.
529 - Then, implementations at or above the selected stability level come before all others.
531 - Then, higher-numbered versions come before low-numbered ones.
533 - Then cached come before non-cached (for 'Full' network use mode).""") + '\n'),
535 (_('Compiling'), '\n' +
536 _("""If there is no binary available for your system then you may be able to compile one from \
537 source by clicking on the Compile button. If no source is available, the Compile button will \
538 be shown shaded.""") + '\n'))