def showAboutWindow(self): ''' 打开关于窗口方法 :return: None ''' aboutdialog = AboutDialog() aboutdialog_window = QMainWindow(MainWindow) aboutdialog.setupUi(aboutdialog_window) aboutdialog_window.setWindowModality(Qt.ApplicationModal) aboutdialog_window.show()
def __init__(self): ''' Constructor ''' super(AppMainWindow, self).__init__() print "STM32 GCC-ARM IDE started..." print SPLASH_NOTICE if False: # todo: set to True if building stand-alone package (cx_Freeze) setpath = os.path.dirname(os.path.realpath(__file__)) if os.name == 'nt': os.chdir(setpath[:setpath.rfind('\\')]) else: os.chdir(setpath[:setpath.rfind('/')]) self.aboutDlg = AboutDialog(self) self.aboutDlg.show() self.setWindowTitle("STM32 GCC-ARM IDE") self.setWindowIcon(QtGui.QIcon('images/app.png')) self.setMinimumSize(300, 400) self.Editor = MultipleCppEditor(self) self.setCentralWidget(self.Editor) self.OutLineView = self.Editor.getOutLineView() self.OutLineView.setObjectName("OutLineView") self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.OutLineView) self.Compiler = GccCompilerThread(self) self.pollCompilerTimerID = None self.serialPortName = None self.serialPortLabel = QtGui.QLabel( '<font color=red><i>(select port)</i></font>') self.SerialPortMonitorDialog = SerialPortMonitor(self) self.flashLoader = FlashLoaderThread(self) self.pollLoaderTimerID = None self.Configs = IdeConfig(self) self.createLogWindow() self.createActions() self.createToolBars() self.createStatusBar() self.Configs.restoreIdeSettings() self.createMenus() self.aboutDlg.finish(self) print "IDE ready."
def _on_about_clicked(self, btn): about_dialog = AboutDialog() # XXX: Getting a refrence to the top-level main window I can't see any # other way of doing it than knowing how many levels of container we're # in... about_dialog.set_transient_for(self.get_parent().get_parent()) def close_dialog(*args): about_dialog.destroy() about_dialog.connect("response", close_dialog) about_dialog.connect("close", close_dialog) about_dialog.show_all()
def open_about_dialog(self): """Open a dialog with info about QWeeChat.""" messages = [ '<b>%s</b> %s' % (NAME, qweechat_version()), '© 2011-2020 %s <<a href="mailto:%s">%s</a>>' % (AUTHOR, AUTHOR_MAIL, AUTHOR_MAIL), '', 'Running with %s' % ('PySide' if qt_compat.uses_pyside else 'PyQt4'), '', 'WeeChat site: <a href="%s">%s</a>' % (WEECHAT_SITE, WEECHAT_SITE), '' ] self.about_dialog = AboutDialog(NAME, messages, self)
def __init__(self): ''' Constructor ''' super(AppMainWindow, self).__init__() print "LM4F GCC-ARM IDE started..." print SPLASH_NOTICE if False: # todo: set to True if building stand-alone package (cx_Freeze) setpath = os.path.dirname( os.path.realpath( __file__ ) ) if os.name == 'nt': os.chdir( setpath[:setpath.rfind('\\')] ) else: os.chdir( setpath[:setpath.rfind('/')] ) self.aboutDlg = AboutDialog(self) self.aboutDlg.show() self.setWindowTitle("LM4F GCC-ARM IDE") self.setWindowIcon(QtGui.QIcon('images/app.png')) self.setMinimumSize(300, 400) self.Editor = MultipleCppEditor(self) self.setCentralWidget(self.Editor) self.OutLineView = self.Editor.getOutLineView() self.OutLineView.setObjectName("OutLineView") self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.OutLineView) self.Compiler = GccCompilerThread(self) self.pollCompilerTimerID = None self.serialPortName = None self.serialPortLabel = QtGui.QLabel('<font color=red><i>(select port)</i></font>') self.SerialPortMonitorDialog = SerialPortMonitor(self) self.flashLoader = LM4FlashThread(self) self.pollLoaderTimerID = None self.Configs = IdeConfig(self) self.createLogWindow() self.createActions() self.createToolBars() self.createStatusBar() self.Configs.restoreIdeSettings() self.createMenus() self.aboutDlg.finish(self) print "IDE ready."
def __init__(self): ''' Constructor ''' super(AppMainWindow, self).__init__() print "PhilRoboKit IDE started..." print SPLASH_NOTICE if False: # todo: set to True if building stand-alone package (cx_Freeze) setpath = os.path.dirname( os.path.realpath( __file__ ) ) if os.name == 'nt': os.chdir( setpath[:setpath.rfind('\\')] ) else: os.chdir( setpath[:setpath.rfind('/')] ) self.aboutDlg = AboutDialog(self) self.aboutDlg.show() self.setWindowTitle("PhilRobokit IDE") self.setWindowIcon(QtGui.QIcon('images/app.png')) self.setMinimumSize(300, 400) self.Configs = IdeConfig(self) self.Editor = MultipleCppEditor(self) self.setCentralWidget(self.Editor) self.Compiler = PicCompilerThread(self) self.pollCompilerTimerID = None self.boardName = '' self.serialPortName = '' self.serialPortLabel = QtGui.QLabel('<font color=red><i>(select port)</i></font>') self.SerialPortMonitorDialog = SerialPortMonitor(self) self.PK2Programmer = PICkit2ProgrammerThread(self) self.pollPK2TimerID = None self.tinyBootloader = TinyPICBootloaderThread(self) self.pollTblTimerID = None self.createLogWindow() self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.aboutDlg.finish(self) print "IDE ready."
class MainWindow(QMainWindow, Ui_MainWindow, PersistentGeometry): settingsDialog = None aboutDialog = None def __init__(self, parent): super().__init__(parent) # UI self.setupUi(self) self.connectUI() self.preserveGeometry("main") def connectUI(self): # connect UI related signal/slot self.action_exit.triggered.connect(self.slotExit) self.action_setting.triggered.connect(self.slotSetting) self.action_showAbout.triggered.connect(self.slotShowAbout) # shorthand @property def page(self): return self.webView.page() @property def frame(self): return self.webView.page().mainFrame() # shorthand ends @pyqtSlot() def slotExit(self): app.quit() @pyqtSlot() def slotSetting(self): self.settingsDialog = SettingsDialog(self) self.settingsDialog.show() @pyqtSlot() def slotShowAbout(self): self.aboutDialog = AboutDialog(self) self.aboutDialog.show() def changeEvent(self, qEvent): if qEvent.type() == QEvent.WindowStateChange: if self.isMinimized(): if app.settings.getbool("frontend", "minimizetosystray"): self.setHidden(True) super().changeEvent(qEvent) def minimize(self): self.showMinimized() def restore(self): self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive) if self.isHidden(): self.setHidden(False) self.raise_() def closeEvent(self, qCloseEvent): if app.settings.getbool("frontend", "closetominimize"): qCloseEvent.ignore() self.minimize() else: qCloseEvent.accept()
class MainWindow(QMainWindow, Ui_MainWindow, PersistentGeometry): settingsDialog = None aboutDialog = None def __init__(self, parent): super().__init__(parent) # UI self.setupUi(self) self.connectUI() self.preserveGeometry() def connectUI(self): # connect UI related signal/slot self.action_exit.triggered.connect(self.slotExit) self.action_setting.triggered.connect(self.slotSetting) self.action_showAbout.triggered.connect(self.slotShowAbout) # shorthand @property def page(self): return self.webView.page() @property def frame(self): return self.webView.page().mainFrame() # shorthand ends @pyqtSlot() def slotExit(self): app.quit() @pyqtSlot() def slotSetting(self): self.settingsDialog = SettingsDialog(self) self.settingsDialog.show() @pyqtSlot() def slotShowAbout(self): self.aboutDialog = AboutDialog(self) self.aboutDialog.show() def changeEvent(self, qEvent): if qEvent.type() == QEvent.WindowStateChange: if self.isMinimized(): if app.settings.getbool("frontend", "minimizetosystray"): self.setHidden(True) super().changeEvent(qEvent) def minimize(self): self.showMinimized() def restore(self): self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive) if self.isHidden(): self.setHidden(False) self.raise_() def closeEvent(self, qCloseEvent): if app.settings.getbool("frontend", "closetominimize"): qCloseEvent.ignore() self.minimize() else: qCloseEvent.accept()
class AppMainWindow(QtGui.QMainWindow): ''' classdocs ''' def __init__(self): ''' Constructor ''' super(AppMainWindow, self).__init__() print "STM32 GCC-ARM IDE started..." print SPLASH_NOTICE if False: # todo: set to True if building stand-alone package (cx_Freeze) setpath = os.path.dirname(os.path.realpath(__file__)) if os.name == 'nt': os.chdir(setpath[:setpath.rfind('\\')]) else: os.chdir(setpath[:setpath.rfind('/')]) self.aboutDlg = AboutDialog(self) self.aboutDlg.show() self.setWindowTitle("STM32 GCC-ARM IDE") self.setWindowIcon(QtGui.QIcon('images/app.png')) self.setMinimumSize(300, 400) self.Editor = MultipleCppEditor(self) self.setCentralWidget(self.Editor) self.OutLineView = self.Editor.getOutLineView() self.OutLineView.setObjectName("OutLineView") self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.OutLineView) self.Compiler = GccCompilerThread(self) self.pollCompilerTimerID = None self.serialPortName = None self.serialPortLabel = QtGui.QLabel( '<font color=red><i>(select port)</i></font>') self.SerialPortMonitorDialog = SerialPortMonitor(self) self.flashLoader = FlashLoaderThread(self) self.pollLoaderTimerID = None self.Configs = IdeConfig(self) self.createLogWindow() self.createActions() self.createToolBars() self.createStatusBar() self.Configs.restoreIdeSettings() self.createMenus() self.aboutDlg.finish(self) print "IDE ready." def about(self): self.aboutDlg.show() kdbMod = QtGui.QApplication.keyboardModifiers() if kdbMod == QtCore.Qt.ShiftModifier: self.aboutDlg.showMessage( '[developer mode] update firmware library...', QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom, QtGui.QColor("#eecc77")) self.aboutDlg.showUpdateDialog() return # todo: other informations self.aboutDlg.showMessage( "STM32 GCC-ARM IDE [ %s ]" % self.aboutDlg.getVersions(), QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom, QtGui.QColor("#eecc77")) def openProjectProtoSite(self): QtGui.QDesktopServices.openUrl( QtCore.QUrl("http://projectproto.blogspot.com")) def openPhilRoboticsSite(self): # todo: change to .ORG QtGui.QDesktopServices.openUrl( QtCore.QUrl("http://www.philrobotics.com")) def aboutCompiler(self): info = self.Compiler.getCompilerInfo() #self.log.append(info) if info: QtGui.QMessageBox.about(self, "Compiler Information", info) else: QtGui.QMessageBox.about(self, "Compiler Information", "no compiler found!") def startBuild(self): if self.Compiler.isRunning(): self.insertLog('compiler busy..') return kdbMod = QtGui.QApplication.keyboardModifiers() ret = self.Editor.saveFile( ) # save the file first before starting the build. if ret == False: self.insertLog("<font color=red>unable to save project!</font>") return elif ret == None: self.insertLog("nothing to build.") return self.insertLog( "<font color=green>------- Start Project Build. -------</font>", True) fn = self.Editor.getCurrentFile() cleanBuild = False if kdbMod == QtCore.Qt.ShiftModifier: #print 'Shift-Click PushButton' cleanBuild = True ret, msg = self.Compiler.buildProject(fn, cleanBuild) if not ret: self.insertLog("<font color=red>%s</font>" % msg) if msg == "file not found": QtGui.QMessageBox.warning( self, "Build Error", "File not found (may be unsaved yet). " + \ "Create or save first the file." ) elif msg == "busy": QtGui.QMessageBox.warning( self, "Busy", "Previous build process still running!") elif msg == "abort": QtGui.QMessageBox.warning(self, "Error", "Unable to start build process!") else: self.insertLog("<font color=lightblue><i> %s </i></font>" % msg) self.pollCompilerTimerID = self.startTimer(50) if not self.pollCompilerTimerID: self.insertLog("<font color=red>Unable to start Timer.</font>") def stopBuild(self): if self.pollCompilerTimerID: self.killTimer(self.pollCompilerTimerID) self.pollCompilerTimerID = None self.Compiler.pollBuildProcess(True) self.insertLog("<font color=red>----- Stopped. -----</font>") else: self.insertLog("nothing to stop.") def programChip(self): if self.Editor.isCurrentFileModified(): self.insertLog( '<font color=orange>Project was modified. Please re-build the project.</font>' ) return if not self.serialPortName: self.insertLog( '<font color=orange>Please select first a Serial Port.</font>') return if self.Compiler.isRunning(): self.insertLog('compiler busy... please wait...') return if self.SerialPortMonitorDialog.isPortOpen(): self.SerialPortMonitorDialog.close( ) # close first serial port monitor if self.flashLoader.isRunning(): self.insertLog('serial bootloader busy.') return binfile = self.Compiler.getExpectedBinFileName( self.Editor.getCurrentFile()) ret, msg = self.flashLoader.programDevice(binfile, self.serialPortName) if ret: self.insertLog("<font color=green>Bootload/Program Device:</font>", True) self.insertLog("<font color=lightblue><i> %s </i></font>" % msg) self.pollLoaderTimerID = self.startTimer(0.5) # relatively fast! if not self.pollLoaderTimerID: self.insertLog("<font color=red>Unable to start Timer.</font>") else: self.insertLog("<font color=red>%s</font>" % msg) def selectSerialPort(self): act = self.serialPortGroup.checkedAction() if act: portname = str(act.text()) if portname != self.serialPortName: self.serialPortName = portname self.Configs.saveIdeSettings(self.serialPortName) self.insertLog( 'selected port: <b><font color=green>%s</font></b>' % self.serialPortName) self.serialPortLabel.setText('<font color=green>%s</font>' % self.serialPortName) if self.SerialPortMonitorDialog.isPortOpen(): if not self.SerialPortMonitorDialog.openPort( self.serialPortName): self.SerialPortMonitorDialog.close() self.insertLog( "<font color=red>unable to open %s</font>" % self.serialPortName) def updateSerialPortList(self): # clear previous actions list self.serialPortMenu.clear() for act in self.serialPortGroup.actions(): self.serialPortGroup.removeAction(act) del act # scan existing ports portList = scan_serialports() # serialport.py previousPortName = self.Configs.getSerialPortName() # create new actions & update serial port menu if len(portList): for i in range(len(portList)): act = QtGui.QAction(portList[i], self, checkable=True, statusTip="select " + portList[i] + " serial port", triggered=self.selectSerialPort) self.serialPortGroup.addAction(act) self.serialPortMenu.addAction(act) if portList[i] == previousPortName: act.setChecked(True) act.trigger() if not self.serialPortGroup.checkedAction(): self.serialPortName = '' self.insertLog( '<i><font color=gray>( please select a serial port. )</font></i>' ) def importFirmwareLib(self, action=None): if action: libname = str(action.text()) self.Editor.importFirmwareLib(libname) def openSerialPortMonitorDialog(self): if self.serialPortName == None: self.insertLog("<font color=red>no serial port selected!</font>") return if self.SerialPortMonitorDialog.openPort(self.serialPortName): self.SerialPortMonitorDialog.show() # non-modal open else: self.insertLog( "<font color=red>unable to open serial port!</font>") def createActions(self): # file menu self.newAct = QtGui.QAction(QtGui.QIcon("./images/new.png"), "&New", self, shortcut=QtGui.QKeySequence("Ctrl+N"), statusTip="Create a new file", triggered=self.Editor.newFile) self.openAct = QtGui.QAction(QtGui.QIcon("./images/open.png"), "&Open...", self, shortcut=QtGui.QKeySequence("Ctrl+O"), statusTip="Open an existing file") self.openAct.triggered.connect( functools.partial(self.Editor.openFile, None)) self.closeAct = QtGui.QAction("&Close", self, shortcut=QtGui.QKeySequence("Ctrl+W"), statusTip="Close the current window", triggered=self.Editor.closeCurrentFile) self.saveAct = QtGui.QAction(QtGui.QIcon("./images/save.png"), "&Save", self, shortcut=QtGui.QKeySequence("Ctrl+S"), statusTip="Save the current file", triggered=self.Editor.saveFile) self.saveAsAct = QtGui.QAction( "Save &As...", self, shortcut=QtGui.QKeySequence("Ctrl+Shift+S"), statusTip="Save to another file", triggered=self.Editor.saveFileAs) self.exitAct = QtGui.QAction("E&xit", self, shortcut=QtGui.QKeySequence("Alt+F4"), statusTip="Exit the application", triggered=QtGui.qApp.closeAllWindows) # edit menu self.editUndoAct = QtGui.QAction("&Undo", self, shortcut=QtGui.QKeySequence("Ctrl+Z"), triggered=self.Editor.editUndo) self.editRedoAct = QtGui.QAction("&Redo", self, shortcut=QtGui.QKeySequence("Ctrl+Y"), triggered=self.Editor.editRedo) self.editCutAct = QtGui.QAction("Cu&t", self, shortcut=QtGui.QKeySequence("Ctrl+X"), triggered=self.Editor.editCut) self.editCopyAct = QtGui.QAction("&Copy", self, shortcut=QtGui.QKeySequence("Ctrl+C"), triggered=self.Editor.editCopy) self.editPasteAct = QtGui.QAction( "&Paste", self, shortcut=QtGui.QKeySequence("Ctrl+V"), triggered=self.Editor.editPaste) self.editSelectAllAct = QtGui.QAction( "Select &All", self, shortcut=QtGui.QKeySequence("Ctrl+A"), triggered=self.Editor.editSelectAll) self.editClearAct = QtGui.QAction("Clear", self, triggered=self.Editor.editClear) # find/replace self.findAct = QtGui.QAction("&Find/Replace...", self, shortcut=QtGui.QKeySequence("Ctrl+F"), statusTip="Find/Replace texts", triggered=self.Editor.showFindDialog) # project menu self.compileAct = QtGui.QAction(QtGui.QIcon("./images/build.png"), "&Compile", self, shortcut=QtGui.QKeySequence("Ctrl+B"), statusTip="Build the current project", triggered=self.startBuild) self.stopAct = QtGui.QAction(QtGui.QIcon("./images/stop.png"), "S&top", self, statusTip="Cancel the build process", triggered=self.stopBuild) self.programAct = QtGui.QAction( QtGui.QIcon("./images/load.png"), "&Load", self, shortcut=QtGui.QKeySequence("Ctrl+R"), statusTip="Download program to the board using bootloader", triggered=self.programChip) self.firmwareLibList = scanFirmwareLibs() self.firmwareLibActs = [] if len(self.firmwareLibList): for i in range(len(self.firmwareLibList)): self.firmwareLibActs.append( QtGui.QAction(self.firmwareLibList[i], self, statusTip="include " + self.firmwareLibList[i] + " library")) self.exampleProjects = getExampleProjects(self.firmwareLibList) self.exampleFolderMenus = [] self.openExampleActs = [] for group in self.exampleProjects: folder, files = group[0], group[1] self.exampleFolderMenus.append(QtGui.QMenu(str(folder), self)) for fname in files: baseName = os.path.basename(fname) self.openExampleActs.append( QtGui.QAction(os.path.splitext(baseName)[0], self, statusTip='Open "' + str(fname).replace('\\', '/') + '"')) # serial monitor/terminal window self.serialMonitorAct = QtGui.QAction( QtGui.QIcon("./images/serial.png"), "Serial &Monitor", self, shortcut=QtGui.QKeySequence("Ctrl+Shift+M"), statusTip="Launch Serial Monitor Dialog", triggered=self.openSerialPortMonitorDialog) self.serialPortGroup = QtGui.QActionGroup(self) self.serialPortList = scan_serialports() self.serialPortActs = [] if len(self.serialPortList): for i in range(len(self.serialPortList)): self.serialPortActs.append( QtGui.QAction(self.serialPortList[i], self, checkable=True, statusTip="select " + self.serialPortList[i] + " serial port", triggered=self.selectSerialPort)) self.serialPortGroup.addAction(self.serialPortActs[i]) # todo: board names?? #self.boardAnitoAct = QtGui.QAction("PhilRobokit &Anito", self, # checkable=True, statusTip="Select PhilRobokit Anito board" ) self.boardEgizmoStm32Act = QtGui.QAction( "e&Gizmo STM32", self, checkable=True, statusTip="Select eGizmo STM32F100C8 MCU board") self.boardGroup = QtGui.QActionGroup(self) #self.boardGroup.addAction(self.boardAnitoAct) self.boardGroup.addAction(self.boardEgizmoStm32Act) self.boardEgizmoStm32Act.setChecked(True) self.restoreDefaultsAct = QtGui.QAction( "Restore Defaults", self, statusTip="Clear configuration files", triggered=self.Configs.setDefaults) # help menu self.aboutAct = QtGui.QAction("&About", self, shortcut=QtGui.QKeySequence("F1"), statusTip="About the IDE", triggered=self.about) self.aboutCompilerAct = QtGui.QAction( "About &Compiler", self, statusTip="About GNU tools for ARM Embedded", triggered=self.aboutCompiler) self.aboutQtAct = QtGui.QAction( "About &Qt", self, statusTip="Show the Qt library's About box", triggered=QtGui.qApp.aboutQt) self.visitProjectprotoSiteAct = QtGui.QAction( "Visit &ProjectProto", self, statusTip="Open ProjectProto blog site (yus' projects)", triggered=self.openProjectProtoSite) self.visitPhilroboticsSiteAct = QtGui.QAction( "Visit Phil&Robotics", self, statusTip="Open PhilRobotics website", triggered=self.openPhilRoboticsSite) def createMenus(self): ### File Menu ### self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.openAct) self.fileMenu.addSeparator() self.examplesMenu = QtGui.QMenu('Examples', self) fileCount = 0 for dirCount in range(len(self.exampleFolderMenus)): examples = self.exampleProjects[dirCount][1] for fname in examples: pathname = str(os.getcwd() + '/' + fname) # complete path pathname = pathname.replace('\\', '/') # for consistency self.openExampleActs[fileCount].triggered.connect( functools.partial(self.Editor.openFile, pathname)) self.exampleFolderMenus[dirCount].addAction( self.openExampleActs[fileCount]) fileCount += 1 self.examplesMenu.addMenu(self.exampleFolderMenus[dirCount]) self.fileMenu.addMenu(self.examplesMenu) self.fileMenu.addSeparator() self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.saveAsAct) self.fileMenu.addAction(self.closeAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) ### Edit Menu ### self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.editUndoAct) self.editMenu.addAction(self.editRedoAct) self.editMenu.addSeparator() self.editMenu.addAction(self.editCutAct) self.editMenu.addAction(self.editCopyAct) self.editMenu.addAction(self.editPasteAct) self.editMenu.addAction(self.editSelectAllAct) self.editMenu.addAction(self.editClearAct) self.editMenu.addSeparator() self.editMenu.addAction(self.findAct) ### Project Menu ### self.projectMenu = self.menuBar().addMenu("&Project") self.projectMenu.addAction(self.compileAct) self.projectMenu.addAction(self.stopAct) self.programMenu = self.projectMenu.addMenu("Program Board...") self.programMenu.addAction(self.programAct) self.projectMenu.addSeparator() self.firmwareLibMenu = self.projectMenu.addMenu("Import &Library...") if len(self.firmwareLibActs): for i in range(len(self.firmwareLibActs)): self.firmwareLibMenu.addAction(self.firmwareLibActs[i]) self.connect(self.firmwareLibMenu, QtCore.SIGNAL("triggered (QAction *)"), self.importFirmwareLib) ### Tools Menu ### self.toolsMenu = self.menuBar().addMenu("&Tools") self.toolsMenu.addAction(self.serialMonitorAct) self.toolsMenu.addSeparator() self.boardMenu = self.toolsMenu.addMenu("&Board") #self.boardMenu.addAction(self.boardAnitoAct) self.boardMenu.addAction(self.boardEgizmoStm32Act) self.serialPortMenu = self.toolsMenu.addMenu("&Serial Port") self.serialPortGroup = QtGui.QActionGroup(self) self.connect(self.serialPortMenu, QtCore.SIGNAL("aboutToShow ()"), self.updateSerialPortList) self.updateSerialPortList() self.toolsMenu.addSeparator() self.toolsMenu.addAction( self.restoreDefaultsAct) # todo: create settings dialog #self.bootloaderMenu = self.toolsMenu.addMenu("&Booloader") ### Help Menu ### self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.visitPhilroboticsSiteAct) self.helpMenu.addAction(self.visitProjectprotoSiteAct) self.helpMenu.addAction(self.aboutCompilerAct) self.helpMenu.addAction(self.aboutQtAct) self.helpMenu.addAction(self.aboutAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.setObjectName("FileToolBar") self.fileToolBar.addAction(self.newAct) self.fileToolBar.addAction(self.openAct) self.fileToolBar.addAction(self.saveAct) self.projectToolBar = self.addToolBar("Project") self.projectToolBar.setObjectName("ProjectToolBar") self.projectToolBar.addAction(self.compileAct) self.projectToolBar.addAction(self.stopAct) self.projectToolBar.addAction(self.programAct) self.serialToolBar = self.addToolBar("Serial Port") self.serialToolBar.setObjectName("SerialPortToolBar") self.serialToolBar.addAction(self.serialMonitorAct) self.serialToolBar.addWidget(self.serialPortLabel) def createStatusBar(self): self.statusBar().showMessage("Ready") def createLogWindow(self): self.log = QtGui.QTextEdit(self) self.log.setReadOnly(True) self.log.resize(self.width(), 100) self.log.setText("Ready") palette = QtGui.QPalette(QtGui.QColor(0, 0, 0)) palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, QtGui.QColor(25, 10, 0)) self.log.setPalette(palette) logWindow = QtGui.QDockWidget("Log", self) logWindow.setObjectName("LogView") logWindow.setWidget(self.log) self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, logWindow) def insertLog(self, log='', resetWindow=False): if resetWindow: self.log.setText('') self.log.append(log) def timerEvent(self, *args, **kwargs): timerID = args[0].timerId() if timerID == self.pollCompilerTimerID: ret, msg = self.Compiler.pollBuildProcess() if ret: if len(msg): self.insertLog(msg) else: self.killTimer(timerID) self.pollCompilerTimerID = None if timerID == self.pollLoaderTimerID: ret, msg = self.flashLoader.pollBootLoadProcess() if ret: if len(msg): self.insertLog("<font color=lightgreen>%s</font>" % msg) else: self.killTimer(timerID) self.pollLoaderTimerID = None return QtGui.QMainWindow.timerEvent(self, *args, **kwargs) def closeEvent(self, event): if not self.Editor.closeAllTabs( ): # check for unsaved changes in the project(s) event.ignore() return self.Configs.saveIdeSettings(self.serialPortName) return QtGui.QMainWindow.closeEvent(self, event)
class ShtoomMainWindow(ShtoomBaseWindow, ShtoomBaseUI): sending = False audiosource = None cookie = None _muted = False def __init__(self, *args, **kwargs): self._newCallURL = None self.dtmf = DTMF() self.dtmf.main = self self.debugging = Debugging() ShtoomBaseWindow.__init__(self, *args, **kwargs) def debugMessage(self, message): print message log.msg(message, system='ui') def statusMessage(self, message): self.statusLabel.setText(message) def errorMessage(self, message, exception=None): log.msg("%s: %s"%(_('ERROR'), message), system='ui') def hangupButton_clicked(self): self.app.dropCall(self.cookie) self.callButton.setEnabled(True) self.hangupButton.setEnabled(False) self.cookie = None def register_clicked(self): self.app.register() def callButton_clicked(self): sipURL = str(self.addressComboBox.currentText()).strip() if not sipURL: return self.addressComboBox.setCurrentText(sipURL) self.addressComboBox.insertItem(QString(sipURL)) self._newCallURL = sipURL self.callButton.setEnabled(False) defer = self.app.placeCall(sipURL) defer.addCallbacks(self.callConnected, self.callFailed).addErrback(log.err) def callStarted(self, cookie): print "started", cookie self.cookie = cookie self.hangupButton.setEnabled(True) self.statusMessage(_('Calling...')) def callFailed(self, e, message=None): self.errorMessage("call failed", e.getErrorMessage()) self.statusMessage(_('Call Failed')) self.hangupButton.setEnabled(False) self.callButton.setEnabled(True) self.cookie = None def callConnected(self, cookie): self.hangupButton.setEnabled(True) self.statusMessage(_('Call Connected')) if self._muted: self.app.muteCall(self.cookie) def callDisconnected(self, cookie, message): self.statusMessage('%s: %s'%(_('Call Disconnected'), message)) self.hangupButton.setEnabled(False) self.callButton.setEnabled(True) self.cookie = None def getLogger(self): l = Logger(self.debugging.debuggingTextEdit) return l def editPreferences(self): from prefs import PreferencesDialog self.prefs =PreferencesDialog(self, self.app.getOptions()) self.prefs.show() def preferences_save(self, options): self.app.updateOptions(options) self.prefs.hide() def preferences_discard(self): self.prefs.hide() def incomingCall(self, description, cookie): # XXX not good. Blockage. Argh. from twisted.internet import defer from shtoom.exceptions import CallRejected accept = QMessageBox.information(self, 'Shtoom', 'Incoming Call: %s\nAnswer?'%description, 'Yes', 'No', '', 0, 1) print "accept is", accept if accept == 0: self.cookie = cookie self.callButton.setEnabled(False) self.addressComboBox.setEnabled(False) return defer.succeed(cookie) else: return defer.fail(CallRejected(cookie)) def muteCheck_stateChanged(self,val): if val: self._muted = True else: self._muted = False if self.cookie is not None: if val: self.app.muteCall(self.cookie) else: self.app.unmuteCall(self.cookie) def startDTMF(self, key): if self.cookie: self.app.startDTMF(self.cookie, key) def stopDTMF(self, key): if self.cookie: self.app.stopDTMF(self.cookie, key) def fileDTMF(self, *args): self.dtmf.show() def fileDebugging(self, *args): self.debugging.show() def _gotAuth(self, res): self._authdialog = None return res def getAuth(self, method, realm): # XXX tofix we should queue auth requests self._authdialog = AuthDialog() d = self._authdialog.getAuth(method, realm) d.addCallback(self._gotAuth) return d def __tr(self, str): return QString(_(str)) def registerButton_clicked(self): self.app.register() def fileExit(self): from twisted.internet import reactor reactor.stop() def helpAbout(self): self.aboutDialog = AboutDialog() self.aboutDialog.show()
class AppMainWindow(QtGui.QMainWindow): ''' classdocs ''' def __init__(self): ''' Constructor ''' super(AppMainWindow, self).__init__() print "LM4F GCC-ARM IDE started..." print SPLASH_NOTICE if False: # todo: set to True if building stand-alone package (cx_Freeze) setpath = os.path.dirname( os.path.realpath( __file__ ) ) if os.name == 'nt': os.chdir( setpath[:setpath.rfind('\\')] ) else: os.chdir( setpath[:setpath.rfind('/')] ) self.aboutDlg = AboutDialog(self) self.aboutDlg.show() self.setWindowTitle("LM4F GCC-ARM IDE") self.setWindowIcon(QtGui.QIcon('images/app.png')) self.setMinimumSize(300, 400) self.Editor = MultipleCppEditor(self) self.setCentralWidget(self.Editor) self.OutLineView = self.Editor.getOutLineView() self.OutLineView.setObjectName("OutLineView") self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.OutLineView) self.Compiler = GccCompilerThread(self) self.pollCompilerTimerID = None self.serialPortName = None self.serialPortLabel = QtGui.QLabel('<font color=red><i>(select port)</i></font>') self.SerialPortMonitorDialog = SerialPortMonitor(self) self.flashLoader = LM4FlashThread(self) self.pollLoaderTimerID = None self.Configs = IdeConfig(self) self.createLogWindow() self.createActions() self.createToolBars() self.createStatusBar() self.Configs.restoreIdeSettings() self.createMenus() self.aboutDlg.finish(self) print "IDE ready." def about(self): self.aboutDlg.show() kdbMod = QtGui.QApplication.keyboardModifiers() if kdbMod == QtCore.Qt.ShiftModifier: self.aboutDlg.showMessage('[developer mode] update firmware library...', QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom, QtGui.QColor("#eecc77")) self.aboutDlg.showUpdateDialog() return # todo: other informations self.aboutDlg.showMessage("LM4F GCC-ARM IDE [ %s ]" % self.aboutDlg.getVersions(), QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom, QtGui.QColor("#eecc77")); def openProjectProtoSite(self): QtGui.QDesktopServices.openUrl( QtCore.QUrl("http://projectproto.blogspot.com") ) def openPhilRoboticsSite(self): # todo: change to .ORG QtGui.QDesktopServices.openUrl( QtCore.QUrl("http://www.philrobotics.com") ) def aboutCompiler(self): info = self.Compiler.getCompilerInfo() #self.log.append(info) if info: QtGui.QMessageBox.about( self, "Compiler Information", info ) else: QtGui.QMessageBox.about( self, "Compiler Information", "no compiler found!" ) def startBuild(self): if self.Compiler.isRunning(): self.insertLog('compiler busy..') return kdbMod = QtGui.QApplication.keyboardModifiers() ret = self.Editor.saveFile() # save the file first before starting the build. if ret == False: self.insertLog("<font color=red>unable to save project!</font>") return elif ret == None: self.insertLog("nothing to build.") return self.insertLog("<font color=green>------- Start Project Build. -------</font>", True) fn = self.Editor.getCurrentFile() cleanBuild = False if kdbMod == QtCore.Qt.ShiftModifier: #print 'Shift-Click PushButton' cleanBuild = True ret, msg = self.Compiler.buildProject(fn, cleanBuild) if not ret: self.insertLog( "<font color=red>%s</font>"%msg ) if msg == "file not found": QtGui.QMessageBox.warning( self, "Build Error", "File not found (may be unsaved yet). " + \ "Create or save first the file." ) elif msg == "busy": QtGui.QMessageBox.warning( self, "Busy", "Previous build process still running!" ) elif msg == "abort": QtGui.QMessageBox.warning( self, "Error", "Unable to start build process!" ) else: self.insertLog( "<font color=lightblue><i> %s </i></font>"%msg ) self.pollCompilerTimerID = self.startTimer(50) if not self.pollCompilerTimerID: self.insertLog("<font color=red>Unable to start Timer.</font>") def stopBuild(self): if self.pollCompilerTimerID: self.killTimer(self.pollCompilerTimerID) self.pollCompilerTimerID = None self.Compiler.pollBuildProcess(True) self.insertLog("<font color=red>----- Stopped. -----</font>") else: self.insertLog("nothing to stop.") def programChip(self): if self.Editor.isCurrentFileModified(): self.insertLog('<font color=orange>Project was modified. Please re-build the project.</font>') return if self.Compiler.isRunning(): self.insertLog('compiler busy... please wait...') return if self.flashLoader.isRunning(): self.insertLog('serial bootloader busy.') return binfile = self.Compiler.getExpectedBinFileName( self.Editor.getCurrentFile() ) ret, msg = self.flashLoader.programDevice( binfile ) if ret: self.insertLog("<font color=green>Bootload/Program Device:</font>", True) self.insertLog("<font color=lightblue><i> %s </i></font>"%msg) self.pollLoaderTimerID = self.startTimer(0.5) # relatively fast! if not self.pollLoaderTimerID: self.insertLog("<font color=red>Unable to start Timer.</font>") else: self.insertLog("<font color=red>%s</font>"%msg) def selectSerialPort(self): act = self.serialPortGroup.checkedAction() if act: portname = str( act.text() ) if portname != self.serialPortName: self.serialPortName = portname self.Configs.saveIdeSettings( self.serialPortName ) self.insertLog( 'selected port: <b><font color=green>%s</font></b>' % self.serialPortName ) self.serialPortLabel.setText('<font color=green>%s</font>'%self.serialPortName) if self.SerialPortMonitorDialog.isPortOpen(): if not self.SerialPortMonitorDialog.openPort(self.serialPortName): self.SerialPortMonitorDialog.close() self.insertLog( "<font color=red>unable to open %s</font>"%self.serialPortName) def updateSerialPortList(self): # clear previous actions list self.serialPortMenu.clear() for act in self.serialPortGroup.actions(): self.serialPortGroup.removeAction(act) del act # scan existing ports portList = scan_serialports() # serialport.py previousPortName = self.Configs.getSerialPortName() # create new actions & update serial port menu if len(portList): for i in range(len(portList)): act = QtGui.QAction(portList[i], self, checkable=True, statusTip="select " + portList[i] + " serial port", triggered=self.selectSerialPort) self.serialPortGroup.addAction( act ) self.serialPortMenu.addAction( act ) if portList[i] == previousPortName: act.setChecked(True) act.trigger() if not self.serialPortGroup.checkedAction(): self.serialPortName = '' #self.insertLog( '<i><font color=gray>( please select a serial port. )</font></i>' ) def importFirmwareLib(self, action=None): if action: libname = str( action.text() ) self.Editor.importFirmwareLib(libname) def openSerialPortMonitorDialog(self): if self.serialPortName == None: self.insertLog( "<font color=red>no serial port selected!</font>" ) return if self.SerialPortMonitorDialog.openPort(self.serialPortName): self.SerialPortMonitorDialog.show() # non-modal open else: self.insertLog( "<font color=red>unable to open serial port!</font>" ) def createActions(self): # file menu self.newAct = QtGui.QAction( QtGui.QIcon("./images/new.png"), "&New", self, shortcut=QtGui.QKeySequence("Ctrl+N"), statusTip="Create a new file", triggered=self.Editor.newFile) self.openAct = QtGui.QAction(QtGui.QIcon("./images/open.png"), "&Open...", self, shortcut=QtGui.QKeySequence("Ctrl+O"), statusTip="Open an existing file") self.openAct.triggered.connect( functools.partial(self.Editor.openFile, None) ) self.closeAct = QtGui.QAction("&Close", self, shortcut=QtGui.QKeySequence("Ctrl+W"), statusTip="Close the current window", triggered=self.Editor.closeCurrentFile) self.saveAct = QtGui.QAction(QtGui.QIcon("./images/save.png"), "&Save", self, shortcut=QtGui.QKeySequence("Ctrl+S"), statusTip="Save the current file", triggered=self.Editor.saveFile) self.saveAsAct = QtGui.QAction("Save &As...", self, shortcut=QtGui.QKeySequence("Ctrl+Shift+S"), statusTip="Save to another file", triggered=self.Editor.saveFileAs) self.exitAct = QtGui.QAction("E&xit", self, shortcut=QtGui.QKeySequence("Alt+F4"), statusTip="Exit the application", triggered=QtGui.qApp.closeAllWindows) # edit menu self.editUndoAct = QtGui.QAction("&Undo", self, shortcut=QtGui.QKeySequence("Ctrl+Z"), triggered=self.Editor.editUndo) self.editRedoAct = QtGui.QAction("&Redo", self, shortcut=QtGui.QKeySequence("Ctrl+Y"), triggered=self.Editor.editRedo) self.editCutAct = QtGui.QAction("Cu&t", self, shortcut=QtGui.QKeySequence("Ctrl+X"), triggered=self.Editor.editCut) self.editCopyAct = QtGui.QAction("&Copy", self, shortcut=QtGui.QKeySequence("Ctrl+C"), triggered=self.Editor.editCopy) self.editPasteAct = QtGui.QAction("&Paste", self, shortcut=QtGui.QKeySequence("Ctrl+V"), triggered=self.Editor.editPaste) self.editSelectAllAct = QtGui.QAction("Select &All", self, shortcut=QtGui.QKeySequence("Ctrl+A"), triggered=self.Editor.editSelectAll) self.editClearAct = QtGui.QAction("Clear", self, triggered=self.Editor.editClear) # find/replace self.findAct = QtGui.QAction("&Find/Replace...", self, shortcut=QtGui.QKeySequence("Ctrl+F"), statusTip="Find/Replace texts", triggered=self.Editor.showFindDialog) # project menu self.compileAct = QtGui.QAction(QtGui.QIcon("./images/build.png"), "&Compile", self, shortcut=QtGui.QKeySequence("Ctrl+B"), statusTip="Build the current project", triggered=self.startBuild) self.stopAct = QtGui.QAction(QtGui.QIcon("./images/stop.png"), "S&top", self, statusTip="Cancel the build process", triggered=self.stopBuild) self.programAct = QtGui.QAction(QtGui.QIcon("./images/load.png"), "&Load", self, shortcut=QtGui.QKeySequence("Ctrl+R"), statusTip="Download program to the board using bootloader", triggered=self.programChip) self.firmwareLibList = scanFirmwareLibs() self.firmwareLibActs = [] if len(self.firmwareLibList): for i in range(len(self.firmwareLibList)): self.firmwareLibActs.append( QtGui.QAction(self.firmwareLibList[i], self, statusTip="include " + self.firmwareLibList[i] + " library" ) ) self.exampleProjects = getExampleProjects(self.firmwareLibList) self.exampleFolderMenus = [] self.openExampleActs = [] for group in self.exampleProjects: folder, files = group[0], group[1] self.exampleFolderMenus.append(QtGui.QMenu(str(folder), self)) for fname in files: baseName = os.path.basename(fname) self.openExampleActs.append(QtGui.QAction(os.path.splitext(baseName)[0], self, statusTip = 'Open "' + str(fname).replace('\\', '/') + '"') ) # serial monitor/terminal window self.serialMonitorAct = QtGui.QAction(QtGui.QIcon("./images/serial.png"), "Serial &Monitor", self, shortcut=QtGui.QKeySequence("Ctrl+Shift+M"), statusTip="Launch Serial Monitor Dialog", triggered=self.openSerialPortMonitorDialog) self.serialPortGroup = QtGui.QActionGroup(self) self.serialPortList = scan_serialports() self.serialPortActs = [] if len(self.serialPortList): for i in range(len(self.serialPortList)): self.serialPortActs.append( QtGui.QAction(self.serialPortList[i], self, checkable=True, statusTip="select " + self.serialPortList[i] + " serial port", triggered=self.selectSerialPort) ) self.serialPortGroup.addAction( self.serialPortActs[i] ) # todo: board names?? #self.boardAnitoAct = QtGui.QAction("PhilRobokit &Anito", self, # checkable=True, statusTip="Select PhilRobokit Anito board" ) self.boardStellarisAct = QtGui.QAction("EK-&LM4F120XL", self, checkable=True, statusTip="Select TI Stellaris LM4F120 LaunchPad" ) self.boardGroup = QtGui.QActionGroup(self) #self.boardGroup.addAction(self.boardAnitoAct) self.boardGroup.addAction(self.boardStellarisAct) self.boardStellarisAct.setChecked(True) self.restoreDefaultsAct = QtGui.QAction("Restore Defaults", self, statusTip="Clear configuration files", triggered=self.Configs.setDefaults) # help menu self.aboutAct = QtGui.QAction("&About", self, shortcut=QtGui.QKeySequence("F1"), statusTip="About the IDE", triggered=self.about) self.aboutCompilerAct = QtGui.QAction("About &Compiler", self, statusTip="About GNU tools for ARM Embedded", triggered=self.aboutCompiler) self.aboutQtAct = QtGui.QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QtGui.qApp.aboutQt) self.visitProjectprotoSiteAct = QtGui.QAction("Visit &ProjectProto", self, statusTip="Open ProjectProto blog site (yus' projects)", triggered=self.openProjectProtoSite) self.visitPhilroboticsSiteAct = QtGui.QAction("Visit Phil&Robotics", self, statusTip="Open PhilRobotics website", triggered=self.openPhilRoboticsSite) def createMenus(self): ### File Menu ### self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.openAct) self.fileMenu.addSeparator() self.examplesMenu = QtGui.QMenu('Examples', self) fileCount = 0 for dirCount in range( len(self.exampleFolderMenus) ): examples = self.exampleProjects[dirCount][1] for fname in examples: pathname = str( os.getcwd() + '/' + fname ) # complete path pathname = pathname.replace('\\', '/') # for consistency self.openExampleActs[fileCount].triggered.connect( functools.partial(self.Editor.openFile, pathname) ) self.exampleFolderMenus[dirCount].addAction(self.openExampleActs[fileCount]) fileCount += 1 self.examplesMenu.addMenu(self.exampleFolderMenus[dirCount]) self.fileMenu.addMenu(self.examplesMenu) self.fileMenu.addSeparator() self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.saveAsAct) self.fileMenu.addAction(self.closeAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) ### Edit Menu ### self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.editUndoAct) self.editMenu.addAction(self.editRedoAct) self.editMenu.addSeparator() self.editMenu.addAction(self.editCutAct) self.editMenu.addAction(self.editCopyAct) self.editMenu.addAction(self.editPasteAct) self.editMenu.addAction(self.editSelectAllAct) self.editMenu.addAction(self.editClearAct) self.editMenu.addSeparator() self.editMenu.addAction(self.findAct) ### Project Menu ### self.projectMenu = self.menuBar().addMenu("&Project") self.projectMenu.addAction(self.compileAct) self.projectMenu.addAction(self.stopAct) self.programMenu = self.projectMenu.addMenu("Program Board...") self.programMenu.addAction(self.programAct) self.projectMenu.addSeparator() self.firmwareLibMenu = self.projectMenu.addMenu("Import &Library...") if len(self.firmwareLibActs): for i in range(len(self.firmwareLibActs)): self.firmwareLibMenu.addAction(self.firmwareLibActs[i]) self.connect(self.firmwareLibMenu, QtCore.SIGNAL("triggered (QAction *)"), self.importFirmwareLib) ### Tools Menu ### self.toolsMenu = self.menuBar().addMenu("&Tools") self.toolsMenu.addAction(self.serialMonitorAct) self.toolsMenu.addSeparator() self.boardMenu = self.toolsMenu.addMenu("&Board") #self.boardMenu.addAction(self.boardAnitoAct) self.boardMenu.addAction(self.boardStellarisAct) self.serialPortMenu = self.toolsMenu.addMenu("&Serial Port") self.serialPortGroup = QtGui.QActionGroup(self) self.connect(self.serialPortMenu, QtCore.SIGNAL("aboutToShow ()"), self.updateSerialPortList ) self.updateSerialPortList() self.toolsMenu.addSeparator() self.toolsMenu.addAction(self.restoreDefaultsAct) # todo: create settings dialog #self.bootloaderMenu = self.toolsMenu.addMenu("&Booloader") ### Help Menu ### self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.visitProjectprotoSiteAct) self.helpMenu.addAction(self.visitPhilroboticsSiteAct) self.helpMenu.addAction(self.aboutCompilerAct) self.helpMenu.addAction(self.aboutQtAct) self.helpMenu.addAction(self.aboutAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.setObjectName("FileToolBar") self.fileToolBar.addAction(self.newAct) self.fileToolBar.addAction(self.openAct) self.fileToolBar.addAction(self.saveAct) self.projectToolBar = self.addToolBar("Project") self.projectToolBar.setObjectName("ProjectToolBar") self.projectToolBar.addAction(self.compileAct) self.projectToolBar.addAction(self.stopAct) self.projectToolBar.addAction(self.programAct) self.serialToolBar = self.addToolBar("Serial Port") self.serialToolBar.setObjectName("SerialPortToolBar") self.serialToolBar.addAction(self.serialMonitorAct) self.serialToolBar.addWidget(self.serialPortLabel) def createStatusBar(self): self.statusBar().showMessage("Ready") def createLogWindow(self): self.log = QtGui.QTextEdit(self) self.log.setReadOnly(True) self.log.resize(self.width(), 100 ) self.log.setText("Ready") palette = QtGui.QPalette(QtGui.QColor(0, 0, 0)) palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, QtGui.QColor(25, 10, 0)) self.log.setPalette(palette) logWindow = QtGui.QDockWidget("Log", self) logWindow.setObjectName("LogView") logWindow.setWidget(self.log) self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, logWindow) def insertLog(self, log='', resetWindow=False): if resetWindow: self.log.setText('') self.log.append(log) def timerEvent(self, *args, **kwargs): timerID = args[0].timerId() if timerID == self.pollCompilerTimerID: ret, msg = self.Compiler.pollBuildProcess() if ret: if len( msg ): self.insertLog( msg ) else: self.killTimer(timerID) self.pollCompilerTimerID = None if timerID == self.pollLoaderTimerID: ret, msg = self.flashLoader.pollBootLoadProcess() if ret: if len(msg): self.insertLog( msg ) else: self.killTimer(timerID) self.pollLoaderTimerID = None return QtGui.QMainWindow.timerEvent(self, *args, **kwargs) def closeEvent(self, event): if not self.Editor.closeAllTabs(): # check for unsaved changes in the project(s) event.ignore() return self.Configs.saveIdeSettings(self.serialPortName) return QtGui.QMainWindow.closeEvent(self, event)
def about(self) -> None: """ Show About dialog (info about application)""" dlg = AboutDialog() dlg.exec_()
def openAbout(self): """Slot for opening the About box.""" dlg = AboutDialog() dlg.show() dlg.exec_()
def about(self): dlg = AboutDialog() dlg.exec_()
def on_actionAbout_triggered(self): about = AboutDialog() about.exec_()
def helpAbout(self): self.aboutDialog = AboutDialog() self.aboutDialog.show()
class ShtoomMainWindow(ShtoomBaseWindow, ShtoomBaseUI): sending = False audiosource = None cookie = None _muted = False def __init__(self, *args, **kwargs): self._newCallURL = None self.dtmf = DTMF() self.dtmf.main = self self.debugging = Debugging() ShtoomBaseWindow.__init__(self, *args, **kwargs) def debugMessage(self, message): print message log.msg(message, system="ui") def statusMessage(self, message): self.statusLabel.setText(message) def errorMessage(self, message, exception=None): log.msg("%s: %s" % (_("ERROR"), message), system="ui") def hangupButton_clicked(self): self.app.dropCall(self.cookie) self.callButton.setEnabled(True) self.hangupButton.setEnabled(False) self.cookie = None def register_clicked(self): self.app.register() def callButton_clicked(self): sipURL = str(self.addressComboBox.currentText()).strip() if not sipURL: return self.addressComboBox.setCurrentText(sipURL) self.addressComboBox.insertItem(QString(sipURL)) self._newCallURL = sipURL self.callButton.setEnabled(False) defer = self.app.placeCall(sipURL) defer.addCallbacks(self.callConnected, self.callFailed).addErrback(log.err) def callStarted(self, cookie): print "started", cookie self.cookie = cookie self.hangupButton.setEnabled(True) self.statusMessage(_("Calling...")) def callFailed(self, e, message=None): self.errorMessage("call failed", e.getErrorMessage()) self.statusMessage(_("Call Failed")) self.hangupButton.setEnabled(False) self.callButton.setEnabled(True) self.cookie = None def callConnected(self, cookie): self.hangupButton.setEnabled(True) self.statusMessage(_("Call Connected")) if self._muted: self.app.muteCall(self.cookie) def callDisconnected(self, cookie, message): self.statusMessage("%s: %s" % (_("Call Disconnected"), message)) self.hangupButton.setEnabled(False) self.callButton.setEnabled(True) self.cookie = None def getLogger(self): l = Logger(self.debugging.debuggingTextEdit) return l def editPreferences(self): from prefs import PreferencesDialog self.prefs = PreferencesDialog(self, self.app.getOptions()) self.prefs.show() def preferences_save(self, options): self.app.updateOptions(options) self.prefs.hide() def preferences_discard(self): self.prefs.hide() def incomingCall(self, description, cookie): # XXX not good. Blockage. Argh. from twisted.internet import defer from shtoom.exceptions import CallRejected accept = QMessageBox.information( self, "Shtoom", "Incoming Call: %s\nAnswer?" % description, "Yes", "No", "", 0, 1 ) print "accept is", accept if accept == 0: self.cookie = cookie self.callButton.setEnabled(False) self.addressComboBox.setEnabled(False) return defer.succeed(cookie) else: return defer.fail(CallRejected(cookie)) def muteCheck_stateChanged(self, val): if val: self._muted = True else: self._muted = False if self.cookie is not None: if val: self.app.muteCall(self.cookie) else: self.app.unmuteCall(self.cookie) def startDTMF(self, key): if self.cookie: self.app.startDTMF(self.cookie, key) def stopDTMF(self, key): if self.cookie: self.app.stopDTMF(self.cookie, key) def fileDTMF(self, *args): self.dtmf.show() def fileDebugging(self, *args): self.debugging.show() def _gotAuth(self, res): self._authdialog = None return res def getAuth(self, method, realm): # XXX tofix we should queue auth requests self._authdialog = AuthDialog() d = self._authdialog.getAuth(method, realm) d.addCallback(self._gotAuth) return d def __tr(self, str): return QString(_(str)) def registerButton_clicked(self): self.app.register() def fileExit(self): from twisted.internet import reactor reactor.stop() def helpAbout(self): self.aboutDialog = AboutDialog() self.aboutDialog.show()
def slotShowAbout(self): self.aboutDialog = AboutDialog(self) self.aboutDialog.show()
def about(self): AboutDialog(self.app).exec_()
def __init__(self, *args): Qt.QMainWindow.__init__(self, *args) self.resize(800, 600) self.setWindowTitle("PlotMeNow") centralWidget = QtGui.QWidget(self) gridLayout = QtGui.QGridLayout(centralWidget) gridLayout.setMargin(0) plot = CartesianPlot(centralWidget) gridLayout.addWidget(plot, 0, 0, 1, 1) self.setCentralWidget(centralWidget) def addToolBar(parent, name): toolBar = QtGui.QToolBar(parent) toolBar.setWindowTitle(name) parent.addToolBar(QtCore.Qt.TopToolBarArea, toolBar) return toolBar toolBar = addToolBar(self, u'Сессия') def genButton(name, res, *args): return toolBar.addAction(QtGui.QIcon(QtGui.QPixmap(":/image/%s.png" % res)), name, *args) def projSaveAs(): print 'projSaveAs()', pc.isChanged() fileName = QtGui.QFileDialog.getSaveFileName(self, u'Сохранить сессию', '.', 'PlotMeNow (*.pmn)') if not fileName.isNull(): return pc.save(unicode(fileName)) return False def projSave(): print 'projSave()', pc.isChanged() if not pc.onDisk(): return projSaveAs() return pc.save() def projNew(): print 'projNew()', pc.isChanged() if pc.isChanged(): reply = QtGui.QMessageBox.question(self, u'Несохраненные изменения', u'Сохранить текущую сессию?', QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Save: projSave() elif reply == QtGui.QMessageBox.Cancel: return self.e.setAB(None, None) print '1', pc.getElements() ret = pc.new() print '2', pc.getElements() if ret: for i in xrange(comboBoxF.count()): comboBoxF.setItemData(i, None) print '3', pc.getElements() print 'comboBoxF.clear()' comboBoxF.clear() print '4', pc.getElements() self.l.destroy() del self.l self.l = None print '5', pc.getElements() self.l = pc.create(Lagrange.__name__) self.l.setEditing() print '6', pc.getElements() self.e.setAB(None, self.l) print 'Control elems', pc.getElements() self.e.reconnect() self.e.setB(self.l) plot.replot() else: if comboBoxF.count() > 0: index = comboBoxF.currentIndex() obj = comboBoxF.itemData(index).toPyObject() self.e.setAB(obj, self.l) return ret def projOpen(): print 'projOpen()', pc.isChanged() fileName = QtGui.QFileDialog.getOpenFileName(self, u'Открыть сессию', '.', 'PlotMeNow (*.pmn)') if not fileName.isNull(): if pc.isChanged() and QtGui.QMessageBox.Save == QtGui.QMessageBox.question(self, u'Несохраненные изменения', u'Сохранить текущую сессию?', QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard, QtGui.QMessageBox.Save): projSave() #return pc.load(unicode(fileName)) self.e.setAB(None, None) print '1', pc.getElements() ret = pc.load(unicode(fileName)) print '2', pc.getElements() if ret: """ self.l.destroy() self.ep.destroy() pc.detach(self.l) pc.detach(self.ep) del self.l del self.ep self.l = None self.ep = None self.l = pc.getElementsByClassName(Lagrange.__name__).pop() self.ep = pc.getElementsByClassName(EvalPlot.__name__).pop() self.e.setAB(self.ep, self.l) plot.replot() """ """ for ep in pc.getElementsByClassName(EvalPlot.__name__): pc.detach(ep) ep.destroy() del ep ep = None self.l.destroy() pc.detach(self.l) del self.l self.l = None """ self.l = pc.getElementsByClassName(Lagrange.__name__).pop() print '3', pc.getElements() print 'comboBoxF.clear()' comboBoxF.clear() print '4', pc.getElements() print 'for ep in pc.getElementsByClassName(EvalPlot.__name__)' for ep in pc.getElementsByClassName(EvalPlot.__name__): f = ep.getExpression() if f is None: print 'Warning!', ep, 'has None function' else: comboBoxF.addItem(f, ep) print '5', pc.getElements() if comboBoxF.count() > 0: index = comboBoxF.currentIndex() obj = comboBoxF.itemData(index).toPyObject() self.e.setA(obj) self.e.reconnect() self.e.setB(self.l).replot() return ret return False projectNew = genButton(u"Новый", "new", projNew) projectOpen = genButton(u"Открыть", "open", projOpen) projectSave = genButton(u"Сохранить", "fileSave", projSave) projectSaveAs = genButton(u"Сохранить как", "fileSaveAs", projSaveAs) toolBar = addToolBar(self, u'Навигация') #toolBar.addSeparator() editUndo = genButton(u"Отменить действие", "editUndo", lambda: pc.undo()) editRedo = genButton(u"Вернуть действие", "editRedo", lambda: pc.redo()) toolBar = addToolBar(self, u'Выражения') #toolBar.addSeparator() comboBoxF = QtGui.QComboBox(toolBar) comboBoxF.setMinimumSize(QtCore.QSize(220, 0)) #comboBoxF.addItems(['4*pi*sin(x)*cos(x)^2', 'x^2', 'e^(-x^2)']) comboBoxF.setEditable(True) comboBoxF.setIconSize(QtCore.QSize(16, 16)) toolBar.addAction("f(x):") toolBar.addWidget(comboBoxF) #QtCore.QObject.connect(comboBoxF, QtCore.SIGNAL("editTextChanged(QString)"), lambda x: self.ep.setExpression(x)) #QtCore.QObject.connect(comboBoxF, QtCore.SIGNAL("currentIndexChanged(QString)"), lambda x: self.ep.setExpression(x)) #QtCore.QObject.connect(comboBoxF, QtCore.SIGNAL("currentIndexChanged(int)"), lambda i: self.e.setA(comboBoxF.itemData(i).toPyObject()).replot()) def currentIndexChanged(index): print 'currentIndexChanged', index if index > -1: obj = comboBoxF.itemData(index).toPyObject() if obj is None: obj = pc.create(EvalPlot.__name__, comboBoxF.itemText(index)) comboBoxF.setItemData(index, obj) self.e.reconnect() self.e.setA(obj) else: self.e.setA(None) self.e.replot() #def editTextChanged(text): QtCore.QObject.connect(comboBoxF, QtCore.SIGNAL("currentIndexChanged(int)"), currentIndexChanged) #QtCore.QObject.connect(comboBoxF, QtCore.SIGNAL("editTextChanged(QString)"), editTextChanged) deleteButtonF = QtGui.QPushButton(QtGui.QIcon(QtGui.QPixmap(":/image/editDelete.png")), '', toolBar) deleteButtonF.setIconSize(QtCore.QSize(12, 12)) deleteButtonF.setMaximumSize(QtCore.QSize(22, 22)) #QtCore.QObject.connect(deleteButtonF, QtCore.SIGNAL("clicked()"), lambda: comboBoxF.removeItem(comboBoxF.currentIndex())) def deleteEP(): if comboBoxF.count() == 0: return index = comboBoxF.currentIndex() obj = comboBoxF.itemData(index).toPyObject() pc.detach(obj) obj.destroy() del obj comboBoxF.removeItem(index) QtCore.QObject.connect(deleteButtonF, QtCore.SIGNAL("clicked()"), deleteEP) toolBar.addWidget(deleteButtonF) toolBar = addToolBar(self, u'Отчет') #toolBar.addSeparator() #generateReportAction = genButton(u"Составить отчет", "fileResource", lambda: generateReport(self, plot, [unicode(comboBoxF.itemText(i)) for i in xrange(comboBoxF.count())], [l])) generateReportAction = genButton(u"Составить отчет", "fileResource", lambda: generateReport(self, plot, pc.getElementsByClassName(EvalPlot.__name__), pc.getElementsByClassName(Lagrange.__name__))) toolBar = addToolBar(self, u'Справка') #toolBar.addSeparator() helpAction = genButton(u"Справка", "help", lambda: HelpDialog(self).show()) aboutAction = genButton(u"О программе", "helpAbout", lambda: AboutDialog(self).show()) pc = PlotControl(plot, editUndo.setEnabled, editRedo.setEnabled) #self.ep = EvalPlot(plot, '4*pi*sin(x)*cos(x)^2') self.l = Lagrange(plot) #self.e = Epsilon(plot, self.ep, self.l) self.l.setEditing() self.e = Epsilon(plot, None, self.l) func = ['4*pi*sin(x)*cos(x)^2', 'x^2', 'e^(-x^2)'] for f in func: comboBoxF.addItem(f, pc.create(EvalPlot.__name__, f)) self.e.reconnect() pc.attach(self.l) #pc.attach(self.ep) picker = Qwt.QwtPlotPicker(Qwt.QwtPlot.xBottom, Qwt.QwtPlot.yLeft, Qwt.QwtPicker.DragSelection, Qwt.QwtPlotPicker.CrossRubberBand, Qwt.QwtPicker.AlwaysOn, plot.canvas())
def OnMenuAbout(self, event): # Open the About dialog self.about = AboutDialog(VERSION) self.about.ShowModal() self.about.Destroy() self.about = None
def about_event_handler(self, event=None): AboutDialog(self.master)
def on_actionAbout_triggered(self): AboutDialog(self).exec_()
def act_about_triggered(self): about_dlg = AboutDialog(self) about_dlg.set_version(VERSION) about_dlg.show()
def menu_about(self, *args): AboutDialog()
def about_action_triggered(self): about_window = AboutDialog() about_window.exec_()
def open_about(self): dialog = QDialog(self.centralwidget, Qt.WindowCloseButtonHint) about = AboutDialog() about.setupUi(dialog) dialog.show() dialog.exec_()
def open_preferences_dialog(self): """Open a dialog with preferences.""" # TODO: implement the preferences dialog box messages = ['Not yet implemented!', ''] self.preferences_dialog = AboutDialog('Preferences', messages, self)
class MyFrame(wx.Frame): def __init__(self, parent, title, db, defaultPrefs, capabilities): wx.Frame.__init__(self, parent, -1, title, style=wx.NO_BORDER | wx.FRAME_NO_TASKBAR | wx.CLIP_CHILDREN) self.db = db self.capabilities = capabilities self.data = [] self.options = None self.about = None self.prefs = Prefs(self.db, defaultPrefs) # Don't allow the user to shrink the window below these dimensions self.minYSize = 30 self.minXSize = 50 # This is the main graph self.panel = wx.Panel(self, style=wx.BORDER_SIMPLE) self.panel.Bind(wx.EVT_MOTION, self.OnPanelMove) self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnPanelDown) self.panel.Bind(wx.EVT_LEFT_UP, self.OnPanelUp) self.panel.Bind(wx.EVT_PAINT, self.OnPanelPaint) # This is the label below the graph showing numeric values self.label = wx.StaticText(self, -1, "-", style=wx.ST_NO_AUTORESIZE | wx.BORDER_SIMPLE | wx.ALIGN_CENTER) self.label.Bind(wx.EVT_LEFT_DOWN, self.OnLabelDown) self.Bind(wx.EVT_MOTION, self.OnLabelMove) self.Bind(wx.EVT_LEFT_UP, self.OnLabelUp) self.label.SetCursor(wx.Cursor(wx.CURSOR_SIZENWSE)) self.label.SetFont( wx.Font(8, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) box = wx.BoxSizer(wx.VERTICAL) box.Add(self.panel, 1, flag=wx.EXPAND) box.Add((10, 1), 0) box.Add(self.label, 0, flag=wx.EXPAND) # Restore the position of the graph from last time self.SetPosition(self.prefs.GetObj('position')) # If you remove a monitor or replace with a lower resolution one, it is possible # that the preferences specify an x,y position that is off screen # This rough code will reset the position assuming that # - the monitors are placed left to right (not on top of each other) # - the rightmost monitor has the least resolution # - bitmeter-desktop client is on the rightmost screen normally displays = (wx.Display(i) for i in range(wx.Display.GetCount())) maxX = 0 maxY = 10000 for v in displays: maxX += v.GetGeometry().GetSize().width if maxY > v.GetGeometry().GetSize().height: maxY = v.GetGeometry().GetSize().height PROPORTION = 4 # Is allowed to be a little off screen resetPosition = False farRight = self.GetPosition().x + self.GetSize().width / PROPORTION if farRight > maxX: resetPosition = True print('Reset position due to out of bounds x position') farDown = self.GetPosition().y + self.GetSize().height / PROPORTION if farDown > maxY: resetPosition = True print('Reset position due to out of bounds y position') if resetPosition: self.SetPosition((100, 100)) self.OnPrefsUpdated() self.SetSizer(box) self.Fit() self.SetSize(self.prefs.GetObj('size')) # We update the graph each second with new data self.timer = wx.Timer(self) self.timer.Start(1000) self.Bind(wx.EVT_TIMER, self.OnTimer) self.InitBuffer() self.Bind(wx.EVT_IDLE, self.OnIdle) # Find the file-system location where we are running from encoding = sys.getfilesystemencoding() if hasattr(sys, "frozen"): self.modulePath = os.path.dirname(sys.executable) else: self.modulePath = os.path.dirname(__file__) iconPath = os.path.join(self.modulePath, "resources", "bitmeter.ico") icon = wx.Icon(iconPath, wx.BITMAP_TYPE_ICO) # The menu can be accessed from the main graph, and from the tray icon self.popupmenu = wx.Menu() self.trayIcon = TrayIcon(self, self.popupmenu, icon) # Hide Graph option removed - no tray icon shown on Ubuntu 18.04, not relevant # self.showHideMain = self.popupmenu.Append(-1, _("Hide Graph")) # self.Bind(wx.EVT_MENU, self.ToggleGraph) # self.trayIcon.Bind(wx.EVT_MENU, self.ToggleGraph) # Menu item to open the Options dialog options = self.popupmenu.Append(-1, _("Options")) self.Bind(wx.EVT_MENU, self.OnMenuOptions, options) self.trayIcon.Bind(wx.EVT_MENU, self.OnMenuOptions, options) # Menu item to open the Web Interface webInterface = self.popupmenu.Append(-1, _("Web Interface")) self.Bind(wx.EVT_MENU, self.OnMenuWebInterface, webInterface) self.trayIcon.Bind(wx.EVT_MENU, self.OnMenuWebInterface, webInterface) # Need this to build the web interface url self.webPort = self.db.GetConfigValue('web.port', 2605) # Menu item to open the About dialog about = self.popupmenu.Append(-1, _("About")) self.Bind(wx.EVT_MENU, self.OnMenuAbout, about) self.trayIcon.Bind(wx.EVT_MENU, self.OnMenuAbout, about) self.popupmenu.AppendSeparator() # Menu item to quit he application exit = self.popupmenu.Append(-1, _("Exit")) self.Bind(wx.EVT_MENU, self.OnMenuExit, exit) self.trayIcon.Bind(wx.EVT_MENU, self.OnMenuExit, exit) self.Bind(wx.EVT_CONTEXT_MENU, self.OnShowPopup) self.Bind(wx.EVT_CLOSE, self.OnClose) def ToggleGraph(self, event): # Show/Hide the graph self.Show(not self.IsShown()) if self.IsShown(): self.showHideMain.SetText(_('Hide Graph')) else: self.showHideMain.SetText(_('Show Graph')) def FormatScale(self, scale): # This value gets displayed to the left of the download and upload amounts return "{:,}".format(int(scale / BYTES_PER_K)).replace(',', ' ') + ' KB' def FormatAmounts(self, dl, ul): # This value gets displayed below the main graph return "D: %.2f U: %.2f" % (float(dl) / 1000, float(ul) / 1000) def OnShowPopup(self, event): pos = event.GetPosition() pos = self.panel.ScreenToClient(pos) self.panel.PopupMenu(self.popupmenu, pos) def OnMenuWebInterface(self, event): # Open the web interface in the default browser webbrowser.open("http://localhost:" + str(self.webPort) + "/index.html") def OnMenuAbout(self, event): # Open the About dialog self.about = AboutDialog(VERSION) self.about.ShowModal() self.about.Destroy() self.about = None def OnMenuExit(self, event): # Close all open windows if self.options: self.options.Close() if self.about: self.about.Close() self.Close() def OnClose(self, event): # Store the current size/position of the graph before exiting self.prefs.SetObj('size', self.GetSize()) self.prefs.SetObj('position', self.GetPosition()) self.prefs.Save() self.trayIcon.RemoveIcon() self.trayIcon.Destroy() self.Destroy() def OnPrefsUpdated(self): # Callback invoked from the Options dialog when the user clicks 'OK' if self.capabilities['opacity']: self.SetTransparent(int(self.prefs.GetNum('opacity') * 2.55)) self.SetBackgroundColour(self.prefs.GetCol('bgcolour')) self.dlPen = wx.Pen(self.prefs.GetCol('dlcolour'), 1) self.ulPen = wx.Pen(self.prefs.GetCol('ulcolour'), 1) self.olPen = wx.Pen(self.prefs.GetCol('olcolour'), 1) self.scale = self.prefs.GetNum('scale') if not (self.prefs.GetObj('float') ^ (not self.HasFlag(wx.STAY_ON_TOP))): # Set the 'Stay On Top' flag to the appropriate value self.ToggleWindowStyle(wx.STAY_ON_TOP) if self.capabilities['clickthru']: # Windows only, window passes all mouse clicks to whatever is underneath if not (self.prefs.GetObj('clickthru') ^ (not self.HasFlag(wx.TRANSPARENT_WINDOW))): self.ToggleWindowStyle(wx.TRANSPARENT_WINDOW) def OnMenuOptions(self, event): # Open the Options dialog self.options = OptionsDialog(self, self.prefs, self.capabilities, self.OnPrefsUpdated) self.options.ShowModal() self.options.Destroy() self.options = None def OnPanelDown(self, event): # Mouse down over the graph means we want to drag the window self._panelDownPos = event.GetPosition() if not self.panel.HasCapture(): self.panel.CaptureMouse() def OnPanelMove(self, event): if event.Dragging() and event.LeftIsDown(): # The window is being dragged pos = event.GetPosition() displacement = self._panelDownPos - pos self.SetPosition(self.GetPosition() - displacement) print('pos:', self.GetPosition()) def OnPanelUp(self, event): # Stop dragging the window if self.panel.HasCapture(): self.panel.ReleaseMouse() def GetEventYInWindow(self, event): # Calculate the y-coordinate of a mouse click within the label, relative to the whole window return self.GetSize().height - self.label.GetSize( ).height + event.GetPosition().y def OnLabelDown(self, event): # Mouse down in the label means we want to resize the window self._prevXInWindow = event.GetPosition().x self._prevYInWindow = self.GetEventYInWindow(event) self._origWidth = self.GetSize().width self._origHeight = self.GetSize().height if not self.HasCapture(): self.CaptureMouse() def OnLabelMove(self, event): # Mouse move in the label means we should resize the window if event.Dragging(): pos = event.GetPosition() displacementX = self._prevXInWindow - pos.x displacementY = self._prevYInWindow - pos.y newXSize = self._origWidth - displacementX newYSize = self._origHeight - displacementY if newYSize < self.minYSize: newYSize = self.minYSize if newXSize < self.minXSize: newXSize = self.minXSize self.SetSize(wx.Size(newXSize, newYSize)) self.reInitBuffer = True def OnLabelUp(self, event): # Mouse up in the label means we want to stop resizing if self.HasCapture(): self.ReleaseMouse() def OnPanelPaint(self, event): # Paint the graph with whatever is in our in-memory buffer dc = wx.BufferedPaintDC(self.panel, self.buffer) def OnIdle(self, event): if self.reInitBuffer: # We have new data to be displayed self.InitBuffer() self.Refresh(False) def InitBuffer(self): # Draw the next graph to be displayed onto the in-memory buffer size = self.panel.GetSize() self.buffer = wx.Bitmap(size.width, size.height) dc = wx.BufferedDC(None, self.buffer) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() self.DrawLines(dc) self.reInitBuffer = False def DrawLines(self, dc): # Draw the graph using the current upload/download values h = self.panel.GetSize().height w = self.panel.GetSize().width now = time.time() ts = 0 self.autoScale = self.scale * BYTES_PER_K for d in self.data: if d[1] > self.autoScale: self.autoScale = d[1] if d[2] > self.autoScale: self.autoScale = d[2] for d in self.data: ts = d[0] dl = d[1] ul = d[2] # For the graph to move left to right # x = now - ts - 1 # For the graph to move right to left x = ts - now + 1 + w y0 = h yDl = y0 - dl * h / (self.autoScale) yUl = y0 - ul * h / (self.autoScale) if dl < ul: dc.SetPen(self.olPen) dc.DrawLine(x, y0, x, yDl) dc.SetPen(self.ulPen) dc.DrawLine(x, yDl, x, yUl) else: dc.SetPen(self.olPen) dc.DrawLine(x, y0, x, yUl) dc.SetPen(self.dlPen) dc.DrawLine(x, yUl, x, yDl) def OnTimer(self, event): # Query the database to get the latest values now = int(time.time()) results = self.db.GetData(now - self.GetSize().width, now) # Store the results and set the flag indicating that the graph should be re-drawn self.data = results[1] self.reInitBuffer = True self.panel.Refresh() self.label.SetLabel( self.FormatScale(self.autoScale) + ' ' + self.FormatAmounts(results[0][0], results[0][1]))
def on_about(self, event): """Show the about box""" dlg = AboutDialog(self, -1, "About") dlg.ShowModal() dlg.Destroy()