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