Need to check how proxies interact with pooling
[zeroinstall.git] / zeroinstall / 0launch-gui / properties.py
blob8de418d9b8363831dcee2a4f41c7d728b3cb6e65
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(policy, interface):
33 iface_cache = policy.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, policy, interface, widgets):
161 self.policy = policy
162 self.interface = interface
164 self.model = gtk.ListStore(str, str, bool)
166 self.description = Description(widgets)
168 self.lines = self.build_model()
169 for line in self.lines:
170 self.model.append(line)
172 add_remote_feed_button = widgets.get_widget('add_remote_feed')
173 add_remote_feed_button.connect('clicked', lambda b: add_remote_feed(policy, widgets.get_widget(), interface))
175 add_local_feed_button = widgets.get_widget('add_local_feed')
176 add_local_feed_button.connect('clicked', lambda b: add_local_feed(policy, interface))
178 self.remove_feed_button = widgets.get_widget('remove_feed')
179 def remove_feed(button):
180 model, iter = self.tv.get_selection().get_selected()
181 feed_uri = model[iter][Feeds.URI]
182 for x in interface.extra_feeds:
183 if x.uri == feed_uri:
184 if x.user_override:
185 interface.extra_feeds.remove(x)
186 writer.save_interface(interface)
187 import main
188 main.recalculate()
189 return
190 else:
191 dialog.alert(self.get_toplevel(),
192 _("Can't remove '%s' as you didn't add it.") % feed_uri)
193 return
194 raise Exception(_("Missing feed '%s'!") % feed_uri)
195 self.remove_feed_button.connect('clicked', remove_feed)
197 self.tv = widgets.get_widget('feeds_list')
198 self.tv.set_model(self.model)
199 text = gtk.CellRendererText()
200 self.tv.append_column(gtk.TreeViewColumn(_('Source'), text, text = Feeds.URI, sensitive = Feeds.USED))
201 self.tv.append_column(gtk.TreeViewColumn(_('Arch'), text, text = Feeds.ARCH, sensitive = Feeds.USED))
203 sel = self.tv.get_selection()
204 sel.set_mode(gtk.SELECTION_BROWSE)
205 sel.connect('changed', self.sel_changed)
206 sel.select_path((0,))
208 def build_model(self):
209 iface_cache = self.policy.config.iface_cache
211 usable_feeds = frozenset(self.policy.usable_feeds(self.interface))
212 unusable_feeds = frozenset(iface_cache.get_feed_imports(self.interface)) - usable_feeds
214 out = [[self.interface.uri, None, True]]
216 for feed in usable_feeds:
217 out.append([feed.uri, feed.arch, True])
218 for feed in unusable_feeds:
219 out.append([feed.uri, feed.arch, False])
220 return out
222 def sel_changed(self, sel):
223 iface_cache = self.policy.config.iface_cache
225 model, miter = sel.get_selected()
226 if not miter: return # build in progress
227 feed_url = model[miter][Feeds.URI]
228 # Only enable removing user_override feeds
229 enable_remove = False
230 for x in self.interface.extra_feeds:
231 if x.uri == feed_url:
232 if x.user_override:
233 enable_remove = True
234 self.remove_feed_button.set_sensitive( enable_remove )
235 try:
236 self.description.set_details(iface_cache, iface_cache.get_feed(feed_url))
237 except zeroinstall.SafeException as ex:
238 self.description.set_details(iface_cache, ex)
240 def updated(self):
241 new_lines = self.build_model()
242 if new_lines != self.lines:
243 self.lines = new_lines
244 self.model.clear()
245 for line in self.lines:
246 self.model.append(line)
247 self.tv.get_selection().select_path((0,))
248 else:
249 self.sel_changed(self.tv.get_selection())
251 class Properties:
252 interface = None
253 use_list = None
254 window = None
255 policy = None
257 def __init__(self, policy, interface, compile, show_versions = False):
258 self.policy = policy
260 widgets = Template('interface_properties')
262 self.interface = interface
264 window = widgets.get_widget('interface_properties')
265 self.window = window
266 window.set_title(_('Properties for %s') % interface.get_name())
267 window.set_default_size(-1, gtk.gdk.screen_height() / 3)
269 self.compile_button = widgets.get_widget('compile')
270 self.compile_button.connect('clicked', lambda b: compile(interface))
271 window.set_default_response(gtk.RESPONSE_CANCEL)
273 def response(dialog, resp):
274 if resp == gtk.RESPONSE_CANCEL:
275 window.destroy()
276 elif resp == gtk.RESPONSE_HELP:
277 properties_help.display()
278 window.connect('response', response)
280 notebook = widgets.get_widget('interface_notebook')
281 assert notebook
283 feeds = Feeds(policy, interface, widgets)
285 stability = widgets.get_widget('preferred_stability')
286 stability.set_active(0)
287 if interface.stability_policy:
288 i = [stable, testing, developer].index(interface.stability_policy)
289 i += 1
290 if i == 0:
291 warn(_("Unknown stability policy %s"), interface.stability_policy)
292 else:
293 i = 0
294 stability.set_active(i)
296 def set_stability_policy(combo, stability = stability): # (pygtk bug?)
297 i = stability.get_active()
298 if i == 0:
299 new_stability = None
300 else:
301 name = ['stable', 'testing', 'developer'][i-1]
302 new_stability = stability_levels[name]
303 interface.set_stability_policy(new_stability)
304 writer.save_interface(interface)
305 import main
306 main.recalculate()
307 stability.connect('changed', set_stability_policy)
309 self.use_list = ImplementationList(policy, interface, widgets)
311 self.update_list()
313 feeds.tv.grab_focus()
315 def updated():
316 self.update_list()
317 feeds.updated()
318 self.shade_compile()
319 window.connect('destroy', lambda s: policy.watchers.remove(updated))
320 policy.watchers.append(updated)
321 self.shade_compile()
323 if show_versions:
324 notebook.next_page()
326 def show(self):
327 self.window.show()
329 def destroy(self):
330 self.window.destroy()
332 def shade_compile(self):
333 self.compile_button.set_sensitive(have_source_for(self.policy, self.interface))
335 def update_list(self):
336 ranked_items = self.policy.solver.details.get(self.interface, None)
337 if ranked_items is None:
338 # The Solver didn't get this far, but we should still display them!
339 ranked_items = [(impl, _("(solve aborted before here)"))
340 for impl in self.interface.implementations.values()]
341 # Always sort by version
342 ranked_items.sort()
343 self.use_list.set_items(ranked_items)
345 @tasks.async
346 def add_remote_feed(policy, parent, interface):
347 try:
348 iface_cache = policy.config.iface_cache
350 d = gtk.MessageDialog(parent, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL,
351 _('Enter the URL of the new source of implementations of this interface:'))
352 d.add_button(gtk.STOCK_ADD, gtk.RESPONSE_OK)
353 d.set_default_response(gtk.RESPONSE_OK)
354 entry = gtk.Entry()
356 align = gtk.VBox(False, 0)
357 align.set_border_width(4)
358 align.add(entry)
359 d.vbox.pack_start(align)
360 entry.set_activates_default(True)
362 entry.set_text('')
364 d.vbox.show_all()
366 error_label = gtk.Label('')
367 error_label.set_padding(4, 4)
368 align.pack_start(error_label)
370 d.show()
372 def error(message):
373 if message:
374 error_label.set_text(message)
375 error_label.show()
376 else:
377 error_label.hide()
379 while True:
380 got_response = DialogResponse(d)
381 yield got_response
382 tasks.check(got_response)
383 resp = got_response.response
385 error(None)
386 if resp == gtk.RESPONSE_OK:
387 try:
388 url = entry.get_text()
389 if not url:
390 raise zeroinstall.SafeException(_('Enter a URL'))
391 fetch = policy.fetcher.download_and_import_feed(url, iface_cache)
392 if fetch:
393 d.set_sensitive(False)
394 yield fetch
395 d.set_sensitive(True)
396 tasks.check(fetch)
398 iface = iface_cache.get_interface(url)
400 d.set_sensitive(True)
401 if not iface.name:
402 error(_('Failed to read interface'))
403 return
404 if not iface.feed_for:
405 error(_("Feed '%(feed)s' is not a feed for '%(feed_for)s'.") % {'feed': iface.get_name(), 'feed_for': interface.get_name()})
406 elif interface.uri not in iface.feed_for:
407 error(_("This is not a feed for '%(uri)s'.\nOnly for:\n%(feed_for)s") %
408 {'uri': interface.uri, 'feed_for': '\n'.join(iface.feed_for)})
409 elif iface.uri in [f.uri for f in interface.extra_feeds]:
410 error(_("Feed from '%s' has already been added!") % iface.uri)
411 else:
412 interface.extra_feeds.append(Feed(iface.uri, arch = None, user_override = True))
413 writer.save_interface(interface)
414 d.destroy()
415 import main
416 main.recalculate()
417 except zeroinstall.SafeException as ex:
418 error(str(ex))
419 else:
420 d.destroy()
421 return
422 except Exception as ex:
423 import traceback
424 traceback.print_exc()
425 policy.handler.report_error(ex)
427 def add_local_feed(policy, interface):
428 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))
429 def ok(feed):
430 from zeroinstall.injector import reader
431 try:
432 feed_targets = policy.get_feed_targets(feed)
433 if interface not in feed_targets:
434 raise Exception(_("Not a valid feed for '%(uri)s'; this is a feed for:\n%(feed_for)s") %
435 {'uri': interface.uri,
436 'feed_for': '\n'.join([f.uri for f in feed_targets])})
437 if feed in [f.uri for f in interface.extra_feeds]:
438 dialog.alert(None, _('This feed is already registered.'))
439 else:
440 interface.extra_feeds.append(Feed(feed, user_override = True, arch = None))
442 writer.save_interface(interface)
443 chooser.destroy()
444 reader.update_from_cache(interface)
445 import main
446 main.recalculate()
447 except Exception as ex:
448 dialog.alert(None, _("Error in feed file '%(feed)s':\n\n%(exception)s") % {'feed': feed, 'exception': str(ex)})
450 def check_response(widget, response):
451 if response == gtk.RESPONSE_OK:
452 ok(widget.get_filename())
453 elif response == gtk.RESPONSE_CANCEL:
454 widget.destroy()
456 chooser.connect('response', check_response)
457 chooser.show()
459 def edit(policy, interface, compile, show_versions = False):
460 assert isinstance(interface, Interface)
461 if interface in _dialogs:
462 _dialogs[interface].destroy()
463 _dialogs[interface] = Properties(policy, interface, compile, show_versions = show_versions)
464 _dialogs[interface].show()
466 properties_help = help_box.HelpBox(_("Injector Properties Help"),
467 (_('Interface properties'), '\n' +
468 _("""This window displays information about an interface. There are two tabs at the top: \
469 Feeds shows the places where the injector looks for implementations of the interface, while \
470 Versions shows the list of implementations found (from all feeds) in order of preference.""")),
472 (_('The Feeds tab'), '\n' +
473 _("""At the top is a list of feeds. By default, the injector uses the full name of the interface \
474 as the default feed location (so if you ask it to run the program "http://foo/bar.xml" then it will \
475 by default get the list of versions by downloading "http://foo/bar.xml".
477 You can add and remove feeds using the buttons on the right. The main feed may also add \
478 some extra feeds itself. If you've checked out a developer version of a program, you can use \
479 the 'Add Local Feed...' button to let the injector know about it, for example.
481 Below the list of feeds is a box describing the selected one:
483 - At the top is its short name.
484 - Below that is the address (a URL or filename).
485 - 'Last upstream change' shows the version of the cached copy of the interface file.
486 - 'Last checked' is the last time a fresh copy of the upstream interface file was \
487 downloaded.
488 - Then there is a longer description of the interface.""")),
490 (_('The Versions tab'), '\n' +
491 _("""This tab shows a list of all known implementations of the interface, from all the feeds. \
492 The columns have the following meanings:
494 Version gives the version number. High-numbered versions are considered to be \
495 better than low-numbered ones.
497 Released gives the date this entry was added to the feed.
499 Stability is 'stable' if the implementation is believed to be stable, 'buggy' if \
500 it is known to contain serious bugs, and 'testing' if its stability is not yet \
501 known. This information is normally supplied and updated by the author of the \
502 software, but you can override their rating by right-clicking here (overridden \
503 values are shown in upper-case). You can also use the special level 'preferred'.
505 Fetch indicates how much data needs to be downloaded to get this version if you don't \
506 have it. If the implementation has already been downloaded to your computer, \
507 it will say (cached). (local) means that you installed this version manually and \
508 told Zero Install about it by adding a feed. (package) means that this version \
509 is provided by your distribution's package manager, not by Zero Install. \
510 In off-line mode, only cached implementations are considered for use.
512 Arch indicates what kind of computer system the implementation is for, or 'any' \
513 if it works with all types of system.""") + '\n'),
514 (_('Sort order'), '\n' +
515 _("""The implementations are ordered by version number (highest first), with the \
516 currently selected one in bold. This is the "best" usable version.
518 Unusable ones are those for incompatible \
519 architectures, those marked as 'buggy' or 'insecure', versions explicitly marked as incompatible with \
520 another interface you are using and, in off-line mode, uncached implementations. Unusable \
521 implementations are shown crossed out.
523 For the usable implementations, the order is as follows:
525 - Preferred implementations come first.
527 - Then, if network use is set to 'Minimal', cached implementations come before \
528 non-cached.
530 - Then, implementations at or above the selected stability level come before all others.
532 - Then, higher-numbered versions come before low-numbered ones.
534 - Then cached come before non-cached (for 'Full' network use mode).""") + '\n'),
536 (_('Compiling'), '\n' +
537 _("""If there is no binary available for your system then you may be able to compile one from \
538 source by clicking on the Compile button. If no source is available, the Compile button will \
539 be shown shaded.""") + '\n'))