def _handleError(self, err): title = constants.ERROR if isinstance(err, socket.error): errMessage = err.strerror + "\nMake sure PVS is running and the port is set correctly" title = "PVS Communication Error" elif isinstance(err, httplib.BadStatusLine): errMessage = err.message elif isinstance(err, exceptions.ValueError): errMessage = err.message title = "JSON Parse Error" elif isinstance(err, util.PVSException): data = err.errorObject[PVSCommunicator.DATA] if data is not None: title = err.message errMessage = err.errorObject[PVSCommunicator.DATA] else: errMessage = err.message if PVSCommunicator.BEGIN in err.errorObject: begin = err.errorObject[PVSCommunicator.BEGIN] end = err.errorObject[PVSCommunicator.END] if PVSCommunicator.END in err.errorObject else None pub.sendMessage(constants.PUB_ERRORLOCATION, begin=begin, end=end) elif isinstance(err, Exception): logging.debug("Unknown Exception: %s", err) errMessage = str(err) else: logging.debug("Unknown Thrown Object: %s", err) errMessage = str(err) logging.error("Error: %s", errMessage) util.getMainFrame().showError(errMessage, title)
def _handleError(self, err): title = constants.ERROR if isinstance(err, socket.error): errMessage = err.strerror + "\nMake sure PVS is running and the port is set correctly" title = "PVS Communication Error" elif isinstance(err, httplib.BadStatusLine): errMessage = err.message elif isinstance(err, exceptions.ValueError): errMessage = err.message title = "JSON Parse Error" elif isinstance(err, util.PVSException): data = err.errorObject[PVSCommunicator.DATA] if data is not None: title = err.message errMessage = err.errorObject[PVSCommunicator.DATA] else: errMessage = err.message if PVSCommunicator.BEGIN in err.errorObject: begin = err.errorObject[PVSCommunicator.BEGIN] end = err.errorObject[ PVSCommunicator. END] if PVSCommunicator.END in err.errorObject else None pub.sendMessage(constants.PUB_ERRORLOCATION, begin=begin, end=end) elif isinstance(err, Exception): logging.debug("Unknown Exception: %s", err) errMessage = str(err) else: logging.debug("Unknown Thrown Object: %s", err) errMessage = str(err) logging.error("Error: %s", errMessage) util.getMainFrame().showError(errMessage, title)
def start(self): parsedURL = urlparse(self.ideURL) host = parsedURL.hostname port = parsedURL.port try: self.guiServer = SimpleXMLRPCServer((host, port), requestHandler=RequestHandler) self.guiServer.register_function(self.onPVSMessageReceived, PVSCommunicator.REQUEST) self.serverThread = threading.Thread( target=self.guiServer.serve_forever, name='XmlRpcThread') self.threadEvent = threading.Event() self.serverThread.start() except Exception as e: logging.error("Error starting the xmlrpc server: %s", e) util.getMainFrame().showError( "You may be running another instance of this application", "Error Starting the XMLRPC Server") try: self.pvsProxy = xmlrpclib.ServerProxy(self.pvsURL) except Exception as e: logging.error("Error starting the server proxy: %s", e) util.getMainFrame().showError( "Cannot start the server proxy for PVS", "Error Starting Server Proxy")
def parse(self, fullname=None): fullname = self._ensureFilenameIsIknown(fullname) directory = os.path.split(fullname)[0] if directory != self.pvsContext: util.getMainFrame().showError("%s is not in the active context"%fullname) return None else: name = os.path.basename(fullname) name = os.path.splitext(name)[0] # just get the filename without the extension pub.sendMessage(constants.PUB_FILEPARSING, fullname=fullname) self._sendCommand("parse", name)
def typecheck(self, fullname=None): fullname = self._ensureFilenameIsIknown(fullname) directory = os.path.split(fullname)[0] if directory != self.pvsContext: util.getMainFrame().showError("%s is not in the active context"%fullname) return None else: name = os.path.basename(fullname) name = util.getFilenameFromFullPath(fullname, False) pub.sendMessage(constants.PUB_FILEPARSING, fullname=fullname) self._sendCommand("typecheck", name, resultfn=lambda r: self.typecheckResult(r, fullname))
def parse(self, fullname=None): fullname = self._ensureFilenameIsIknown(fullname) directory = os.path.split(fullname)[0] if directory != self.pvsContext: util.getMainFrame().showError("%s is not in the active context" % fullname) return None else: name = os.path.basename(fullname) name = os.path.splitext(name)[ 0] # just get the filename without the extension pub.sendMessage(constants.PUB_FILEPARSING, fullname=fullname) self._sendCommand("parse", name)
def typecheck(self, fullname=None): fullname = self._ensureFilenameIsIknown(fullname) directory = os.path.split(fullname)[0] if directory != self.pvsContext: util.getMainFrame().showError("%s is not in the active context" % fullname) return None else: name = os.path.basename(fullname) name = util.getFilenameFromFullPath(fullname, False) pub.sendMessage(constants.PUB_FILEPARSING, fullname=fullname) self._sendCommand( "typecheck", name, resultfn=lambda r: self.typecheckResult(r, fullname))
def create(self, pluginDefinition): name = pluginDefinition[PluginManager.NAME] module = importlib.import_module(pluginDefinition[PluginManager.MODULE]) panelClass = getattr(module, pluginDefinition[PluginManager.CLASS]) size = pluginDefinition[PluginManager.SIZE] panel = panelClass(util.getMainFrame(), pluginDefinition) location = pluginDefinition[PluginManager.LOCATION] if PluginManager.LOCATION in pluginDefinition else PluginManager.FLOAT auiManager = util.auiManager() paneInfo = aui.AuiPaneInfo() paneInfo = paneInfo.Caption(name).Name(name).BestSize(size) if location == PluginManager.TOP: paneInfo = paneInfo.Top() elif location == PluginManager.BOTTOM: paneInfo = paneInfo.Bottom() elif location == PluginManager.LEFT: paneInfo = paneInfo.Left() elif location == PluginManager.RIGHT: paneInfo = paneInfo.Right() elif location == PluginManager.FLOAT: paneInfo = paneInfo.Float() elif location == PluginManager.CENTER: paneInfo = paneInfo.Center() else: logging.error("Unknown Location: %s", location) paneInfo = paneInfo.Float() auiManager.AddPane(panel, paneInfo) if PluginManager.VISIBLE in pluginDefinition: self.showPlugin(name, pvscomm.PVSCommandManager().pvsMode in pluginDefinition[PluginManager.VISIBLE]) else: self.showPlugin(name, False) auiManager.Update() pub.sendMessage(PUB_ADDITEMTOVIEWMENU, name=name, callBackFunction=(lambda ce: self.togglePluginVisibility(name))) return None
def onChangeContext(event): """called to handle 'change context' request""" frame = util.getMainFrame() preferences = preference.Preferences() newContext = frame.chooseDirectory("Select a directory", preferences.getRecentContexts()[0]) if newContext is not None: pvscomm.PVSCommandManager().changeContext(newContext)
def _process_dialog(self, *parameters): logging.debug("Parameters %s", (parameters,)) question = parameters[0].strip() frame = util.getMainFrame() defaultName = parameters[1].strip() if len(parameters)>1 else constants.EMPTY_STRING frame.showMessage("This is not implemented yet...Using the default name") #result = frame.askForText(question, constants.EMPTY_STRING, defaultName, True) return defaultName
def _process_yes_no(self, *parameters): logging.debug("Parameters %s", (parameters,)) frame = util.getMainFrame() question = parameters[0].strip() answer = frame.askYesNoQuestion(question) result = "yes" if answer==wx.ID_YES else "no" return result
def showRichEditorForFile(self, fullname): logging.info("Showing richEditor for %s", fullname) richEditor = self[fullname] frame = self._getWidgetFrame(richEditor) if frame == util.getMainFrame(): self.notebook.SetSelection(self._getPageIndex(richEditor)) else: frame.Raise()
def getFocusedRichEditor(self): focus = wx.Window.FindFocus() focus = self._getWidgetFrame(focus) if "richEditor" in focus.__dict__: return focus.richEditor # A Floating Frame elif focus == util.getMainFrame(): return self._getSelectedPage() return None
def _process_yes_no(self, *parameters): logging.debug("Parameters %s", (parameters, )) frame = util.getMainFrame() question = parameters[0].strip() answer = frame.askYesNoQuestion(question) result = "yes" if answer == wx.ID_YES else "no" return result
def addFile(self, fullname): opened = True if not fullname in self.editors: opened = False logging.info("Opening a new editor tab for %s", fullname) editor = ui.rchedtr.RichEditor(self.notebook, wx.ID_ANY, fullname) self.notebook.AddPage(editor, util.getFilenameFromFullPath(fullname), True, self.getProperBitmap()) if not os.path.exists(fullname): f = open(fullname, "w") f.close() if editor.styledText.readFile(fullname): editor.styledText.SetSelection(0, 0) self[fullname] = editor opened = True if opened: self.showRichEditorForFile(fullname) else: util.getMainFrame().showError("Could not open %s"%fullname)
def addPluginToViewMenu(self, name, callBackFunction): logging.debug("Name: %s", name) frame = util.getMainFrame() item = self.pluginMenu.Append(wx.ID_ANY, name, EMPTY_STRING, wx.ITEM_CHECK) self.plugins[name] = item self.pluginMenu.Check( item.GetId(), PluginManager().shouldPluginBeVisible(name, pvscomm.PVSCommandManager().pvsMode) ) frame.Bind(wx.EVT_MENU, callBackFunction, item)
def __init__(self,): wx.Frame.__init__(self, util.getMainFrame(), wx.ID_ANY) mainSizer = wx.BoxSizer(wx.VERTICAL) self.SetTitle("PVS GUI Help") help = wx.html.HtmlWindow(self, wx.ID_ANY, style=wx.NO_BORDER) helpFile = os.path.join(config.PVSIDEConfiguration().applicationFolder, "src", "help.html") mainSizer.Add(help, 1, wx.EXPAND, 5) self.SetSizer(mainSizer) help.LoadPage(helpFile) self.SetSize((500, 600))
def _process_dialog(self, *parameters): logging.debug("Parameters %s", (parameters, )) question = parameters[0].strip() frame = util.getMainFrame() defaultName = parameters[1].strip( ) if len(parameters) > 1 else constants.EMPTY_STRING frame.showMessage( "This is not implemented yet...Using the default name") #result = frame.askForText(question, constants.EMPTY_STRING, defaultName, True) return defaultName
def findText(self): #TODO: RichEditor should have an API for finding and replacing text. frame = util.getMainFrame() _find = self.data.GetFindString() logging.info("Find Next %s", _find) page = remgr.RichEditorManager().getFocusedRichEditor() nextOne = self.findPositionOfNext(_find) if nextOne is not None: page.styledText.SetSelection(nextOne, nextOne + len(_find)) else: frame.showMessage("No more occurrences of '%s' was found"%_find)
def __init__(self, parent, definition): PluginPanel.__init__(self, parent, definition) self.sequent = None self.initializeCommandList() self.history = [] splitter = wx.SplitterWindow(self, style = wx.SP_NOBORDER) splitter.SetMinimumPaneSize(70) mainSizer = wx.BoxSizer(wx.VERTICAL) toolbar = wx.ToolBar(self, wx.ID_ANY, style=wx.TB_HORIZONTAL) # | wx.NO_BORDER) lb = wx.ComboBox(toolbar, wx.ID_ANY, pos=(50, 170), size=(150, -1), choices=self.commandList, style=wx.CB_READONLY) lb.SetToolTipString("My List of Commands") toolbar.AddControl(lb) undoButton = toolbar.AddTool(wx.ID_ANY, ui.images.getBitmap('undo.gif'), shortHelpString="Undo the last command") postponeButton = toolbar.AddTool(wx.ID_ANY, ui.images.getBitmap('rightarrow.png'), shortHelpString="Postpone the current subgoal") commentaryButton = toolbar.AddTool(wx.ID_ANY, ui.images.getBitmap('commentary.png'), shortHelpString="Display the commentary box") toolbar.AddSeparator() quitButton = toolbar.AddTool(wx.ID_ANY, ui.images.getBitmap('quit.png'), shortHelpString="Quit the prover") mainSizer.Add(toolbar) self.outputTextCtrl = wx.TextCtrl(splitter, wx.ID_ANY, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH | wx.TE_RICH2) bottomPanel = wx.Panel(splitter) bottomSizer = wx.BoxSizer(wx.VERTICAL) horizontalSizer = wx.BoxSizer(wx.HORIZONTAL) self.historyBox = wx.ComboBox(bottomPanel, wx.ID_ANY, choices=["history"], style=wx.CB_READONLY) self.commandTextControl = wx.TextCtrl(bottomPanel, wx.ID_ANY, "", style=wx.TE_MULTILINE) horizontalSizer.Add(wx.StaticText(bottomPanel, wx.ID_ANY, "Enter Rule:"), 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 0) horizontalSizer.Add(self.historyBox, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 0) bottomSizer.Add(horizontalSizer, 0, wx.ALL | wx.EXPAND, 5) bottomSizer.Add(self.commandTextControl, 1, wx.ALL | wx.EXPAND, 5) self.historyBox.SetSelection(0) bottomPanel.SetSizer(bottomSizer) splitter.SplitHorizontally(self.outputTextCtrl, bottomPanel) splitter.SetSashPosition(300) mainSizer.Add(splitter, 1, wx.ALL | wx.EXPAND, 0) self.SetSizer(mainSizer) toolbar.Realize() self.commentaryDialog = ui.logdlg.PVSCommunicationLogDialog(util.getMainFrame(), "Proof Commentary", constants.COMMENTARYLOG) #self.Bind(wx.EVT_TEXT_ENTER, self.onCommandEntered, self.commandTextControl) self.Bind(wx.EVT_TEXT, self.onCommand, self.commandTextControl) lb.Bind(wx.EVT_COMBOBOX, self.OnSelectCommand) self.historyBox.Bind(wx.EVT_COMBOBOX, self.OnSelectHistory) self.Bind(wx.EVT_TOOL, self.OnUndoLastCommand, undoButton) self.Bind(wx.EVT_TOOL, self.OnPostponeCommand, postponeButton) self.Bind(wx.EVT_TOOL, self.OnCommentaryButtonClicked, commentaryButton) self.Bind(wx.EVT_TOOL, self.OnQuitProver, quitButton) pub.subscribe(self.proofInformationReceived, constants.PUB_PROOFINFORMATIONRECEIVED) self.Layout()
def start(self): parsedURL = urlparse(self.ideURL) host = parsedURL.hostname port = parsedURL.port try: self.guiServer = SimpleXMLRPCServer((host, port), requestHandler=RequestHandler) self.guiServer.register_function(self.onPVSMessageReceived, PVSCommunicator.REQUEST) self.serverThread = threading.Thread(target=self.guiServer.serve_forever, name='XmlRpcThread') self.threadEvent = threading.Event() self.serverThread.start() except Exception as e: logging.error("Error starting the xmlrpc server: %s", e) util.getMainFrame().showError("You may be running another instance of this application", "Error Starting the XMLRPC Server") try: self.pvsProxy = xmlrpclib.ServerProxy(self.pvsURL) except Exception as e: logging.error("Error starting the server proxy: %s", e) util.getMainFrame().showError("Cannot start the server proxy for PVS", "Error Starting Server Proxy")
def addPluginToViewMenu(self, name, callBackFunction): logging.debug("Name: %s", name) frame = util.getMainFrame() item = self.pluginMenu.Append(wx.ID_ANY, name, EMPTY_STRING, wx.ITEM_CHECK) self.plugins[name] = item self.pluginMenu.Check( item.GetId(), PluginManager().shouldPluginBeVisible( name, pvscomm.PVSCommandManager().pvsMode)) frame.Bind(wx.EVT_MENU, callBackFunction, item)
def OnReplace(self, evt): frame = util.getMainFrame() _find = self.data.GetFindString() _replace = self.data.GetReplaceString() logging.info("Replace Next %s", _find) page = remgr.RichEditorManager().getFocusedRichEditor() nextOne = self.findPositionOfNext(_find) if nextOne is not None: page.styledText.SetSelection(nextOne, nextOne + len(_find)) page.styledText.ReplaceSelection(_replace) else: frame.showMessage("No more occurrences of '%s' was found"%_find)
def onPVSMessageReceived(self, jsonString): """ Process a request from PVS An XML-RPC request presumably from PVS - typically a JSON-RPC message without id. This always returns a value at the XML-RPC level. If the JSON-RPC message cannot be parsed, or some other problem happens at the XML-RPC level, then it returns an error string. If the JSON-RPC message is parsed, but doesn't include an id, then if an error occurs it is returned as a string. If no id and no error, "null" is returned. Otherwise, a valid JSON-RPC response/error form is returned. """ logging.debug("Received: %s", jsonString) try: message = json.loads(jsonString) self._validateJSON(message) lg = PVSCommunicationLogger() lg.log(constants.JSONLOG, "<= %s\n" % (message, )) evt = PVSRequestEvent() evt.message = message evt.threadEvent = self.threadEvent evt.threadEvent.clear() try: # calls processEvent mframe = util.getMainFrame() #mframe.Bind(EVT_REQUEST_FROM_PVS, mframe.processEvent) wx.PostEvent(mframe, evt) import time time.sleep(0) evt.threadEvent.wait() except Exception as err: lg.log(constants.JSONLOG, "PostEvent error: {0}".format(err)) result = evt.result # result = self.processMessage(message) logging.debug("Sending Back: %s", result) self._validateJSON(result) lg.log(constants.JSONLOG, "=> %s\n" % (result, )) return result #TODO: The return vlaues for errors should be different and json-based except TypeError as err: return 'request: {0} is of type {1}, string expected'.format( jsonString, type(jsonString)) except ValueError as err: return 'request: {0} is invalid - {1}'.format(jsonString, err) except util.XMLRPCException as err: # Can't give normal JSON-RPC error response, # This is just an XML-RPC answer. return 'request: {0} is invalid - {1}'.format(jsonString, err) except Exception as err: lg.log(constants.JSONLOG, 'Unknown error: {0}'.format(err)) return "Unknown Error"
def onOpenFile(event): """called to handle 'open file' request""" logging.debug("Starting") frame = util.getMainFrame() filters = "PVS files (*" + PVS_EXTENSION + ")|*" + PVS_EXTENSION dialog = wx.FileDialog (frame, "Open PVS file", wildcard = filters, style = wx.OPEN ) if dialog.ShowModal() == wx.ID_OK: fullname = dialog.GetPath() logging.info("Opening file %s", fullname) util.openFile(fullname) else: logging.info("Nothing was selected.") dialog.Destroy()
def onPVSMessageReceived(self, jsonString): """ Process a request from PVS An XML-RPC request presumably from PVS - typically a JSON-RPC message without id. This always returns a value at the XML-RPC level. If the JSON-RPC message cannot be parsed, or some other problem happens at the XML-RPC level, then it returns an error string. If the JSON-RPC message is parsed, but doesn't include an id, then if an error occurs it is returned as a string. If no id and no error, "null" is returned. Otherwise, a valid JSON-RPC response/error form is returned. """ logging.debug("Received: %s", jsonString) try: message = json.loads(jsonString) self._validateJSON(message) lg = PVSCommunicationLogger() lg.log(constants.JSONLOG, "<= %s\n"%(message,)) evt = PVSRequestEvent() evt.message = message evt.threadEvent = self.threadEvent evt.threadEvent.clear() try: # calls processEvent mframe = util.getMainFrame() #mframe.Bind(EVT_REQUEST_FROM_PVS, mframe.processEvent) wx.PostEvent(mframe, evt) import time time.sleep(0) evt.threadEvent.wait() except Exception as err: lg.log(constants.JSONLOG, "PostEvent error: {0}".format(err)) result = evt.result # result = self.processMessage(message) logging.debug("Sending Back: %s", result) self._validateJSON(result) lg.log(constants.JSONLOG, "=> %s\n"%(result,)) return result #TODO: The return vlaues for errors should be different and json-based except TypeError as err: return 'request: {0} is of type {1}, string expected'.format(jsonString, type(jsonString)) except ValueError as err: return 'request: {0} is invalid - {1}'.format(jsonString, err) except util.XMLRPCException as err: # Can't give normal JSON-RPC error response, # This is just an XML-RPC answer. return 'request: {0} is invalid - {1}'.format(jsonString, err) except Exception as err: lg.log(constants.JSONLOG, 'Unknown error: {0}'.format(err)) return "Unknown Error"
def _sendCommandPVS(self, *args, **keywords): method = args[0] params = args[1:] if 'resultfn' in keywords: resultfn = keywords['resultfn'] del keywords['resultfn'] else: resultfn = None evt = PVSResponseEvent() try: silent = keywords[PVSCommunicator.SILENT] if PVSCommunicator.SILENT in keywords else False # Spawn a new thread, allowing the WX thread to go back to the main loop. # Note that _sendCommand does not directly return a result. jsonResult = self.pvsComm.requestPVS(method, *params) pvsMode = jsonResult[PVSCommunicator.MODE] evt.pvsmode = pvsMode evt.context = util.normalizePath(jsonResult[PVSCommunicator.CONTEXT]) if PVSCommunicator.XMLRPCERROR in jsonResult: errorObj = jsonResult[PVSCommunicator.XMLRPCERROR] errorObject = {} if isinstance(errorObj, str) or isinstance(errorObj, unicode): logging.error("jsonResult[xmlrpc_error] should be a dictionary and not a string") errorObject[PVSCommunicator.CODE] = -100 errorObject[PVSCommunicator.MESSAGE] = errorObj errorObject[PVSCommunicator.DATA] = None else: errorObject[PVSCommunicator.CODE] = int(errorObj[PVSCommunicator.CODE]) errorObject[PVSCommunicator.MESSAGE] = errorObj[PVSCommunicator.MESSAGE] errorObject[PVSCommunicator.DATA] = errorObj[PVSCommunicator.DATA] if PVSCommunicator.DATA in errorObj else None raise util.PVSException(message=errorObject[PVSCommunicator.MESSAGE], errorObject=errorObject) result = jsonResult[PVSCommunicator.JSONRPCRESULT] if isinstance(result, str) or isinstance(result, unicode): result2 = json.loads(result) #TODO: Keep this for a while, but remove the if statement later if you never get an assertion error. #assert (result2 == result), "result '%s' is a json object inside a string"%result if result2 != result: logging.error("result '%s' should not be a string here, but an object", result) result = result2 if PVSCommunicator.ERROR in result: errDict = result[PVSCommunicator.ERROR] errorObject = self._processJSONErrorObject(errDict) raise util.PVSException(message=errorObject[PVSCommunicator.MESSAGE], errorObject=errorObject) evt.result = result[PVSCommunicator.RESULT] evt.resultfn = resultfn wx.PostEvent(util.getMainFrame(), evt) except Exception as err: # import traceback # traceback.print_stack() if not silent: self._handleError(err)
def onCreateNewFile(event): """called to handle 'create new file' request""" logging.debug("Starting") frame = util.getMainFrame() filters = "PVS files (*" + PVS_EXTENSION + ")|*" + PVS_EXTENSION dialog = wx.FileDialog (frame, "Create a new PVS file", wildcard = filters, style = wx.SAVE | wx.OVERWRITE_PROMPT ) if dialog.ShowModal() == wx.ID_OK: fullname = dialog.GetPath() if not fullname.endswith(PVS_EXTENSION): fullname = fullname + PVS_EXTENSION logging.info("Creating new file %s", fullname) util.openFile(fullname) else: logging.info("Nothing was selected.") dialog.Destroy()
def onOpenFile(event): """called to handle 'open file' request""" logging.debug("Starting") frame = util.getMainFrame() filters = "PVS files (*" + PVS_EXTENSION + ")|*" + PVS_EXTENSION dialog = wx.FileDialog(frame, "Open PVS file", wildcard=filters, style=wx.OPEN) if dialog.ShowModal() == wx.ID_OK: fullname = dialog.GetPath() logging.info("Opening file %s", fullname) util.openFile(fullname) else: logging.info("Nothing was selected.") dialog.Destroy()
def prepareRecentContextsSubMenu(self): try: while True: # TODO: Find out if there is a better way to remove all the items from a menu item = self.recentContextsMenu.FindItemByPosition(0) self.recentContextsMenu.RemoveItem(item) except: pass self._recentContexts = {} preferences = Preferences() recentContexts = preferences.getRecentContexts() logging.debug("Recent Contexts: %s", recentContexts) frame = util.getMainFrame() for cxt in recentContexts: item = self.recentContextsMenu.Append(wx.ID_ANY, cxt, EMPTY_STRING, wx.ITEM_NORMAL) self._recentContexts[item.GetId()] = cxt frame.Bind(wx.EVT_MENU, self.onRecentContextSelected, item)
def onFindText(event): """called to handle 'find text' request""" logging.debug("Starting") #TODO: Fix Find/Replace in a good manner. focus = util.getMainFrame().FindFocus() #page = remgr.RichEditorManager().getFocusedRichEditor() if focus is not None and (isinstance(focus, wx.TextCtrl) or isinstance(focus, stc.StyledTextCtrl)): pass else: focus = remgr.RichEditorManager().getFocusedRichEditor() if focus is not None: focus = focus.styledText if focus is not None: selected = focus.GetSelectedText() if selected is None: selected = "" FindReplaceManager(selected, EMPTY_STRING).show()
def onSaveAsFile(event): """save the active file (an active file is one whose tab is visible)""" logging.debug("Starting") frame = util.getMainFrame() filters = "PVS files (*" + PVS_EXTENSION + ")|*" + PVS_EXTENSION dialog = wx.FileDialog (frame, "Save File As...", wildcard = filters, style = wx.SAVE | wx.OVERWRITE_PROMPT ) if dialog.ShowModal() == wx.ID_OK: fullname = dialog.GetPath() if not fullname.endswith(PVS_EXTENSION): fullname = fullname + PVS_EXTENSION logging.info("Saving file as %s", fullname) richEditor = remgr.RichEditorManager().getFocusedRichEditor() if richEditor is not None: richEditor.saveFile(fullname) else: logging.info("Nothing was selected.") dialog.Destroy()
def prepareRecentContextsSubMenu(self): try: while True: #TODO: Find out if there is a better way to remove all the items from a menu item = self.recentContextsMenu.FindItemByPosition(0) self.recentContextsMenu.RemoveItem(item) except: pass self._recentContexts = {} preferences = Preferences() recentContexts = preferences.getRecentContexts() logging.debug("Recent Contexts: %s", recentContexts) frame = util.getMainFrame() for cxt in recentContexts: item = self.recentContextsMenu.Append(wx.ID_ANY, cxt, EMPTY_STRING, wx.ITEM_NORMAL) self._recentContexts[item.GetId()] = cxt frame.Bind(wx.EVT_MENU, self.onRecentContextSelected, item)
def show(self): frame = util.getMainFrame() self.data.SetFindString(self.defaultFindText) self.data.SetReplaceString(self.defaultReplaceText) dlg = wx.FindReplaceDialog(frame, self.data, "Find & Replace", wx.FR_REPLACEDIALOG) dlg.Bind(wx.EVT_FIND, self.OnFind) dlg.Bind(wx.EVT_FIND_NEXT, self.OnFindNext) dlg.Bind(wx.EVT_FIND_REPLACE, self.OnReplace) dlg.Bind(wx.EVT_FIND_REPLACE_ALL, self.OnReplaceAll) dlg.Bind(wx.EVT_FIND_CLOSE, self.OnFindReplaceBoxClose) self.goingDown = False self.wholeWord = False self.matchCase = False p1 = frame.GetPosition() dlg.Show(True) p2 = dlg.GetPosition() p3 = (p2[0], max(5, p1[1]-100)) dlg.SetPosition(p3)
def onCreateNewFile(event): """called to handle 'create new file' request""" logging.debug("Starting") frame = util.getMainFrame() filters = "PVS files (*" + PVS_EXTENSION + ")|*" + PVS_EXTENSION dialog = wx.FileDialog(frame, "Create a new PVS file", wildcard=filters, style=wx.SAVE | wx.OVERWRITE_PROMPT) if dialog.ShowModal() == wx.ID_OK: fullname = dialog.GetPath() if not fullname.endswith(PVS_EXTENSION): fullname = fullname + PVS_EXTENSION logging.info("Creating new file %s", fullname) util.openFile(fullname) else: logging.info("Nothing was selected.") dialog.Destroy()
def removeFile(self, fullname): richEditor = self[fullname] logging.info("Closing RichEditor for %s", fullname) del self[fullname] frame = self._getWidgetFrame(richEditor) if "richEditor" in frame.__dict__: frame.attachRichEditorBackToNotebook = False # Close frame and the editor both frame.Close() return elif frame == util.getMainFrame(): for i in range(self.notebook.GetPageCount()): page = self.notebook.GetPage(i) if fullname == page.getFilename(): self.notebook.DeletePage(i) return logging.warning("Did not find the file %s", fullname) else: logging.error("The code should not reach here for %s", fullname)
def create(self, pluginDefinition): name = pluginDefinition[PluginManager.NAME] module = importlib.import_module( pluginDefinition[PluginManager.MODULE]) panelClass = getattr(module, pluginDefinition[PluginManager.CLASS]) size = pluginDefinition[PluginManager.SIZE] panel = panelClass(util.getMainFrame(), pluginDefinition) location = pluginDefinition[ PluginManager. LOCATION] if PluginManager.LOCATION in pluginDefinition else PluginManager.FLOAT auiManager = util.auiManager() paneInfo = aui.AuiPaneInfo() paneInfo = paneInfo.Caption(name).Name(name).BestSize(size) if location == PluginManager.TOP: paneInfo = paneInfo.Top() elif location == PluginManager.BOTTOM: paneInfo = paneInfo.Bottom() elif location == PluginManager.LEFT: paneInfo = paneInfo.Left() elif location == PluginManager.RIGHT: paneInfo = paneInfo.Right() elif location == PluginManager.FLOAT: paneInfo = paneInfo.Float() elif location == PluginManager.CENTER: paneInfo = paneInfo.Center() else: logging.error("Unknown Location: %s", location) paneInfo = paneInfo.Float() auiManager.AddPane(panel, paneInfo) if PluginManager.VISIBLE in pluginDefinition: self.showPlugin( name, pvscomm.PVSCommandManager().pvsMode in pluginDefinition[PluginManager.VISIBLE]) else: self.showPlugin(name, False) auiManager.Update() pub.sendMessage( PUB_ADDITEMTOVIEWMENU, name=name, callBackFunction=(lambda ce: self.togglePluginVisibility(name))) return None
def onSaveAsFile(event): """save the active file (an active file is one whose tab is visible)""" logging.debug("Starting") frame = util.getMainFrame() filters = "PVS files (*" + PVS_EXTENSION + ")|*" + PVS_EXTENSION dialog = wx.FileDialog(frame, "Save File As...", wildcard=filters, style=wx.SAVE | wx.OVERWRITE_PROMPT) if dialog.ShowModal() == wx.ID_OK: fullname = dialog.GetPath() if not fullname.endswith(PVS_EXTENSION): fullname = fullname + PVS_EXTENSION logging.info("Saving file as %s", fullname) richEditor = remgr.RichEditorManager().getFocusedRichEditor() if richEditor is not None: richEditor.saveFile(fullname) else: logging.info("Nothing was selected.") dialog.Destroy()
def ensureFilesAreSavedToPoceed(self, files=None): """Ensure that all files are saved before closing them all""" filesAreSaved = True richEditors = self.getOpenRichEditors() if files is None else [self.editors[fullname] for fullname in files] for richEditor in richEditors: if richEditor.styledText.GetModify(): filesAreSaved = False break safeToProceed = True numberOfFiles = len(richEditors) if not filesAreSaved and numberOfFiles>0: if numberOfFiles == 1: message = "%s has been modified. Save changes?"%richEditors[0].getFilename() else: message = "Some files have been modified. Save changes?" choice = util.getMainFrame().askYesNoCancelQuestion(message) if choice == wx.ID_YES: self.saveAllFiles() elif choice == wx.ID_CANCEL: safeToProceed = False return safeToProceed
def setBindings(self): frame = util.getMainFrame() frame.Bind(wx.EVT_MENU, onCreateNewFile, self.newFileMenuItem) frame.Bind(wx.EVT_MENU, onOpenFile, self.openFileMenuItem) frame.Bind(wx.EVT_MENU, onSaveFile, self.saveFileMenuItem) frame.Bind(wx.EVT_MENU, onSaveAsFile, self.saveFileAsMenuItem) frame.Bind(wx.EVT_MENU, onCloseFile, self.closeFileMenuItem) frame.Bind(wx.EVT_MENU, onQuitFrame, self.quitMenuItem) frame.Bind(wx.EVT_MENU, onUndo, self.undoMenuItem) frame.Bind(wx.EVT_MENU, onRedo, self.redoMenuItem) frame.Bind(wx.EVT_MENU, onSelectAll, self.selectAllMenuItem) frame.Bind(wx.EVT_MENU, onCutText, self.cutMenuItem) frame.Bind(wx.EVT_MENU, onCopyText, self.copyMenuItem) frame.Bind(wx.EVT_MENU, onPasteText, self.pasteMenuItem) frame.Bind(wx.EVT_MENU, onFindText, self.findMenuItem) frame.Bind(wx.EVT_MENU, onChangeContext, self.changeContextMenuItem) frame.Bind(wx.EVT_MENU, onTypecheck, self.typecheckMenuItem) frame.Bind(wx.EVT_MENU, onResetPVS, self.pvsResetMenuItem) frame.Bind(wx.EVT_MENU, onShowPVSCommunicationLog, self.pvsDialogMenuItem) frame.Bind(wx.EVT_MENU, onShowHelpFrame, self.helpMenuItem)
def onShowPVSCommunicationLog(event): """called to handle 'pvs communication logs' request""" logging.debug("Starting") dlg = ui.logdlg.PVSCommunicationLogDialog(util.getMainFrame(), "PVS Communication Log", JSONLOG) dlg.Show()
def onPasteText(event): """called to handle 'paste' request""" logging.debug("Starting") if not util.getMainFrame().handlePasteRequest(): event.Skip()
def onCopyText(event): """called to handle 'copy' request""" logging.debug("Starting") if not util.getMainFrame().handleCopyRequest(): event.Skip()
def onRedo(event): """called to handle 'redo' request""" logging.debug("Starting") if not util.getMainFrame().handleRedoRequest(): event.Skip()
def onQuitFrame(event): """called to handle 'quit application' request""" logging.debug("Starting") frame = util.getMainFrame() frame.Close()
def _sendCommandPVS(self, *args, **keywords): method = args[0] params = args[1:] if 'resultfn' in keywords: resultfn = keywords['resultfn'] del keywords['resultfn'] else: resultfn = None evt = PVSResponseEvent() try: silent = keywords[ PVSCommunicator. SILENT] if PVSCommunicator.SILENT in keywords else False # Spawn a new thread, allowing the WX thread to go back to the main loop. # Note that _sendCommand does not directly return a result. jsonResult = self.pvsComm.requestPVS(method, *params) pvsMode = jsonResult[PVSCommunicator.MODE] evt.pvsmode = pvsMode evt.context = util.normalizePath( jsonResult[PVSCommunicator.CONTEXT]) if PVSCommunicator.XMLRPCERROR in jsonResult: errorObj = jsonResult[PVSCommunicator.XMLRPCERROR] errorObject = {} if isinstance(errorObj, str) or isinstance(errorObj, unicode): logging.error( "jsonResult[xmlrpc_error] should be a dictionary and not a string" ) errorObject[PVSCommunicator.CODE] = -100 errorObject[PVSCommunicator.MESSAGE] = errorObj errorObject[PVSCommunicator.DATA] = None else: errorObject[PVSCommunicator.CODE] = int( errorObj[PVSCommunicator.CODE]) errorObject[PVSCommunicator.MESSAGE] = errorObj[ PVSCommunicator.MESSAGE] errorObject[PVSCommunicator.DATA] = errorObj[ PVSCommunicator. DATA] if PVSCommunicator.DATA in errorObj else None raise util.PVSException( message=errorObject[PVSCommunicator.MESSAGE], errorObject=errorObject) result = jsonResult[PVSCommunicator.JSONRPCRESULT] if isinstance(result, str) or isinstance(result, unicode): result2 = json.loads(result) #TODO: Keep this for a while, but remove the if statement later if you never get an assertion error. #assert (result2 == result), "result '%s' is a json object inside a string"%result if result2 != result: logging.error( "result '%s' should not be a string here, but an object", result) result = result2 if PVSCommunicator.ERROR in result: errDict = result[PVSCommunicator.ERROR] errorObject = self._processJSONErrorObject(errDict) raise util.PVSException( message=errorObject[PVSCommunicator.MESSAGE], errorObject=errorObject) evt.result = result[PVSCommunicator.RESULT] evt.resultfn = resultfn wx.PostEvent(util.getMainFrame(), evt) except Exception as err: # import traceback # traceback.print_stack() if not silent: self._handleError(err)
def onSelectAll(event): """called to handle 'select all' request""" logging.debug("Starting") if not util.getMainFrame().handleSelectAllRequest(): event.Skip()
def _getWidgetFrame(self, w): if w is None: return util.getMainFrame() while not isinstance(w, wx.Frame): w = w.GetParent() return w