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