Updated exception handling to Python 2.6 syntax
[zeroinstall.git] / zeroinstall / 0launch-gui / mainwindow.py
blob6c9f8d435da15b8a914ad450905a356d9afd3bb3
1 # Copyright (C) 2009, Thomas Leonard
2 # See the README file for details, or visit http://0install.net.
4 import gtk
5 import sys
6 from logging import info
8 from zeroinstall import _, translation
9 from zeroinstall import SafeException
10 from zeroinstall.support import tasks, pretty_size
11 from zeroinstall.injector import download, iface_cache
12 from iface_browser import InterfaceBrowser
13 import dialog
14 from zeroinstall.gtkui import gtkutils
15 from zeroinstall.gtkui import help_box
17 ngettext = translation.ngettext
19 SHOW_PREFERENCES = 0
21 class MainWindow:
22 progress = None
23 progress_area = None
24 browser = None
25 window = None
26 cancel_download_and_run = None
27 policy = None
28 comment = None
29 systray_icon = None
30 systray_icon_blocker = None
32 def __init__(self, policy, widgets, download_only, select_only = False):
33 self.policy = policy
34 self.select_only = select_only
36 def update_ok_state():
37 self.window.set_response_sensitive(gtk.RESPONSE_OK, policy.solver.ready)
38 if policy.solver.ready and self.window.get_focus() is None:
39 run_button.grab_focus()
40 policy.watchers.append(update_ok_state)
42 self.window = widgets.get_widget('main')
43 self.window.set_default_size(gtk.gdk.screen_width() * 2 / 5, 300)
45 self.progress = widgets.get_widget('progress')
46 self.progress_area = widgets.get_widget('progress_area')
47 self.comment = widgets.get_widget('comment')
49 widgets.get_widget('stop').connect('clicked', lambda b: policy.handler.abort_all_downloads())
51 self.refresh_button = widgets.get_widget('refresh')
53 # Tree view
54 self.browser = InterfaceBrowser(policy, widgets)
56 prefs = widgets.get_widget('preferences')
57 self.window.action_area.set_child_secondary(prefs, True)
59 # Glade won't let me add this to the template!
60 if select_only:
61 run_button = dialog.MixedButton(_("_Select"), gtk.STOCK_EXECUTE, button = gtk.ToggleButton())
62 elif download_only:
63 run_button = dialog.MixedButton(_("_Download"), gtk.STOCK_EXECUTE, button = gtk.ToggleButton())
64 else:
65 run_button = dialog.MixedButton(_("_Run"), gtk.STOCK_EXECUTE, button = gtk.ToggleButton())
66 self.window.add_action_widget(run_button, gtk.RESPONSE_OK)
67 run_button.show_all()
68 run_button.set_flags(gtk.CAN_DEFAULT)
69 self.run_button = run_button
71 run_button.grab_focus()
73 def response(dialog, resp):
74 if resp in (gtk.RESPONSE_CANCEL, gtk.RESPONSE_DELETE_EVENT):
75 self.window.destroy()
76 sys.exit(1)
77 elif resp == gtk.RESPONSE_OK:
78 if self.cancel_download_and_run:
79 self.cancel_download_and_run.trigger()
80 if run_button.get_active():
81 self.cancel_download_and_run = tasks.Blocker("cancel downloads")
82 self.download_and_run(run_button, self.cancel_download_and_run)
83 elif resp == gtk.RESPONSE_HELP:
84 gui_help.display()
85 elif resp == SHOW_PREFERENCES:
86 import preferences
87 preferences.show_preferences(policy.config, notify_cb = lambda: policy.solve_with_downloads())
88 self.window.connect('response', response)
89 self.window.realize() # Make busy pointer work, even with --systray
91 def destroy(self):
92 self.window.destroy()
94 def show(self):
95 self.window.show()
97 def set_response_sensitive(self, response, sensitive):
98 self.window.set_response_sensitive(response, sensitive)
100 @tasks.async
101 def download_and_run(self, run_button, cancelled):
102 try:
103 if not self.select_only:
104 downloaded = self.policy.download_uncached_implementations()
106 if downloaded:
107 # We need to wait until everything is downloaded...
108 blockers = [downloaded, cancelled]
109 yield blockers
110 tasks.check(blockers)
112 if cancelled.happened:
113 return
115 uncached = self.policy.get_uncached_implementations()
116 else:
117 uncached = None # (we don't care)
119 if uncached:
120 missing = '\n- '.join([_('%(iface_name)s %(impl_version)s') % {'iface_name': iface.get_name(), 'impl_version': impl.get_version()} for iface, impl in uncached])
121 dialog.alert(self.window, _('Not all downloads succeeded; cannot run program.\n\nFailed to get:') + '\n- ' + missing)
122 else:
123 from zeroinstall.injector import selections
124 sels = selections.Selections(self.policy)
125 doc = sels.toDOM()
126 reply = doc.toxml('utf-8')
127 sys.stdout.write(('Length:%8x\n' % len(reply)) + reply)
128 self.window.destroy()
129 sys.exit(0) # Success
130 except SystemExit:
131 raise
132 except download.DownloadAborted as ex:
133 run_button.set_active(False)
134 # Don't bother reporting this to the user
135 except Exception as ex:
136 run_button.set_active(False)
137 self.report_exception(ex)
139 def update_download_status(self):
140 """Called at regular intervals while there are downloads in progress,
141 and once at the end. Update the display."""
142 monitored_downloads = self.policy.handler.monitored_downloads
144 self.browser.update_download_status()
146 if not monitored_downloads:
147 self.progress_area.hide()
148 self.window.window.set_cursor(None)
149 return
151 if not self.progress_area.get_property('visible'):
152 self.progress_area.show()
153 self.window.window.set_cursor(gtkutils.get_busy_pointer())
155 any_known = False
156 done = total = self.policy.handler.total_bytes_downloaded # Completed downloads
157 n_downloads = self.policy.handler.n_completed_downloads
158 # Now add downloads in progress...
159 for x in monitored_downloads.values():
160 if x.status != download.download_fetching: continue
161 n_downloads += 1
162 if x.expected_size:
163 any_known = True
164 so_far = x.get_bytes_downloaded_so_far()
165 total += x.expected_size or max(4096, so_far) # Guess about 4K for feeds/icons
166 done += so_far
168 progress_text = '%s / %s' % (pretty_size(done), pretty_size(total))
169 self.progress.set_text(
170 ngettext('Downloading one file (%(progress)s)',
171 'Downloading %(number)d files (%(progress)s)', n_downloads)
172 % {'progress': progress_text, 'number': n_downloads})
174 if total == 0 or (n_downloads < 2 and not any_known):
175 self.progress.pulse()
176 else:
177 self.progress.set_fraction(float(done) / total)
179 def set_message(self, message):
180 import pango
181 self.comment.set_text(message)
182 attrs = pango.AttrList()
183 attrs.insert(pango.AttrWeight(pango.WEIGHT_BOLD, end_index = len(message)))
184 self.comment.set_attributes(attrs)
185 self.comment.show()
187 def use_systray_icon(self):
188 try:
189 self.systray_icon = gtk.status_icon_new_from_icon_name("zeroinstall")
190 except Exception as ex:
191 info(_("No system tray support: %s"), ex)
192 else:
193 root_iface = iface_cache.iface_cache.get_interface(self.policy.root)
194 self.systray_icon.set_tooltip(_('Checking for updates for %s') % root_iface.get_name())
195 self.systray_icon.connect('activate', self.remove_systray_icon)
196 self.systray_icon_blocker = tasks.Blocker('Tray icon clicked')
198 def remove_systray_icon(self, i = None):
199 assert self.systray_icon, i
200 self.show()
201 self.systray_icon.set_visible(False)
202 self.systray_icon = None
203 self.systray_icon_blocker.trigger()
204 self.systray_icon_blocker = None
206 def report_exception(self, ex, tb = None):
207 if not isinstance(ex, SafeException):
208 import traceback
209 traceback.print_exception(ex, None, tb)
210 if self.systray_icon:
211 self.systray_icon.set_blinking(True)
212 self.systray_icon.set_tooltip(str(ex) + '\n' + _('(click for details)'))
213 else:
214 dialog.alert(self.window, str(ex))
216 gui_help = help_box.HelpBox(_("Injector Help"),
217 (_('Overview'), '\n' +
218 _("""A program is made up of many different components, typically written by different \
219 groups of people. Each component is available in multiple versions. Zero Install is \
220 used when starting a program. Its job is to decide which implementation of each required \
221 component to use.
223 Zero Install starts with the program you want to run (like 'The Gimp') and chooses an \
224 implementation (like 'The Gimp 2.2.0'). However, this implementation \
225 will in turn depend on other components, such as 'GTK' (which draws the menus \
226 and buttons). Thus, it must choose implementations of \
227 each dependency (each of which may require further components, and so on).""")),
229 (_('List of components'), '\n' +
230 _("""The main window displays all these components, and the version of each chosen \
231 implementation. The top-most one represents the program you tried to run, and each direct \
232 child is a dependency. The 'Fetch' column shows the amount of data that needs to be \
233 downloaded, or '(cached)' if it is already on this computer.
235 If you are happy with the choices shown, click on the Download (or Run) button to \
236 download (and run) the program.""")),
238 (_('Choosing different versions'), '\n' +
239 _("""To control which implementations (versions) are chosen you can click on Preferences \
240 and adjust the network policy and the overall stability policy. These settings affect \
241 all programs run using Zero Install.
243 Alternatively, you can edit the policy of an individual component by clicking on the \
244 button at the end of its line in the table and choosing "Show Versions" from the menu. \
245 See that dialog's help text for more information.""") + '\n'),
247 (_('Reporting bugs'), '\n' +
248 _("""To report a bug, right-click over the component which you think contains the problem \
249 and choose 'Report a Bug...' from the menu. If you don't know which one is the cause, \
250 choose the top one (i.e. the program itself). The program's author can reassign the \
251 bug if necessary, or switch to using a different version of the library.""") + '\n'),
253 (_('The cache'), '\n' +
254 _("""Each version of a program that is downloaded is stored in the Zero Install cache. This \
255 means that it won't need to be downloaded again each time you run the program. The \
256 "0store manage" command can be used to view the cache.""") + '\n'),