Update year to 2009 in various places
[zeroinstall/zeroinstall-rsl.git] / zeroinstall / helpers.py
blob4f952ef67d4fb06321ea8ef6af973db592bb62b3
1 """
2 Convenience routines for performing common operations.
3 @since: 0.28
4 """
6 # Copyright (C) 2009, Thomas Leonard
7 # See the README file for details, or visit http://0install.net.
9 import os, sys, logging
10 from zeroinstall import support
12 def get_selections_gui(iface_uri, gui_args, test_callback = None):
13 """Run the GUI to choose and download a set of implementations.
14 If the GUI itself is due for a check, refresh it first.
15 The user may ask the GUI to submit a bug report about the program. In that case,
16 the GUI may ask us to test it. test_callback is called in that case with the implementations
17 to be tested; the callback will typically call L{zeroinstall.injector.run.test_selections} and return the result of that.
18 @param iface_uri: the required program
19 @type iface_uri: str
20 @param gui_args: any additional arguments for the GUI itself
21 @type gui_args: [str]
22 @param test_callback: function to use to try running the program
23 @type test_callback: L{zeroinstall.injector.selections.Selections} -> str
24 @return: the selected implementations
25 @rtype: L{zeroinstall.injector.selections.Selections}
26 @since: 0.28
27 """
28 from zeroinstall.injector import selections, autopolicy, namespaces, model, run, qdom
29 from StringIO import StringIO
31 gui_policy = autopolicy.AutoPolicy(namespaces.injector_gui_uri)
32 if iface_uri != namespaces.injector_gui_uri and (gui_policy.need_download() or gui_policy.stale_feeds):
33 # The GUI itself needs updating. Do that first.
34 logging.info("The GUI could do with updating first.")
35 gui_sel = get_selections_gui(namespaces.injector_gui_uri, ['--refresh'])
36 if gui_sel is None:
37 logging.info("Aborted at user request")
38 return None # Aborted by user
39 else:
40 # Try to start the GUI without using the network.
41 gui_policy.freshness = 0
42 gui_policy.network_use = model.network_offline
43 gui_policy.recalculate()
44 assert gui_policy.ready # Should always be some version available
45 gui_sel = selections.Selections(gui_policy)
47 import socket
48 cli, gui = socket.socketpair()
50 try:
51 child = os.fork()
52 if child == 0:
53 # We are the child (GUI)
54 try:
55 try:
56 cli.close()
57 # We used to use pipes to support Python2.3...
58 os.dup2(gui.fileno(), 1)
59 os.dup2(gui.fileno(), 0)
60 run.execute_selections(gui_sel, gui_args + ['--', iface_uri])
61 except:
62 import traceback
63 traceback.print_exc(file = sys.stderr)
64 finally:
65 sys.stderr.flush()
66 os._exit(1)
67 # We are the parent (CLI)
68 gui.close()
69 gui = None
71 while True:
72 logging.info("Waiting for selections from GUI...")
74 reply = support.read_bytes(cli.fileno(), len('Length:') + 9, null_ok = True)
75 if reply:
76 if not reply.startswith('Length:'):
77 raise Exception("Expected Length:, but got %s" % repr(reply))
78 xml = support.read_bytes(cli.fileno(), int(reply.split(':', 1)[1], 16))
80 dom = qdom.parse(StringIO(xml))
81 sels = selections.Selections(dom)
83 if dom.getAttribute('run-test'):
84 logging.info("Testing program, as requested by GUI...")
85 if test_callback is None:
86 output = "Can't test: no test_callback was passed to get_selections_gui()\n"
87 else:
88 output = test_callback(sels)
89 logging.info("Sending results to GUI...")
90 output = ('Length:%8x\n' % len(output)) + output
91 logging.debug("Sending: %s", repr(output))
92 while output:
93 sent = cli.send(output)
94 output = output[sent:]
95 continue
96 else:
97 sels = None
99 pid, status = os.waitpid(child, 0)
100 assert pid == child
101 if status == 1 << 8:
102 logging.info("User cancelled the GUI; aborting")
103 return None # Aborted
104 if status != 0:
105 raise Exception("Error from GUI: code = %d" % status)
106 break
107 finally:
108 for sock in [cli, gui]:
109 if sock is not None: sock.close()
111 return sels
113 def ensure_cached(uri):
114 """Ensure that an implementation of uri is cached.
115 If not, it downloads one. It uses the GUI if a display is
116 available, or the console otherwise.
117 @param uri: the required interface
118 @type uri: str
119 @return: a new policy for this program, or None if the user cancelled
120 @rtype: L{zeroinstall.injector.selections.Selections}
122 from zeroinstall.injector import autopolicy, selections
124 p = autopolicy.AutoPolicy(uri, download_only = True)
125 p.freshness = 0 # Don't check for updates
127 if p.need_download() or not p.ready:
128 if os.environ.get('DISPLAY', None):
129 return get_selections_gui(uri, [])
130 else:
131 p.recalculate_with_dl()
132 p.start_downloading_impls()
133 p.handler.wait_for_downloads()
135 return selections.Selections(p)