def runcmd(cmd): print cmd sts, output = commands.getstatusoutput(cmd) if sts or output: if not output: output = 'Exit status ' + `sts` stdwin.message(output)
def runcmd(cmd): print cmd sts, output = commands.getstatusoutput(cmd) if sts or output: if not output: output = "Exit status " + ` sts ` stdwin.message(output)
def mainloop(): while windows: event = stdwin.getevent() if event[1] in windows: try: event[1].dispatch(event) except KeyboardInterrupt: # The user can type Control-C (or whatever) # to leave the browser without closing # the window. Mainly useful for # debugging. break except: # During debugging, it was annoying if # every mistake in a callback caused the # whole browser to crash, hence this # handler. In a production version # it may be better to disable this. # msg = sys.exc_type if sys.exc_value: val = sys.exc_value if type(val) <> type(''): val = `val` msg = msg + ': ' + val msg = 'Oops, an exception occurred: ' + msg event = None stdwin.message(msg) event = None
def getselection(w): icol, irow = w.selection if 0 <= icol < len(w.data): if 0 <= irow < len(w.data[icol]): return w.data[icol][irow][0] stdwin.message('no selection') return ''
def mainloop(): while windows: event = stdwin.getevent() if event[1] in windows: try: event[1].dispatch(event) except KeyboardInterrupt: # The user can type Control-C (or whatever) # to leave the browser without closing # the window. Mainly useful for # debugging. break except: # During debugging, it was annoying if # every mistake in a callback caused the # whole browser to crash, hence this # handler. In a production version # it may be better to disable this. # msg = sys.exc_type if sys.exc_value: val = sys.exc_value if type(val) <> type(''): val = ` val ` msg = msg + ': ' + val msg = 'Oops, an exception occurred: ' + msg event = None stdwin.message(msg) event = None
def getselection(w): icol, irow = w.selection if 0 <= icol < len(w.data): if 0 <= irow < len(w.data[icol]): return w.data[icol][irow][0] stdwin.message("no selection") return ""
def do_close(win): if win.busy: stdwin.message('Can\'t close busy window') return # need to fail if quitting?? win.editor = None # Break circular reference #del win.editmenu # What about the filemenu?? mainloop.unregister(win) win.close()
def anyopen(name): # Open any kind of document, ignore errors try: w = anywin.open(name) except (RuntimeError, os.error): stdwin.message('Can\'t open ' + name) return 0 addstatmenu(w, [name]) return w
def anyopen(name): # Open any kind of document, ignore errors try: w = anywin.open(name) except (RuntimeError, os.error): stdwin.message("Can't open " + name) return 0 addstatmenu(w, [name]) return w
def igoto(win): try: choice = stdwin.askstr('Go to node (full name):', '') except KeyboardInterrupt: return if not choice: stdwin.message('Sorry, Go to has no default') return imove(win, choice)
def timerevent(self): if self.speaker and self.speaker.busy(): self.win.settimer(1) return while 1: if self.loadnextline(): return if not self.loadnextact(): stdwin.message('The END') self.win.close() raise done self.win.change(((0, 0), (WINWIDTH, self.winheight)))
def timerevent(self): if self.speaker and self.speaker.busy(): self.win.settimer(1) return while 1: if self.loadnextline(): return if not self.loadnextact(): stdwin.message('The END') self.win.close() raise done self.win.change(((0,0), (WINWIDTH, self.winheight)))
def imove(win, ref): savetitle = win.gettitle() win.settitle('Looking for ' + ref + '...') # try: file, node, header, menu, footnotes, text = \ icache.get_node(win.file, ref) except NoSuchFile, file: win.settitle(savetitle) stdwin.message(\ 'Sorry, I can\'t find a file named ' + `file` + '.') return
def open_window(filename, title, contents): try: window = stdwin.open(title) except RuntimeError: stdwin.message('cannot open new window') return # Error, forget it window.textobject = window.textcreate((0, 0), window.getwinsize()) window.textobject.settext(contents) window.changed = 0 window.filename = filename fix_textsize(window) windows.append(window)
def open_file(filename): try: fp = open(filename, 'r') except RuntimeError: stdwin.message(filename + ': cannot open') return # Error, forget it try: contents = fp.read() except RuntimeError: stdwin.message(filename + ': read error') return # Error, forget it del fp # Close the file open_window(filename, filename, contents)
def save(self): try: file = stdwin.askfile('Save to file:', '', 1) except KeyboardInterrupt: return file = string.strip(file) if not file: return try: f = open(file, 'w') except IOError, msg: stdwin.message(file + ': ' + msg) return
def save_file(window, filename): try: fp = open(filename, 'w') except RuntimeError: stdwin.message(filename + ': cannot create') return 0 contents = window.textobject.gettext() try: fp.write(contents) except RuntimeError: stdwin.message(filename + ': write error') return 0 return 1
def save_source(self): try: file = stdwin.askfile('Save source to file:', '', 1) except KeyboardInterrupt: return file = string.strip(file) if not file: return try: f = open(file, 'w') f.write(self.cur_data) f.close() except IOError, msg: stdwin.message(file + ': ' + msg)
def save_hook(self): if not G.data: stdwin.fleep() else: prompt = 'Store sampled data on file: ' try: G.savefile = stdwin.askfile(prompt, G.savefile, 1) except KeyboardInterrupt: return try: fp = open(G.savefile, 'w') fp.write(Magics[G.rate] + G.data) except: stdwin.message('Cannot create ' + file)
def isearch(win): try: pat = stdwin.askstr('Search pattern:', win.pat) except KeyboardInterrupt: return if not pat: pat = win.pat if not pat: stdwin.message('No previous pattern') return try: cpat = regexp.compile(pat) except regexp.error, msg: stdwin.message('Bad pattern: ' + msg) return
def cp_ba(w, m, item): x = getselection(w) if x: if x[-1:] == '/': x = x[:-1] ax = os.path.join(w.a, x) bx = os.path.join(w.b, x) if os.path.isdir(bx): if os.path.exists(ax): m = 'Can\'t copy directory to existing target' stdwin.message(m) return runcmd('cp -r' + mkarg(bx) + mkarg(w.a)) else: runcmd('cp' + mk2arg(w.b, x) + mkarg(ax)) update(w)
def mouse_up(self, detail): if self.last_mouse_down: h1, v1 = self.last_mouse_down[0] h2, v2 = detail[0] long1 = self.cur_backend.whereis(stdwin, h1, v1) long2 = self.cur_backend.whereis(stdwin, h2, v2) if not long1 or not long2: return long1, long2 = self.roundpositions(long1, long2) self.cur_backend.setselection((long1, long2)) # selection = self.cur_backend.extractpart(long1, long2) if not selection: return if not self.window.setselection(WS_PRIMARY, selection): # Meaning some other application got it now stdwin.fleep() return stdwin.rotatecutbuffers(1) stdwin.setcutbuffer(0, selection) return h, v = detail[0] hits = self.cur_backend.hitcheck(h, v) if not hits: return if len(hits) > 1: stdwin.message('Please click in exactly one anchor') return id = hits[0] if 1 <= id <= len(self.cur_anchors): addr = self.cur_anchors[id-1] name = self.cur_anchornames[id-1] type = self.cur_anchortypes[id-1] button = detail[2] if button == 2: if name: msg = 'NAME="' + name + '" ' else: msg = '' if addr: msg = msg + 'HREF="' + addr + '"' stdwin.message(msg) elif addr[:7] == 'telnet:': self.telnet(addr) elif button == 3 and addr and addr[0] <> '#': addr = self.full_addr(addr) w = self.new() history = self.history + [self.cur_addr] if not w.setaddr(addr): w.close() stdwin.message(addr + ': ' + \ self.last_msg) else: w.set_history(history) else: self.follow(addr) else: stdwin.message('Strange - bad anchor id???')
def mouse_up(self, detail): if self.last_mouse_down: h1, v1 = self.last_mouse_down[0] h2, v2 = detail[0] long1 = self.cur_backend.whereis(stdwin, h1, v1) long2 = self.cur_backend.whereis(stdwin, h2, v2) if not long1 or not long2: return long1, long2 = self.roundpositions(long1, long2) self.cur_backend.setselection((long1, long2)) # selection = self.cur_backend.extractpart(long1, long2) if not selection: return if not self.window.setselection(WS_PRIMARY, selection): # Meaning some other application got it now stdwin.fleep() return stdwin.rotatecutbuffers(1) stdwin.setcutbuffer(0, selection) return h, v = detail[0] hits = self.cur_backend.hitcheck(h, v) if not hits: return if len(hits) > 1: stdwin.message('Please click in exactly one anchor') return id = hits[0] if 1 <= id <= len(self.cur_anchors): addr = self.cur_anchors[id - 1] name = self.cur_anchornames[id - 1] type = self.cur_anchortypes[id - 1] button = detail[2] if button == 2: if name: msg = 'NAME="' + name + '" ' else: msg = '' if addr: msg = msg + 'HREF="' + addr + '"' stdwin.message(msg) elif addr[:7] == 'telnet:': self.telnet(addr) elif button == 3 and addr and addr[0] <> '#': addr = self.full_addr(addr) w = self.new() history = self.history + [self.cur_addr] if not w.setaddr(addr): w.close() stdwin.message(addr + ': ' + \ self.last_msg) else: w.set_history(history) else: self.follow(addr) else: stdwin.message('Strange - bad anchor id???')
def cp_ab(w, m, item): x = getselection(w) if x: if x[-1:] == "/": x = x[:-1] ax = os.path.join(w.a, x) bx = os.path.join(w.b, x) if os.path.isdir(ax): if os.path.exists(bx): m = "Can't copy directory to existing target" stdwin.message(m) return runcmd("cp -r" + mkarg(ax) + mkarg(w.b)) else: runcmd("cp" + mkarg(ax) + mk2arg(w.b, x)) update(w)
def mouse_down(self, detail): (h, v), clicks, button, mask = detail if h >= self.leftmargin: srcwin.SourceWindow.dispatch(self, \ (WE_MOUSE_DOWN, self.win, detail)) return lineno = v/self.lineheight + 1 if 1 <= lineno <= self.linecount: if self.debugger.get_break(self.filename, lineno): f = self.debugger.clear_break else: f = self.debugger.set_break err = f(self.filename, lineno) if err: stdwin.message(err) else: self.changemark(lineno) else: stdwin.fleep()
def revert_dialog(window): if not window.filename: stdwin.message('This window has no file to revert from') return if window.changed: prompt = 'Really read ' + window.filename + ' back from file?' if not stdwin.askync(prompt, 1): return try: fp = open(window.filename, 'r') except RuntimeError: stdwin.message(filename + ': cannot open') return contents = fp.read() del fp # Close the file window.textobject.settext(contents) window.changed = 0 fix_docsize(window)
def find(self, pat): import regex global last_regex if not pat: if last_regex: prog, pat = last_regex else: prog, pat = None, '' if not prog: stdwin.message('No previous regexp') return else: try: prog = regex.compile(string.lower(pat)) except regex.error, msg: if type(msg) <> type(''): msg = ` msg ` stdwin.message(msg) return last_regex = prog, pat
def find(self, pat): import regex global last_regex if not pat: if last_regex: prog, pat = last_regex else: prog, pat = None, '' if not prog: stdwin.message('No previous regexp') return else: try: prog = regex.compile(string.lower(pat)) except regex.error, msg: if type(msg) <> type(''): msg = `msg` stdwin.message(msg) return last_regex = prog, pat
def ichoice(win, prompt, list, default): if not list: stdwin.fleep() return if not default: topic, ref = list[0] default = topic try: choice = stdwin.askstr(prompt, default) except KeyboardInterrupt: return if not choice: return choice = string.lower(choice) n = len(choice) for topic, ref in list: topic = string.lower(topic) if topic[:n] == choice: imove(win, ref) return stdwin.message('Sorry, no topic matches ' + `choice`)
def save_file(window, text, filename): # # Open the file for writing, handling exceptions # try: fp = open(filename, 'w') except RuntimeError: stdwin.message('Cannot create ' + filename) return 0 # # Get the contents of the text object as one very long string # contents = text.gettext() # # Write the contents to the file # fp.write(contents) # # The file is automatically closed when this routine returns # return 1
def followok(self, addr, hist, warn): # Check for empty address if not addr: return 1 # We're already here # Check if there's just an anchor if addr[0] == '#': anchor = addr[1:] if anchor not in self.cur_anchornames: if warn: stdwin.fleep() # Anchor not found return 0 id = 1 + self.cur_anchornames.index(anchor) self.cur_backend.showanchor(id) return 1 # Set the address, bail out if we can't parent = self.cur_addr if not self.setaddr(addr): if warn: stdwin.message(addr + ' :' + self.last_msg) return 0 # Fix the exits in the places directory exits = places[parent][1] if self.cur_addr in exits: exits.remove(self.cur_addr) exits.append(self.cur_addr) # Fix the history if hist == H_NOP: pass elif hist == H_POP: if self.history and self.history[-1] == self.cur_addr: del self.history[-1] elif hist == H_PUSH: if parent: self.history.append(parent) else: print 'Strange hist:', hist self.make_history_menu() return 1
# Pass this program the Holy Grail script on stdin.
def main(): vt = vt100win.VT100win() # host = 'biefstuk.cwi.nl' tn = telnetlib.Telnet(host, 0) # try: vt.send(tn.read_until('login: '******'cwilib\r') # vt.send(tn.read_until('Hit <RETURN> to continue...', 10)) tn.write('\r') # vt.send(tn.read_until('QUIT', 20)) except EOFError: sys.stderr.write('Connection closed prematurely\n') sys.exit(1) # define_screens(vt) matches = vt.which_screens() if 'menu' not in matches: sys.stderr.write('Main menu does not appear\n') sys.exit(1) # tn.write('\r\r') vt.open('Progress -- CWI Library') vt.set_debuglevel(0) ui = UserInterface() # while 1: try: data = tn.read_very_eager() except EOFError: stdwin.message('Connection closed--goodbye') break if data: print 'send...' vt.send(data) print 'send...done' continue event = stdwin.pollevent() if event: type, window, detail = event if window == None and type == WE_LOST_SEL: window = ui.queryform.window event = type, window, detail if type == WE_CLOSE: break if window in ui.windows: ui.dispatch(type, window, detail) elif window == vt.window: if type == WE_NULL: pass elif type == WE_COMMAND: if detail == WC_RETURN: tn.write('\r') elif detail == WC_BACKSPACE: tn.write('\b') elif detail == WC_TAB: tn.write('\t') elif detail == WC_UP: tn.write('\033[A') elif detail == WC_DOWN: tn.write('\033[B') elif detail == WC_RIGHT: tn.write('\033[C') elif detail == WC_LEFT: tn.write('\033[D') else: print '*** Command:', detail elif type == WE_CHAR: tn.write(detail) elif type == WE_DRAW: vt.draw(detail) elif type in (WE_ACTIVATE, WE_DEACTIVATE): pass else: print '*** VT100 event:', type, detail else: print '*** Alien event:', type, window, detail continue rfd, wfd, xfd = select.select([tn, stdwin], [], [])
try: f = open(file, 'w') except IOError, msg: stdwin.message(file + ': ' + msg) return self.window.setwincursor(WAITCURSOR) fmtr = fmt.WritingFormatter(f, 72) parser = htmllib.FormattingParser(fmtr, \ htmllib.NullStylesheet) try: parser.feed(self.cur_data) parser.close() f.write('\n') f.close() except IOError, msg: stdwin.message(file + ': ' + msg) self.window.setwincursor(READYCURSOR) # def save_source(self): try: file = stdwin.askfile('Save source to file:', '', 1) except KeyboardInterrupt: return file = string.strip(file) if not file: return try: f = open(file, 'w') f.write(self.cur_data) f.close() except IOError, msg:
def stataction(w, m, item): # Menu item action for stat menu file = m.files[item] try: m.setitem(item, commands.getstatus(file)) except os.error: stdwin.message('Can\'t get status for ' + file)
def message(msg): stdwin.message(msg)
try: f = open(file, 'w') except IOError, msg: stdwin.message(file + ': ' + msg) return self.window.setwincursor(WAITCURSOR) fmtr = fmt.WritingFormatter(f, 72) parser = htmllib.FormattingParser(fmtr, \ htmllib.NullStylesheet) try: parser.feed(self.cur_data) parser.close() f.write('\n') f.close() except IOError, msg: stdwin.message(file + ': ' + msg) self.window.setwincursor(READYCURSOR) # def save_source(self): try: file = stdwin.askfile('Save source to file:', '', 1) except KeyboardInterrupt: return file = string.strip(file) if not file: return try: f = open(file, 'w') f.write(self.cur_data) f.close()
def do_exec(win): if win.busy: if win not in inputwindows: stdwin.message('Can\'t run recursive commands') return if win <> inputwindows[0]: stdwin.message('Please complete recursive input first') return # # Set text to the string to execute. a, b = win.editor.getfocus() alltext = win.editor.gettext() n = len(alltext) if a == b: # There is no selected text, just an insert point; # so execute the current line. while 0 < a and alltext[a - 1] <> '\n': # Find beginning of line a = a - 1 while b < n and alltext[b] <> '\n': # Find end of line after b b = b + 1 text = alltext[a:b] + '\n' else: # Execute exactly the selected text. text = win.editor.getfocustext() if text[-1:] <> '\n': # Make sure text ends with \n text = text + '\n' while b < n and alltext[b] <> '\n': # Find end of line after b b = b + 1 # # Set the focus to expect the output, since there is always something. # Output will be inserted at end of line after current focus, # or appended to the end of the text. b = [n, b][win.insertOutput] win.editor.setfocus(b, b) # # Make sure there is a preceeding newline. if alltext[b - 1:b] <> '\n': win.editor.replace('\n') # # if win.busy: # Send it to raw_input() below raise InputAvailable, text # # Like the real Python interpreter, we want to execute # single-line commands immediately, but save multi-line # commands until they are terminated by a blank line. # Unlike the real Python interpreter, we don't do any syntax # checking while saving up parts of a multi-line command. # # The current heuristic to determine whether a command is # the first line of a multi-line command simply checks whether # the command ends in a colon (followed by a newline). # This is not very robust (comments and continuations will # confuse it), but it is usable, and simple to implement. # (It even has the advantage that single-line loops etc. # don't need te be terminated by a blank line.) # if win.command: # Already continuing win.command = win.command + text if win.command[-2:] <> '\n\n': win.settitle('Unfinished command...') return # Need more... else: # New command win.command = text if text[-2:] == ':\n': win.settitle('Unfinished command...') return command = win.command win.command = '' win.settitle('Executing command...') # # Some hacks: # - The standard files are replaced by an IOWindow instance. # - A 2nd argument to exec() is used to specify the directory # holding the user's global variables. (If this wasn't done, # the exec would be executed in the current local environment, # and the user's assignments to globals would be lost...) # save_stdin = sys.stdin save_stdout = sys.stdout save_stderr = sys.stderr try: sys.stdin = sys.stdout = sys.stderr = IOWindow(win) win.busy = 1 try: exec(command, win.globals) except KeyboardInterrupt: print '[Interrupt]' except: if type(sys.exc_type) == type(''): msg = sys.exc_type else: msg = sys.exc_type.__name__ if sys.exc_value <> None: msg = msg + ': ' + ` sys.exc_value ` if win.insertError: stdwin.fleep() replace(win, msg + '\n') else: win.settitle('Unhandled exception') stdwin.message(msg) finally: # Restore redirected I/O in *all* cases win.busy = 0 sys.stderr = save_stderr sys.stdout = save_stdout sys.stdin = save_stdin settitle(win)
# def imove(win, ref): savetitle = win.gettitle() win.settitle('Looking for ' + ref + '...') # try: file, node, header, menu, footnotes, text = \ icache.get_node(win.file, ref) except NoSuchFile, file: win.settitle(savetitle) stdwin.message(\ 'Sorry, I can\'t find a file named ' + `file` + '.') return except NoSuchNode, node: win.settitle(savetitle) stdwin.message(\ 'Sorry, I can\'t find a node named ' + `node` + '.') return # win.settitle('Found (' + file + ')' + node + '...') # if win.file and win.node: lastnode = '(' + win.file + ')' + win.node win.last.append(lastnode, win.textobj.getfocus()) win.file = file win.node = node win.header = header win.menu = menu win.footnotes = footnotes win.text = text #
def stataction(w, m, item): # Menu item action for stat menu file = m.files[item] try: m.setitem(item, commands.getstatus(file)) except os.error: stdwin.message("Can't get status for " + file)