Removed warning about old GnuPG.
[zeroinstall.git] / zeroinstall / injector / background.py
blobd42a337c4d9ad15d3408c4b40f8069e1a2fcffa8
1 """
2 Check for updates in a background process. If we can start a program immediately, but some of our information
3 is rather old (longer that the freshness threshold) then we run it anyway, and check for updates using a new
4 process that runs quietly in the background.
6 This avoids the need to annoy people with a 'checking for updates' box when they're trying to run things.
7 """
9 import sys, os
10 from logging import info
11 from zeroinstall.injector.iface_cache import iface_cache
12 from zeroinstall.injector import handler
14 # Copyright (C) 2007, Thomas Leonard
15 # See the README file for details, or visit http://0install.net.
17 try:
18 import dbus
19 import dbus.glib
21 session_bus = dbus.SessionBus()
23 remote_object = session_bus.get_object('org.freedesktop.Notifications',
24 '/org/freedesktop/Notifications')
26 notification_service = dbus.Interface(remote_object,
27 'org.freedesktop.Notifications')
29 # The Python bindings insist on printing a pointless introspection
30 # warning to stderr if the service is missing. Force it to be done
31 # now so we can skip it
32 old_stderr = sys.stderr
33 sys.stderr = None
34 try:
35 notification_service.GetCapabilities()
36 finally:
37 sys.stderr = old_stderr
39 have_notifications = True
40 except Exception, ex:
41 info("Failed to import D-BUS bindings: %s", ex)
42 have_notifications = False
44 LOW = 0
45 NORMAL = 1
46 CRITICAL = 2
48 def _escape_xml(s):
49 return s.replace('&', '&amp;').replace('<', '&lt;')
51 def notify(title, message, timeout = 0, actions = []):
52 if not have_notifications:
53 info('%s: %s', title, message)
54 return None
56 import time
57 import dbus.types
59 hints = {}
60 if actions:
61 hints['urgency'] = dbus.types.Byte(NORMAL)
62 else:
63 hints['urgency'] = dbus.types.Byte(LOW)
65 return notification_service.Notify('Zero Install',
66 0, # replaces_id,
67 '', # icon
68 _escape_xml(title),
69 _escape_xml(message),
70 actions,
71 hints,
72 timeout * 1000)
74 def _exec_gui(uri, *args):
75 os.execvp('0launch', ['0launch', '--download-only', '--gui'] + list(args) + [uri])
77 class BackgroundHandler(handler.Handler):
78 def __init__(self, title):
79 handler.Handler.__init__(self)
80 self.title = title
82 def confirm_trust_keys(self, interface, sigs, iface_xml):
83 notify("Zero Install", "Can't update interface; signature not yet trusted. Running GUI...", timeout = 2)
84 _exec_gui(interface.uri, '--refresh')
86 def report_error(self, exception):
87 notify("Zero Install", "Error updating %s: %s" % (self.title, str(exception)))
89 def _detach():
90 """Fork a detached grandchild.
91 @return: True if we are the original."""
92 child = os.fork()
93 if child:
94 pid, status = os.waitpid(child, 0)
95 assert pid == child
96 return True
98 # The calling process might be waiting for EOF from its child.
99 # Close our stdout so we don't keep it waiting.
100 # Note: this only fixes the most common case; it could be waiting
101 # on any other FD as well. We should really use gobject.spawn_async
102 # to close *all* FDs.
103 null = os.open('/dev/null', os.O_RDWR)
104 os.dup2(null, 1)
105 os.close(null)
107 grandchild = os.fork()
108 if grandchild:
109 os._exit(0) # Parent's waitpid returns and grandchild continues
111 return False
113 def _check_for_updates(policy, verbose):
114 root_iface = iface_cache.get_interface(policy.root).get_name()
115 info("Checking for updates to '%s' in a background process", root_iface)
116 if verbose:
117 notify("Zero Install", "Checking for updates to '%s'..." % root_iface, timeout = 1)
119 policy.handler = BackgroundHandler(root_iface)
120 policy.freshness = 0 # Don't bother trying to refresh when getting the interface
121 policy.refresh_all() # (causes confusing log messages)
122 policy.handler.wait_for_downloads()
123 # We could even download the archives here, but for now just
124 # update the interfaces.
126 if not policy.need_download():
127 if verbose:
128 notify("Zero Install", "No updates to download.", timeout = 1)
129 sys.exit(0)
131 if not have_notifications:
132 notify("Zero Install", "Updates ready to download for '%s'." % root_iface)
133 sys.exit(0)
135 import gobject
136 ctx = gobject.main_context_default()
137 loop = gobject.MainLoop(ctx)
139 def _NotificationClosed(nid, *unused):
140 if nid != our_question: return
141 loop.quit()
143 def _ActionInvoked(nid, action):
144 if nid != our_question: return
145 if action == 'download':
146 _exec_gui(policy.root)
147 loop.quit()
149 notification_service.connect_to_signal('NotificationClosed', _NotificationClosed)
150 notification_service.connect_to_signal('ActionInvoked', _ActionInvoked)
152 our_question = notify("Zero Install", "Updates ready to download for '%s'." % root_iface,
153 actions = ['download', 'Download'])
155 loop.run()
157 def spawn_background_update(policy, verbose):
158 # Mark all feeds as being updated. Do this before forking, so that if someone is
159 # running lots of 0launch commands in series on the same program we don't start
160 # huge numbers of processes.
161 import time
162 for x in policy.implementation:
163 iface_cache.mark_as_checking(x.uri) # Main feed
164 for f in policy.usable_feeds(x):
165 iface_cache.mark_as_checking(f.uri) # Extra feeds
167 if _detach():
168 return
170 try:
171 try:
172 _check_for_updates(policy, verbose)
173 except SystemExit:
174 raise
175 except:
176 import traceback
177 traceback.print_exc()
178 sys.stdout.flush()
179 else:
180 sys.exit(0)
181 finally:
182 os._exit(1)