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