Minor improvement to log message.
[zeroinstall.git] / zeroinstall / helpers.py
blobbc142985cea5e33844035e0a31a5d3ec3fccf3aa
1 """
2 Convenience routines for performing common operations.
3 @since: 0.28
4 """
6 # Copyright (C) 2007, 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 @since: 0.28
25 """
26 from zeroinstall.injector import selections, autopolicy, namespaces, model, run, qdom
27 from StringIO import StringIO
29 gui_policy = autopolicy.AutoPolicy(namespaces.injector_gui_uri)
30 if iface_uri != namespaces.injector_gui_uri and (gui_policy.need_download() or gui_policy.stale_feeds):
31 # The GUI itself needs updating. Do that first.
32 logging.info("The GUI could do with updating first.")
33 gui_sel = get_selections_gui(namespaces.injector_gui_uri, ['--refresh'])
34 if gui_sel is None:
35 logging.info("Aborted at user request")
36 return None # Aborted by user
37 else:
38 # Try to start the GUI without using the network.
39 gui_policy.freshness = 0
40 gui_policy.network_use = model.network_offline
41 gui_policy.recalculate()
42 assert gui_policy.ready # Should always be some version available
43 gui_sel = selections.Selections(gui_policy)
45 import socket
46 cli, gui = socket.socketpair()
48 try:
49 child = os.fork()
50 if child == 0:
51 # We are the child (GUI)
52 try:
53 try:
54 cli.close()
55 # We used to use pipes to support Python2.3...
56 os.dup2(gui.fileno(), 1)
57 os.dup2(gui.fileno(), 0)
58 run.execute_selections(gui_sel, gui_args + ['--', iface_uri])
59 except:
60 import traceback
61 traceback.print_exc(file = sys.stderr)
62 finally:
63 sys.stderr.flush()
64 os._exit(1)
65 # We are the parent (CLI)
66 gui.close()
67 gui = None
69 while True:
70 logging.info("Waiting for selections from GUI...")
72 reply = support.read_bytes(cli.fileno(), len('Length:') + 9, null_ok = True)
73 if reply:
74 if not reply.startswith('Length:'):
75 raise Exception("Expected Length:, but got %s" % repr(reply))
76 xml = support.read_bytes(cli.fileno(), int(reply.split(':', 1)[1], 16))
78 dom = qdom.parse(StringIO(xml))
79 sels = selections.Selections(dom)
81 if dom.getAttribute('run-test'):
82 logging.info("Testing program, as requested by GUI...")
83 if test_callback is None:
84 output = "Can't test: no test_callback was passed to get_selections_gui()\n"
85 else:
86 output = test_callback(sels)
87 logging.info("Sending results to GUI...")
88 output = ('Length:%8x\n' % len(output)) + output
89 logging.debug("Sending: %s" % `output`)
90 while output:
91 sent = cli.send(output)
92 output = output[sent:]
93 continue
94 else:
95 sels = None
97 pid, status = os.waitpid(child, 0)
98 assert pid == child
99 if status == 1 << 8:
100 logging.info("User cancelled the GUI; aborting")
101 return None # Aborted
102 if status != 0:
103 raise Exception("Error from GUI: code = %d" % status)
104 break
105 finally:
106 for sock in [cli, gui]:
107 if sock is not None: sock.close()
109 return sels
111 def ensure_cached(uri):
112 """Ensure that an implementation of uri is cached.
113 If not, it downloads one. It uses the GUI if a display is
114 available, or the console otherwise.
115 @param uri: the required interface
116 @type uri: str
117 @return: a new policy for this program, or None if the user cancelled
118 @rtype: L{zeroinstall.injector.selections.Selections}
120 from zeroinstall.injector import autopolicy, selections
122 p = autopolicy.AutoPolicy(uri, download_only = True)
123 p.freshness = 0 # Don't check for updates
125 if p.need_download() or not p.ready:
126 if os.environ.get('DISPLAY', None):
127 return get_selections_gui(uri, [])
128 else:
129 p.recalculate_with_dl()
130 p.start_downloading_impls()
131 p.handler.wait_for_downloads()
133 return selections.Selections(p)