Fix bug that made user selected per feed stability not work
[zeroinstall.git] / zeroinstall / 0launch-gui / properties.py
blob828931a8f2ca73baea08995a11185c51544ecf25
1 # Copyright (C) 2009, Thomas Leonard
2 # See the README file for details, or visit http://0install.net.
4 import zeroinstall
5 from zeroinstall.support import tasks
6 from zeroinstall.injector.model import Interface, Feed, stable, testing, developer, stability_levels
7 from zeroinstall.injector.iface_cache import iface_cache
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
18 import compile
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(policy, interface):
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 have_src = False
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, 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 buffer.insert_with_tags(iter,
92 '%s ' % feed.get_name(), heading_style)
93 buffer.insert(iter, '(%s)' % feed.summary)
95 buffer.insert(iter, '\n%s\n' % feed.url)
97 # (converts to local time)
98 if feed.last_modified:
99 buffer.insert(iter, '\n' + _('Last upstream change: %s') % self.strtime(feed.last_modified))
101 if feed.last_checked:
102 buffer.insert(iter, '\n' + _('Last checked: %s') % self.strtime(feed.last_checked))
104 last_check_attempt = iface_cache.get_last_check_attempt(feed.url)
105 if last_check_attempt:
106 if feed.last_checked and feed.last_checked >= last_check_attempt:
107 pass # Don't bother reporting successful attempts
108 else:
109 buffer.insert(iter, '\n' + _('Last check attempt: %s (failed or in progress)') %
110 self.strtime(last_check_attempt))
112 buffer.insert_with_tags(iter, '\n\n' + _('Description') + '\n', heading_style)
114 paragraphs = [format_para(p) for p in (feed.description or "-").split('\n\n')]
116 buffer.insert(iter, '\n\n'.join(paragraphs))
117 buffer.insert(iter, '\n')
119 need_gap = True
120 for x in feed.get_metadata(namespaces.XMLNS_IFACE, 'homepage'):
121 if need_gap:
122 buffer.insert(iter, '\n')
123 need_gap = False
124 buffer.insert(iter, _('Homepage: '))
125 buffer.insert_with_tags(iter, '%s\n' % x.content, self.link_style)
127 buffer.insert_with_tags(iter, '\n' + _('Signatures') + '\n', heading_style)
128 sigs = iface_cache.get_cached_signatures(feed.url)
129 if sigs:
130 for sig in sigs:
131 if isinstance(sig, gpg.ValidSig):
132 name = _('<unknown>')
133 details = sig.get_details()
134 for item in details:
135 if item[0] == 'uid' and len(item) > 9:
136 name = item[9]
137 break
138 buffer.insert_with_tags(iter, _('Valid signature by "%(name)s"\n- Dated: %(sig_date)s\n- Fingerprint: %(sig_fingerprint)s\n') %
139 {'name': name, 'sig_date': time.strftime('%c', time.localtime(sig.get_timestamp())), 'sig_fingerprint': sig.fingerprint})
140 if not sig.is_trusted():
141 if feed.url.startswith('/'):
142 buffer.insert_with_tags(iter, _('WARNING: This key is not in the trusted list') + '\n')
143 else:
144 buffer.insert_with_tags(iter, _('WARNING: This key is not in the trusted list (either you removed it, or '
145 'you trust one of the other signatures)') + '\n')
146 else:
147 buffer.insert_with_tags(iter, '%s\n' % sig)
148 else:
149 buffer.insert_with_tags(iter, _('No signature information (old style feed or out-of-date cache)') + '\n')
151 class Feeds:
152 URI = 0
153 ARCH = 1
154 USED = 2
156 def __init__(self, policy, interface, widgets):
157 self.policy = policy
158 self.interface = interface
160 self.model = gtk.ListStore(str, str, bool)
162 self.description = Description(widgets)
164 self.lines = self.build_model()
165 for line in self.lines:
166 self.model.append(line)
168 add_remote_feed_button = widgets.get_widget('add_remote_feed')
169 add_remote_feed_button.connect('clicked', lambda b: add_remote_feed(policy, widgets.get_widget(), interface))
171 add_local_feed_button = widgets.get_widget('add_local_feed')
172 add_local_feed_button.connect('clicked', lambda b: add_local_feed(policy, interface))
174 self.remove_feed_button = widgets.get_widget('remove_feed')
175 def remove_feed(button):
176 model, iter = self.tv.get_selection().get_selected()
177 feed_uri = model[iter][Feeds.URI]
178 for x in interface.extra_feeds:
179 if x.uri == feed_uri:
180 if x.user_override:
181 interface.extra_feeds.remove(x)
182 writer.save_interface(interface)
183 policy.recalculate()
184 return
185 else:
186 dialog.alert(self.get_toplevel(),
187 _("Can't remove '%s' as you didn't add it.") % feed_uri)
188 return
189 raise Exception(_("Missing feed '%s'!") % feed_uri)
190 self.remove_feed_button.connect('clicked', remove_feed)
192 self.tv = widgets.get_widget('feeds_list')
193 self.tv.set_model(self.model)
194 text = gtk.CellRendererText()
195 self.tv.append_column(gtk.TreeViewColumn(_('Source'), text, text = Feeds.URI, sensitive = Feeds.USED))
196 self.tv.append_column(gtk.TreeViewColumn(_('Arch'), text, text = Feeds.ARCH, sensitive = Feeds.USED))
198 sel = self.tv.get_selection()
199 sel.set_mode(gtk.SELECTION_BROWSE)
200 sel.connect('changed', self.sel_changed)
201 sel.select_path((0,))
203 def build_model(self):
204 usable_feeds = frozenset(self.policy.usable_feeds(self.interface))
205 unusable_feeds = frozenset(iface_cache.get_feed_imports(self.interface)) - usable_feeds
207 out = [[self.interface.uri, None, True]]
209 for feed in usable_feeds:
210 out.append([feed.uri, feed.arch, True])
211 for feed in unusable_feeds:
212 out.append([feed.uri, feed.arch, False])
213 return out
215 def sel_changed(self, sel):
216 model, miter = sel.get_selected()
217 if not miter: return # build in progress
218 feed_url = model[miter][Feeds.URI]
219 # Only enable removing user_override feeds
220 enable_remove = False
221 for x in self.interface.extra_feeds:
222 if x.uri == feed_url:
223 if x.user_override:
224 enable_remove = True
225 self.remove_feed_button.set_sensitive( enable_remove )
226 self.description.set_details(iface_cache.get_feed(feed_url))
228 def updated(self):
229 new_lines = self.build_model()
230 if new_lines != self.lines:
231 self.lines = new_lines
232 self.model.clear()
233 for line in self.lines:
234 self.model.append(line)
235 self.tv.get_selection().select_path((0,))
236 else:
237 self.sel_changed(self.tv.get_selection())
239 class Properties:
240 interface = None
241 use_list = None
242 window = None
243 policy = None
245 def __init__(self, policy, interface, show_versions = False):
246 self.policy = policy
248 widgets = Template('interface_properties')
250 self.interface = interface
252 window = widgets.get_widget('interface_properties')
253 self.window = window
254 window.set_title(_('Properties for %s') % interface.get_name())
255 window.set_default_size(-1, gtk.gdk.screen_height() / 3)
257 self.compile_button = widgets.get_widget('compile')
258 self.compile_button.connect('clicked', lambda b: compile.compile(policy, interface))
259 window.set_default_response(gtk.RESPONSE_CANCEL)
261 def response(dialog, resp):
262 if resp == gtk.RESPONSE_CANCEL:
263 window.destroy()
264 elif resp == gtk.RESPONSE_HELP:
265 properties_help.display()
266 window.connect('response', response)
268 notebook = widgets.get_widget('interface_notebook')
269 assert notebook
271 feeds = Feeds(policy, interface, widgets)
273 stability = widgets.get_widget('preferred_stability')
274 stability.set_active(0)
275 if interface.stability_policy:
276 i = [stable, testing, developer].index(interface.stability_policy)
277 i += 1
278 if i == 0:
279 warn(_("Unknown stability policy %s"), interface.stability_policy)
280 else:
281 i = 0
282 stability.set_active(i)
284 def set_stability_policy(combo):
285 i = stability.get_active()
286 if i == 0:
287 new_stability = None
288 else:
289 name = ['stable', 'testing', 'developer'][i-1]
290 new_stability = stability_levels[name]
291 interface.set_stability_policy(new_stability)
292 writer.save_interface(interface)
293 policy.recalculate()
294 stability.connect('changed', set_stability_policy)
296 self.use_list = ImplementationList(policy, interface, widgets)
298 self.update_list()
300 feeds.tv.grab_focus()
302 def updated():
303 self.update_list()
304 feeds.updated()
305 self.shade_compile()
306 window.connect('destroy', lambda s: policy.watchers.remove(updated))
307 policy.watchers.append(updated)
308 self.shade_compile()
310 if show_versions:
311 notebook.next_page()
313 def show(self):
314 self.window.show()
316 def destroy(self):
317 self.window.destroy()
319 def shade_compile(self):
320 self.compile_button.set_sensitive(have_source_for(self.policy, self.interface))
322 def update_list(self):
323 ranked_items = self.policy.solver.details.get(self.interface, None)
324 if ranked_items is None:
325 # The Solver didn't get this far, but we should still display them!
326 ranked_items = [(impl, _("(solve aborted before here)"))
327 for impl in self.interface.implementations.values()]
328 # Always sort by version
329 ranked_items.sort()
330 self.use_list.set_items(ranked_items)
332 @tasks.async
333 def add_remote_feed(policy, parent, interface):
334 try:
335 d = gtk.MessageDialog(parent, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL,
336 _('Enter the URL of the new source of implementations of this interface:'))
337 d.add_button(gtk.STOCK_ADD, gtk.RESPONSE_OK)
338 d.set_default_response(gtk.RESPONSE_OK)
339 entry = gtk.Entry()
341 align = gtk.VBox(False, 0)
342 align.set_border_width(4)
343 align.add(entry)
344 d.vbox.pack_start(align)
345 entry.set_activates_default(True)
347 entry.set_text('')
349 d.vbox.show_all()
351 error_label = gtk.Label('')
352 error_label.set_padding(4, 4)
353 align.pack_start(error_label)
355 d.show()
357 def error(message):
358 if message:
359 error_label.set_text(message)
360 error_label.show()
361 else:
362 error_label.hide()
364 while True:
365 got_response = DialogResponse(d)
366 yield got_response
367 tasks.check(got_response)
368 resp = got_response.response
370 error(None)
371 if resp == gtk.RESPONSE_OK:
372 try:
373 url = entry.get_text()
374 if not url:
375 raise zeroinstall.SafeException(_('Enter a URL'))
376 fetch = policy.fetcher.download_and_import_feed(url, iface_cache)
377 if fetch:
378 d.set_sensitive(False)
379 yield fetch
380 d.set_sensitive(True)
381 tasks.check(fetch)
383 iface = iface_cache.get_interface(url)
385 d.set_sensitive(True)
386 if not iface.name:
387 error(_('Failed to read interface'))
388 return
389 if not iface.feed_for:
390 error(_("Feed '%(feed)s' is not a feed for '%(feed_for)s'.") % {'feed': iface.get_name(), 'feed_for': interface.get_name()})
391 elif interface.uri not in iface.feed_for:
392 error(_("This is not a feed for '%(uri)s'.\nOnly for:\n%(feed_for)s") %
393 {'uri': interface.uri, 'feed_for': '\n'.join(iface.feed_for)})
394 elif iface.uri in [f.uri for f in interface.extra_feeds]:
395 error(_("Feed from '%s' has already been added!") % iface.uri)
396 else:
397 interface.extra_feeds.append(Feed(iface.uri, arch = None, user_override = True))
398 writer.save_interface(interface)
399 d.destroy()
400 policy.recalculate()
401 except zeroinstall.SafeException, ex:
402 error(str(ex))
403 else:
404 d.destroy()
405 return
406 except Exception, ex:
407 import traceback
408 traceback.print_exc()
409 policy.handler.report_error(ex)
411 def add_local_feed(policy, interface):
412 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))
413 def ok(feed):
414 from zeroinstall.injector import reader
415 try:
416 feed_targets = policy.get_feed_targets(feed)
417 if interface not in feed_targets:
418 raise Exception(_("Not a valid feed for '%(uri)s'; this is a feed for:\n%(feed_for)s") %
419 {'uri': interface.uri,
420 'feed_for': '\n'.join([f.uri for f in feed_targets])})
421 if feed in [f.uri for f in interface.extra_feeds]:
422 dialog.alert(None, _('This feed is already registered.'))
423 else:
424 interface.extra_feeds.append(Feed(feed, user_override = True, arch = None))
426 writer.save_interface(interface)
427 chooser.destroy()
428 reader.update_from_cache(interface)
429 policy.recalculate()
430 except Exception, ex:
431 dialog.alert(None, _("Error in feed file '%(feed)s':\n\n%(exception)s") % {'feed': feed, 'exception': str(ex)})
433 def check_response(widget, response):
434 if response == gtk.RESPONSE_OK:
435 ok(widget.get_filename())
436 elif response == gtk.RESPONSE_CANCEL:
437 widget.destroy()
439 chooser.connect('response', check_response)
440 chooser.show()
442 def edit(policy, interface, show_versions = False):
443 assert isinstance(interface, Interface)
444 if interface in _dialogs:
445 _dialogs[interface].destroy()
446 _dialogs[interface] = Properties(policy, interface, show_versions)
447 _dialogs[interface].show()
449 properties_help = help_box.HelpBox(_("Injector Properties Help"),
450 (_('Interface properties'), '\n' +
451 _("""This window displays information about an interface. There are two tabs at the top: \
452 Feeds shows the places where the injector looks for implementations of the interface, while \
453 Versions shows the list of implementations found (from all feeds) in order of preference.""")),
455 (_('The Feeds tab'), '\n' +
456 _("""At the top is a list of feeds. By default, the injector uses the full name of the interface \
457 as the default feed location (so if you ask it to run the program "http://foo/bar.xml" then it will \
458 by default get the list of versions by downloading "http://foo/bar.xml".
460 You can add and remove feeds using the buttons on the right. The main feed may also add \
461 some extra feeds itself. If you've checked out a developer version of a program, you can use \
462 the 'Add Local Feed...' button to let the injector know about it, for example.
464 Below the list of feeds is a box describing the selected one:
466 - At the top is its short name.
467 - Below that is the address (a URL or filename).
468 - 'Last upstream change' shows the version of the cached copy of the interface file.
469 - 'Last checked' is the last time a fresh copy of the upstream interface file was \
470 downloaded.
471 - Then there is a longer description of the interface.""")),
473 (_('The Versions tab'), '\n' +
474 _("""This tab shows a list of all known implementations of the interface, from all the feeds. \
475 The columns have the following meanings:
477 Version gives the version number. High-numbered versions are considered to be \
478 better than low-numbered ones.
480 Released gives the date this entry was added to the feed.
482 Stability is 'stable' if the implementation is believed to be stable, 'buggy' if \
483 it is known to contain serious bugs, and 'testing' if its stability is not yet \
484 known. This information is normally supplied and updated by the author of the \
485 software, but you can override their rating by right-clicking here (overridden \
486 values are shown in upper-case). You can also use the special level 'preferred'.
488 Fetch indicates how much data needs to be downloaded to get this version if you don't \
489 have it. If the implementation has already been downloaded to your computer, \
490 it will say (cached). (local) means that you installed this version manually and \
491 told Zero Install about it by adding a feed. (package) means that this version \
492 is provided by your distribution's package manager, not by Zero Install. \
493 In off-line mode, only cached implementations are considered for use.
495 Arch indicates what kind of computer system the implementation is for, or 'any' \
496 if it works with all types of system.""") + '\n'),
497 (_('Sort order'), '\n' +
498 _("""The implementations are ordered by version number (highest first), with the \
499 currently selected one in bold. This is the "best" usable version.
501 Unusable ones are those for incompatible \
502 architectures, those marked as 'buggy' or 'insecure', versions explicitly marked as incompatible with \
503 another interface you are using and, in off-line mode, uncached implementations. Unusable \
504 implementations are shown crossed out.
506 For the usable implementations, the order is as follows:
508 - Preferred implementations come first.
510 - Then, if network use is set to 'Minimal', cached implementations come before \
511 non-cached.
513 - Then, implementations at or above the selected stability level come before all others.
515 - Then, higher-numbered versions come before low-numbered ones.
517 - Then cached come before non-cached (for 'Full' network use mode).""") + '\n'),
519 (_('Compiling'), '\n' +
520 _("""If there is no binary available for your system then you may be able to compile one from \
521 source by clicking on the Compile button. If no source is available, the Compile button will \
522 be shown shaded.""") + '\n'))