Debian Codegraph @

timedops.py

raw
1 #!/usr/bin/python3
2
3 ## Copyright (C) 2008, 2009, 2010, 2012, 2014 Red Hat, Inc.
4 ## Authors:
5 ## Tim Waugh <[email protected]>
6
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
16
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
21 import dbus.mainloop.glib
22 from gi.repository import GObject
23 from gi.repository import GLib
24 from gi.repository import Gdk
25 from gi.repository import Gtk
26 import subprocess
27 import threading
28 import config
29 import gettext
30 gettext.install(domain=config.PACKAGE, localedir=config.localedir)
31 from debug import *
32
33 # Initialise threading for D-Bus. This is needed as long as it is
34 # used from two separate threads. We only do this in a few places
35 # now, but in particular the troubleshooter does this (bug #662047).
36 Gdk.threads_init ()
37 dbus.mainloop.glib.threads_init ()
38
39 class OperationCanceled(RuntimeError):
40 pass
41
42 class Timed:
43 def run (self):
44 pass
45
46 def cancel (self):
47 return False
48
49 class TimedSubprocess(Timed):
50 def __init__ (self, timeout=60000, parent=None, show_dialog=True,
51 **args):
52 self.subp = subprocess.Popen (**args)
53 self.output = dict()
54 self.io_source = []
55 self.watchers = 2
56 self.timeout = timeout
57 self.parent = parent
58 self.show_dialog = show_dialog
59 for f in [self.subp.stdout, self.subp.stderr]:
60 if f is not None:
61 source = GLib.io_add_watch (f,
62 GLib.PRIORITY_DEFAULT,
63 GLib.IO_IN |
64 GLib.IO_HUP |
65 GLib.IO_ERR,
66 self.watcher)
67 self.io_source.append (source)
68
69 self.wait_window = None
70
71 def run (self):
72 if self.show_dialog:
73 self.wait_source = GLib.timeout_add_seconds (
74 1,
75 self.show_wait_window)
76
77 self.timeout_source = GLib.timeout_add (self.timeout,
78 self.do_timeout)
79 Gtk.main ()
80 if self.timeout_source:
81 GLib.source_remove (self.timeout_source)
82 if self.show_dialog:
83 GLib.source_remove (self.wait_source)
84 for source in self.io_source:
85 GLib.source_remove (source)
86 if self.wait_window is not None:
87 self.wait_window.destroy ()
88 return (self.output.get (self.subp.stdout, '').split ('\n'),
89 self.output.get (self.subp.stderr, '').split ('\n'),
90 self.subp.poll ())
91
92 def do_timeout (self):
93 self.timeout_source = None
94 Gtk.main_quit ()
95 return False
96
97 def watcher (self, source, condition):
98 if condition & GLib.IO_IN:
99 buffer = self.output.get (source, '')
100 buffer += (source.read ()).decode("utf-8")
101 self.output[source] = buffer
102
103 if condition & GLib.IO_HUP:
104 self.watchers -= 1
105 if self.watchers == 0:
106 Gtk.main_quit ()
107
108 return True
109
110 def show_wait_window (self):
111 Gdk.threads_enter ()
112 wait = Gtk.MessageDialog (parent=self.parent,
113 modal=True, destroy_with_parent=True,
114 message_type=Gtk.MessageType.INFO,
115 buttons=Gtk.ButtonsType.CANCEL,
116 text=_("Please wait"))
117 wait.connect ("delete_event", lambda *args: False)
118 wait.connect ("response", self.wait_window_response)
119 if self.parent:
120 wait.set_transient_for (self.parent)
121 wait.set_position (Gtk.WindowPosition.CENTER_ON_PARENT)
122 wait.format_secondary_text (_("Gathering information"))
123 wait.show_all ()
124 self.wait_window = wait
125 Gdk.threads_leave ()
126 return False
127
128 def wait_window_response (self, dialog, response):
129 if response == Gtk.ResponseType.CANCEL:
130 self.cancel ()
131
132 def cancel (self):
133 if self.watchers > 0:
134 debugprint ("Command canceled")
135 Gtk.main_quit ()
136 self.watchers = 0
137
138 return False
139
140 class OperationThread(threading.Thread):
141 def __init__ (self, target=None, args=(), kwargs={}):
142 threading.Thread.__init__ (self)
143 self.setDaemon (True)
144 self.target = target
145 self.args = args
146 self.kwargs = kwargs
147 self.exception = None
148 self.result = None
149
150 def run (self):
151 try:
152 debugprint ("Calling %s" % self.target)
153 self.result = self.target (*self.args, **self.kwargs)
154 debugprint ("Done")
155 except Exception as e:
156 debugprint ("Caught exception %s" % e)
157 self.exception = e
158
159 def collect_result (self):
160 if self.is_alive ():
161 # We've been canceled.
162 raise OperationCanceled()
163
164 if self.exception:
165 raise self.exception
166
167 return self.result
168
169 class TimedOperation(Timed):
170 def __init__ (self, target, args=(), kwargs={}, parent=None,
171 show_dialog=False, callback=None, context=None):
172 self.wait_window = None
173 self.parent = parent
174 self.show_dialog = show_dialog
175 self.callback = callback
176 self.context = context
177 self.thread = OperationThread (target=target,
178 args=args,
179 kwargs=kwargs)
180 self.thread.start ()
181
182 self.use_callback = callback is not None
183 if self.use_callback:
184 self.timeout_source = GLib.timeout_add (50, self._check_thread)
185
186 def run (self):
187 if self.use_callback:
188 raise RuntimeError
189
190 if self.show_dialog:
191 wait = Gtk.MessageDialog (parent=self.parent,
192 modal=True, destroy_with_parent=True,
193 message_type=Gtk.MessageType.INFO,
194 buttons=Gtk.ButtonsType.CANCEL,
195 text=_("Please wait"))
196 wait.connect ("delete_event", lambda *args: False)
197 wait.connect ("response", self._wait_window_response)
198 if self.parent:
199 wait.set_transient_for (self.parent)
200
201 wait.set_position (Gtk.WindowPosition.CENTER_ON_PARENT)
202 wait.format_secondary_text (_("Gathering information"))
203 wait.show_all ()
204
205 self.timeout_source = GLib.timeout_add (50, self._check_thread)
206 Gtk.main ()
207 if self.timeout_source:
208 GLib.source_remove (self.timeout_source)
209 if self.show_dialog:
210 wait.destroy ()
211
212 return self.thread.collect_result ()
213
214 def _check_thread (self):
215 if self.thread.is_alive ():
216 # Thread still running.
217 return True
218
219 # Thread has finished. Stop the sub-loop or trigger callback.
220 self.timeout_source = False
221 if self.use_callback:
222 if self.callback is not None:
223 if self.context is not None:
224 self.callback (self.thread.result, self.thread.exception,
225 self.context)
226 else:
227 self.callback (self.thread.result, self.thread.exception)
228 else:
229 Gtk.main_quit ()
230
231 return False
232
233 def _wait_window_response (self, dialog, response):
234 if response == Gtk.ResponseType.CANCEL:
235 self.cancel ()
236
237 def cancel (self):
238 debugprint ("Command canceled")
239 if self.use_callback:
240 self.callback = None
241 else:
242 Gtk.main_quit ()
243
244 return False