Warning: Error with navigation contributor "BrowserModule"

source: ferringb/src_uri_checker/frontend.py @ marienz@gentoo.org-20060220170847-f0f633c8d1b80da6

Revision marienz@gentoo.org-20060220170847-f0f633c8d1b80da6, 5.6 KB checked in by Marien Zwart <marienz@…>, 5 years ago (diff)

remove pylint tab/space indent message disabling, use --indent-string='\t' instead.

  • Property executable set to True
Line 
1#!/usr/bin/env python
2
3
4"""Fancier frontend to scan."""
5
6
7import sys
8try:
9        import cPickle as pickle
10except ImportError:
11        import pickle
12
13
14from twisted.python import log, reflect, text as tptext
15from twisted.internet import task, reactor
16
17from twisted.conch import stdio
18from twisted.conch.insults import insults, window
19
20import base
21
22
23class TextOutputArea(window.TextOutputArea):
24
25        """Subclass to make the output clean up properly when scrolling up."""
26
27        def render(self, width, height, terminal):
28                """Write both our actual data and whitespace where we have none."""
29                n = 0
30                inputLines = self.text.splitlines()
31                outputLines = []
32                while inputLines:
33                        if self.longLines == self.WRAP:
34                                wrappedLines = tptext.greedyWrap(inputLines.pop(0), width)
35                                outputLines.extend(wrappedLines or [''])
36                        else:
37                                outputLines.append(inputLines.pop(0)[:width])
38                        if len(outputLines) >= height:
39                                break
40                for n, line in enumerate(outputLines[:height]):
41                        terminal.cursorPosition(0, n)
42                        terminal.write(line.ljust(width))
43                for n in range(len(outputLines), height):
44                        terminal.cursorPosition(0, n)
45                        terminal.write(''.ljust(width))
46
47
48class ScanFrontend(insults.TerminalProtocol):
49
50        """Pretty frontend to the scanner.
51
52        Mercilessly stolen from twisted-conch window.tac.
53        """
54
55        width = 80
56        height = 50
57
58        def _draw(self):
59                """Draw stuff."""
60                self.window.draw(self.width, self.height, self.terminal)
61
62        def _redraw(self):
63                """Redraw everything."""
64                self.window.filthy()
65                self._draw()
66
67        def _safeFormat(self, fmtString, crap):
68                #There's a way we could make this if not safer at least more
69                #informative: perhaps some sort of str/repr wrapper objects
70                #could be wrapped around the things inside of 'crap'. That way
71                #if the event dict contains an object with a bad __repr__, we
72                #can only cry about that individual object instead of the
73                #entire event dict.
74                try:
75                        text = fmtString % crap
76                except KeyboardInterrupt:
77                        raise
78                except:
79                        try:
80                                text = ('Invalid format string or unformattable object in log message: %r, %s' % (fmtString, crap))
81                        except:
82                                try:
83                                        text = 'UNFORMATTABLE OBJECT WRITTEN TO LOG with fmt %r, MESSAGE LOST' % (fmtString,)
84                                except:
85                                        text = 'PATHOLOGICAL ERROR IN BOTH FORMAT STRING AND MESSAGE DETAILS, MESSAGE LOST'
86                return text
87
88        def log(self, eventDict):
89                """Log a message."""
90                # Ripped from t.python.log.emit
91                edm = eventDict['message']
92                if eventDict['isError']:
93                        attrs = 'ERROR: ' # self.ERROR
94                else:
95                        attrs = '' # self.NORMAL
96                if not edm:
97                        if eventDict['isError'] and eventDict.has_key('failure'):
98                                text = eventDict['failure'].getTraceback()
99                        elif eventDict.has_key('format'):
100                                text = self._safeFormat(eventDict['format'], eventDict)
101                        else:
102                                # we don't know how to log this
103                                return
104                else:
105                        text = attrs + ' '.join(map(reflect.safe_str, edm)) #+ self.NORMAL
106                self.logLines.append(text)
107                self.logOut.setText('\n'.join(self.logLines))
108
109        def connectionMade(self):
110                """Initialize."""
111                if len(sys.argv) != 3:
112                        print 'need 2 args: url_dict pickle and file to write failures to'
113                        sys.exit(1)
114                        return
115
116                # read our hosts pickle
117                f = open(sys.argv[1], 'r')
118                urlDict = pickle.load(f)
119                f.close()
120
121                hosts = base.convertDictToHosts(urlDict)
122
123                self.terminal.eraseDisplay()
124                self.terminal.resetPrivateModes([insults.privateModes.CURSOR_MODE])
125                self.window = window.TopWindow(self._draw)
126                vbox = window.VBox()
127                # autosizing log window
128                self.logOut = TextOutputArea()
129                self.logLines = []
130                vbox.addChild(window.ScrolledArea(self.logOut))
131
132                # status output
133                self.statusOut = TextOutputArea()
134                vbox.addChild(self.statusOut)
135
136                # hosts output
137                self.hostsOut = TextOutputArea((80, 3))
138                vbox.addChild(window.ScrolledArea(self.hostsOut))
139
140                # set up logging
141                log.addObserver(self.log)
142
143                # finalize
144                self.window.addChild(vbox)
145                self.terminalSize(self.width, self.height)
146
147                # initialize jobProcessor
148                self.jobProcessor = base.JobProcessor(hosts)
149                logCall = task.LoopingCall(self.printStats)
150                logCall.start(0.5)
151                hostsCall = task.LoopingCall(self.printHosts)
152                hostsCall.start(5)
153                def writeStats(arg):
154                        """Write our statistics to file."""
155                        outFile = open(sys.argv[2], "w")
156                        try:
157                                base.writeHosts(outFile, self.jobProcessor.hosts)
158                        finally:
159                                outFile.close()
160
161                def shutDown(arg):
162                        """Exit."""
163                        logCall.stop()
164                        hostsCall.stop()
165                        reactor.stop()
166                self.jobProcessor.deferred.addErrback(log.err)
167                self.jobProcessor.deferred.addCallback(writeStats)
168                self.jobProcessor.deferred.addBoth(shutDown)
169
170        def printStats(self):
171                """Print current status to an output widget."""
172                self.statusOut.setText('\n'.join(self.jobProcessor.stats()))
173
174        def printHosts(self):
175                """Print active hosts to our output widget."""
176                self.hostsOut.setText('\n'.join(self.jobProcessor.moreStats()))
177
178        def connectionLost(self, reason):
179                """Relay a lost connection."""
180                insults.TerminalProtocol.connectionLost(self, reason)
181
182        def terminalSize(self, width, height):
183                """Adjust to a changed terminal size."""
184                self.width = width
185                self.height = height
186                self.terminal.eraseDisplay()
187                self._redraw()
188
189        def unhandledControlSequence(self, seq):
190                """Log unhandled input."""
191                log.msg('wtf is %r' % seq)
192
193        def keystrokeReceived(self, keyID, modifier):
194                """Write and quit on q, pass the rest to the widget machinery."""
195                if keyID == 'q':
196                        try:
197                                outFile = open(sys.argv[2], "w")
198                                try:
199                                        base.writeHosts(outFile, self.jobProcessor.hosts)
200                                finally:
201                                        outFile.close()
202                        finally:
203                                reactor.stop()
204                self.window.keystrokeReceived(keyID, modifier)
205
206
207if __name__ == '__main__':
208        # extra logging
209        log.startLogging(open('twisted.log', 'w'))
210        # this fires up the reactor too
211        stdio.runWithProtocol(ScanFrontend)
Note: See TracBrowser for help on using the repository browser.