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