~alecu/ubuntu-sso-client/qt-defer-to-thread

« back to all changes in this revision

Viewing changes to ubuntu_sso/utils/windows.py

  • Committer: Alejandro J. Cura
  • Date: 2012-03-30 00:37:10 UTC
  • Revision ID: alecu@canonical.com-20120330003710-18we5wlcbfpv2z4n
A Qt-based deferToThread

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
"""Platform specific constants and functions (for Windows)."""
18
18
 
19
19
PLATFORM_QSS = ":/windows.qss"
 
20
 
 
21
from twisted.internet import defer
 
22
from PyQt4.QtCore import QThread, QCoreApplication
 
23
 
 
24
 
 
25
class DeferredThread(QThread):
 
26
    """A thread that runs a given function."""
 
27
 
 
28
    def __init__(self, f, *args, **kwargs):
 
29
        """Initialize this thread."""
 
30
        app = QCoreApplication.instance()
 
31
        super(DeferredThread, self).__init__(app)
 
32
        self.deferred = defer.Deferred()
 
33
        self.f = f
 
34
        self.args = args
 
35
        self.kwargs = kwargs
 
36
        self.succeeded = True
 
37
        self.result = None
 
38
        self.finished.connect(self.on_finished)
 
39
 
 
40
    def run(self):
 
41
        """This code runs inside the thread."""
 
42
        try:
 
43
            self.result = self.f(*self.args, **self.kwargs)
 
44
        except Exception as e:
 
45
            self.succeeded = False
 
46
            self.result = e
 
47
 
 
48
    def on_finished(self):
 
49
        """The thread has completed."""
 
50
        if self.succeeded:
 
51
            self.deferred.callback(self.result)
 
52
        else:
 
53
            self.deferred.errback(self.result)
 
54
 
 
55
 
 
56
def qtDeferToThread(f, *args, **kwargs):
 
57
    """A Qt-based implementation of deferToThread."""
 
58
    thread = DeferredThread(f, *args, **kwargs)
 
59
    thread.start()
 
60
    return thread.deferred