Debian Codegraph @

docs/core/examples/threadedselect/Cocoa/SimpleWebClient/Twistzilla.py

raw
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4
5 from AppKit import *
6
7 # import needed classes/functions from Cocoa
8 from Foundation import *
9
10 # import Nib loading functionality from AppKit
11 from PyObjCTools import AppHelper, NibClassBuilder
12
13 from twisted.internet import _threadedselect
14
15 _threadedselect.install()
16
17 import sys
18
19 import urlparse
20
21 from twisted.internet import protocol, reactor
22 from twisted.python import log
23 from twisted.web import http
24
25 # create ObjC classes as defined in MainMenu.nib
26 NibClassBuilder.extractClasses("MainMenu")
27
28
29 class TwistzillaClient(http.HTTPClient):
30 def __init__(self, delegate, urls):
31 self.urls = urls
32 self.delegate = delegate
33
34 def connectionMade(self):
35 self.sendCommand("GET", str(self.urls[2]))
36 self.sendHeader("Host", "%s:%d" % (self.urls[0], self.urls[1]))
37 self.sendHeader("User-Agent", "CocoaTwistzilla")
38 self.endHeaders()
39
40 def handleResponse(self, data):
41 self.delegate.gotResponse_(data)
42
43
44 class MyAppDelegate(NibClassBuilder.AutoBaseClass):
45 def gotResponse_(self, html):
46 s = self.resultTextField.textStorage()
47 s.replaceCharactersInRange_withString_((0, s.length()), html)
48 self.progressIndicator.stopAnimation_(self)
49
50 def doTwistzillaFetch_(self, sender):
51 s = self.resultTextField.textStorage()
52 s.deleteCharactersInRange_((0, s.length()))
53 self.progressIndicator.startAnimation_(self)
54 u = urlparse.urlparse(self.messageTextField.stringValue())
55 pos = u[1].find(":")
56 if pos == -1:
57 host, port = u[1], 80
58 else:
59 host, port = u[1][:pos], int(u[1][pos + 1 :])
60 if u[2] == "":
61 fname = "/"
62 else:
63 fname = u[2]
64 host = host.encode("utf8")
65 fname = fname.encode("utf8")
66 protocol.ClientCreator(
67 reactor, TwistzillaClient, self, (host, port, fname)
68 ).connectTCP(host, port).addErrback(
69 lambda f: self.gotResponse_(f.getBriefTraceback())
70 )
71
72 def applicationDidFinishLaunching_(self, aNotification):
73 """
74 Invoked by NSApplication once the app is done launching and
75 immediately before the first pass through the main event
76 loop.
77 """
78 self.messageTextField.setStringValue_("http://www.twistedmatrix.com/")
79 reactor.interleave(AppHelper.callAfter)
80
81 def applicationShouldTerminate_(self, sender):
82 if reactor.running:
83 reactor.addSystemEventTrigger("after", "shutdown", AppHelper.stopEventLoop)
84 reactor.stop()
85 return False
86 return True
87
88
89 if __name__ == "__main__":
90 log.startLogging(sys.stdout)
91 AppHelper.runEventLoop()