• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /macosx-10.10/pyobjc-45/2.6/pyobjc/pyobjc-framework-WebKit/Examples/PyDocURLProtocol/
1from Foundation import *
2import objc
3from pydochelper import gethtmldoc
4
5PYDOCSCHEME = u'pydoc'
6
7class PyDocURLProtocol(NSURLProtocol):
8
9    def canInitWithRequest_(klass, request):
10        if request.URL().scheme() == PYDOCSCHEME:
11            return True
12        return False
13
14    def canonicalRequestForRequest_(klass, request):
15        return request
16
17    def startLoading(self):
18        client = self.client()
19        request = self.request()
20        urlpath = request.URL().standardizedURL().path()
21        modpath = urlpath.replace(u'/', u'.'
22            ).lstrip(u'.'
23            ).replace(u'.html', u'')
24
25        try:
26            data = gethtmldoc(modpath.encode('utf-8'))
27        except Exception, e:
28            client.URLProtocol_didFailWithError_(
29                self,
30                NSError.errorWithDomain_code_userInfo_(
31                    NSURLErrorDomain,
32                    NSURLErrorResourceUnavailable,
33                    None,
34                ),
35            )
36        else:
37            response = NSURLResponse.alloc().initWithURL_MIMEType_expectedContentLength_textEncodingName_(
38                request.URL(),
39                u'text/html',
40                len(data),
41                u'utf-8',
42            )
43            client.URLProtocol_didReceiveResponse_cacheStoragePolicy_(
44                self,
45                response,
46                NSURLCacheStorageNotAllowed,
47            )
48            client.URLProtocol_didLoadData_(
49                self,
50                buffer(data),
51            )
52            client.URLProtocolDidFinishLoading_(self)
53
54    def stopLoading(self):
55        pass
56
57def setup():
58    NSURLProtocol.registerClass_(PyDocURLProtocol)
59
60def teardown():
61    NSURLProtocol.unregisterClass_(PyDocURLProtocol)
62
63def main(*args):
64    if not args:
65        args = ('dict',)
66    setup()
67    for arg in args:
68        url = NSURL.URLWithString_(u'pydoc:///%s' % (arg,))
69        print NSString.stringWithContentsOfURL_(url)
70    teardown()
71
72import sys
73if __name__ == '__main__': main(*sys.argv[1:])
74