def set_corner_widgets(self, corner_widgets): """ Set tabs corner widgets corner_widgets: dictionary of (corner, widgets) corner: Qt.TopLeftCorner or Qt.TopRightCorner widgets: list of widgets (may contains integers to add spacings) """ assert isinstance(corner_widgets, dict) assert all(key in (Qt.TopLeftCorner, Qt.TopRightCorner) for key in corner_widgets) self.corner_widgets.update(corner_widgets) for corner, widgets in self.corner_widgets.iteritems(): cwidget = QWidget() cwidget.hide() prev_widget = self.cornerWidget(corner) if prev_widget: prev_widget.close() self.setCornerWidget(cwidget, corner) clayout = QHBoxLayout() clayout.setContentsMargins(0, 0, 0, 0) for widget in widgets: if isinstance(widget, int): clayout.addSpacing(widget) else: clayout.addWidget(widget) cwidget.setLayout(clayout) cwidget.show()
def hide(self): """Overrides Qt Method""" for widget in self.replace_widgets: widget.hide() QWidget.hide(self) if self.editor is not None: self.editor.setFocus()
def hide(self): """Overrides Qt Method""" for widget in self.replace_widgets: widget.hide() QWidget.hide(self) self.emit(SIGNAL("visibility_changed(bool)"), False) if self.editor is not None: self.editor.setFocus()
class DocumentationTab(QWidget): def __init__(self, mainwindow, filePath): QWidget.__init__(self, mainwindow) self.mainwindow = mainwindow self.tabIcon = QIcon(":/Images/Images/chart_organisation.png") self.tabLabel = "Documentation Tab" self.tab = QWidget(self.mainwindow) self.widgetLayout = QVBoxLayout(self.tab) self.widgetLayout.setAlignment(Qt.AlignTop) self.docStatusLabel = QLabel(self.tab) self.docStatusLabel.setAlignment(Qt.AlignCenter) self.docStatusLabel.setObjectName("docStatusLabel") self.docStatusLabel.setText( QString("No documentation currently loaded...")) self.widgetLayout.addWidget(self.docStatusLabel) self.pbnRemoveDoc = QPushButton(self.tab) self.pbnRemoveDoc.setObjectName("pbnRemoveDoc") self.pbnRemoveDoc.setText(QString("Remove Documentation")) QObject.connect(self.pbnRemoveDoc, SIGNAL("clicked()"), self.clicked) self.widgetLayout.addWidget(self.pbnRemoveDoc) self.docStuff = DocumentationBase(self.mainwindow, filePath) self.widgetLayout.addWidget(self.docStuff) self.docStatusLabel.setText(QString(filePath)) self.mainwindow.tabWidget.insertTab(0, self.tab, self.tabIcon, self.tabLabel) self.mainwindow.tabWidget.setCurrentIndex(0) def clicked(self): print "Remove Documentation Pressed..." self.mainwindow.tabWidget.removeTab( self.mainwindow.tabWidget.indexOf(self.tab)) self.tab.hide()
class DocumentationTab(QWidget): def __init__(self, mainwindow, filePath): QWidget.__init__(self, mainwindow) self.mainwindow = mainwindow self.tabIcon = QIcon(":/Images/Images/chart_organisation.png") self.tabLabel = "Documentation Tab" self.tab = QWidget(self.mainwindow) self.widgetLayout = QVBoxLayout(self.tab) self.widgetLayout.setAlignment(Qt.AlignTop) self.docStatusLabel = QLabel(self.tab) self.docStatusLabel.setAlignment(Qt.AlignCenter) self.docStatusLabel.setObjectName("docStatusLabel") self.docStatusLabel.setText(QString("No documentation currently loaded...")) self.widgetLayout.addWidget(self.docStatusLabel) self.pbnRemoveDoc = QPushButton(self.tab) self.pbnRemoveDoc.setObjectName("pbnRemoveDoc") self.pbnRemoveDoc.setText(QString("Remove Documentation")) QObject.connect(self.pbnRemoveDoc, SIGNAL("clicked()"), self.clicked) self.widgetLayout.addWidget(self.pbnRemoveDoc) self.docStuff = DocumentationBase(self.mainwindow,filePath) self.widgetLayout.addWidget(self.docStuff) self.docStatusLabel.setText(QString(filePath)) self.mainwindow.tabWidget.insertTab(0,self.tab,self.tabIcon,self.tabLabel) self.mainwindow.tabWidget.setCurrentIndex(0) def clicked(self): print "Remove Documentation Pressed..." self.mainwindow.tabWidget.removeTab(self.mainwindow.tabWidget.indexOf(self.tab)) self.tab.hide()
class PythonConsoleWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle( QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QSettings() self.shell = ShellScintilla(self) self.setFocusProxy(self.shell) self.shellOut = ShellOutputScintilla(self) self.tabEditorWidget = EditorTabWidget(self) ##------------ UI ------------------------------- self.splitterEditor = QSplitter(self) self.splitterEditor.setOrientation(Qt.Horizontal) self.splitterEditor.setHandleWidth(6) self.splitterEditor.setChildrenCollapsible(True) self.splitter = QSplitter(self.splitterEditor) self.splitter.setOrientation(Qt.Vertical) self.splitter.setHandleWidth(3) self.splitter.setChildrenCollapsible(False) self.splitter.addWidget(self.shellOut) self.splitter.addWidget(self.shell) #self.splitterEditor.addWidget(self.tabEditorWidget) self.splitterObj = QSplitter(self.splitterEditor) self.splitterObj.setHandleWidth(3) self.splitterObj.setOrientation(Qt.Horizontal) #self.splitterObj.setSizes([0, 0]) #self.splitterObj.setStretchFactor(0, 1) self.widgetEditor = QWidget(self.splitterObj) self.widgetFind = QWidget(self) self.listClassMethod = QTreeWidget(self.splitterObj) self.listClassMethod.setColumnCount(2) objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector") self.listClassMethod.setHeaderLabels([objInspLabel, '']) self.listClassMethod.setColumnHidden(1, True) self.listClassMethod.setAlternatingRowColors(True) #self.splitterEditor.addWidget(self.widgetEditor) #self.splitterObj.addWidget(self.listClassMethod) #self.splitterObj.addWidget(self.widgetEditor) # Hide side editor on start up self.splitterObj.hide() self.listClassMethod.hide() # Hide search widget on start up self.widgetFind.hide() sizes = self.splitter.sizes() self.splitter.setSizes(sizes) ##----------------Restore Settings------------------------------------ self.restoreSettingsConsole() ##------------------Toolbar Editor------------------------------------- ## Action for Open File openFileBt = QCoreApplication.translate("PythonConsole", "Open file") self.openFileButton = QAction(self) self.openFileButton.setCheckable(False) self.openFileButton.setEnabled(True) self.openFileButton.setIcon( QgsApplication.getThemeIcon("console/iconOpenConsole.png")) self.openFileButton.setMenuRole(QAction.PreferencesRole) self.openFileButton.setIconVisibleInMenu(True) self.openFileButton.setToolTip(openFileBt) self.openFileButton.setText(openFileBt) ## Action for Save File saveFileBt = QCoreApplication.translate("PythonConsole", "Save") self.saveFileButton = QAction(self) self.saveFileButton.setCheckable(False) self.saveFileButton.setEnabled(False) self.saveFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveConsole.png")) self.saveFileButton.setMenuRole(QAction.PreferencesRole) self.saveFileButton.setIconVisibleInMenu(True) self.saveFileButton.setToolTip(saveFileBt) self.saveFileButton.setText(saveFileBt) ## Action for Save File As saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...") self.saveAsFileButton = QAction(self) self.saveAsFileButton.setCheckable(False) self.saveAsFileButton.setEnabled(True) self.saveAsFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveAsConsole.png")) self.saveAsFileButton.setMenuRole(QAction.PreferencesRole) self.saveAsFileButton.setIconVisibleInMenu(True) self.saveAsFileButton.setToolTip(saveAsFileBt) self.saveAsFileButton.setText(saveAsFileBt) ## Action Cut cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut") self.cutEditorButton = QAction(self) self.cutEditorButton.setCheckable(False) self.cutEditorButton.setEnabled(True) self.cutEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconCutEditorConsole.png")) self.cutEditorButton.setMenuRole(QAction.PreferencesRole) self.cutEditorButton.setIconVisibleInMenu(True) self.cutEditorButton.setToolTip(cutEditorBt) self.cutEditorButton.setText(cutEditorBt) ## Action Copy copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy") self.copyEditorButton = QAction(self) self.copyEditorButton.setCheckable(False) self.copyEditorButton.setEnabled(True) self.copyEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png")) self.copyEditorButton.setMenuRole(QAction.PreferencesRole) self.copyEditorButton.setIconVisibleInMenu(True) self.copyEditorButton.setToolTip(copyEditorBt) self.copyEditorButton.setText(copyEditorBt) ## Action Paste pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste") self.pasteEditorButton = QAction(self) self.pasteEditorButton.setCheckable(False) self.pasteEditorButton.setEnabled(True) self.pasteEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png")) self.pasteEditorButton.setMenuRole(QAction.PreferencesRole) self.pasteEditorButton.setIconVisibleInMenu(True) self.pasteEditorButton.setToolTip(pasteEditorBt) self.pasteEditorButton.setText(pasteEditorBt) ## Action Run Script (subprocess) runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script") self.runScriptEditorButton = QAction(self) self.runScriptEditorButton.setCheckable(False) self.runScriptEditorButton.setEnabled(True) self.runScriptEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconRunScriptConsole.png")) self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole) self.runScriptEditorButton.setIconVisibleInMenu(True) self.runScriptEditorButton.setToolTip(runScriptEditorBt) self.runScriptEditorButton.setText(runScriptEditorBt) ## Action Run Script (subprocess) commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment") self.commentEditorButton = QAction(self) self.commentEditorButton.setCheckable(False) self.commentEditorButton.setEnabled(True) self.commentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconCommentEditorConsole.png")) self.commentEditorButton.setMenuRole(QAction.PreferencesRole) self.commentEditorButton.setIconVisibleInMenu(True) self.commentEditorButton.setToolTip(commentEditorBt) self.commentEditorButton.setText(commentEditorBt) ## Action Run Script (subprocess) uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment") self.uncommentEditorButton = QAction(self) self.uncommentEditorButton.setCheckable(False) self.uncommentEditorButton.setEnabled(True) self.uncommentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconUncommentEditorConsole.png")) self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole) self.uncommentEditorButton.setIconVisibleInMenu(True) self.uncommentEditorButton.setToolTip(uncommentEditorBt) self.uncommentEditorButton.setText(uncommentEditorBt) ## Action for Object browser objList = QCoreApplication.translate("PythonConsole", "Object Inspector") self.objectListButton = QAction(self) self.objectListButton.setCheckable(True) self.objectListButton.setEnabled( self.settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.objectListButton.setIcon( QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png")) self.objectListButton.setMenuRole(QAction.PreferencesRole) self.objectListButton.setIconVisibleInMenu(True) self.objectListButton.setToolTip(objList) self.objectListButton.setText(objList) ## Action for Find text findText = QCoreApplication.translate("PythonConsole", "Find Text") self.findTextButton = QAction(self) self.findTextButton.setCheckable(True) self.findTextButton.setEnabled(True) self.findTextButton.setIcon( QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png")) self.findTextButton.setMenuRole(QAction.PreferencesRole) self.findTextButton.setIconVisibleInMenu(True) self.findTextButton.setToolTip(findText) self.findTextButton.setText(findText) ##----------------Toolbar Console------------------------------------- ## Action Show Editor showEditor = QCoreApplication.translate("PythonConsole", "Show editor") self.showEditorButton = QAction(self) self.showEditorButton.setEnabled(True) self.showEditorButton.setCheckable(True) self.showEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.showEditorButton.setMenuRole(QAction.PreferencesRole) self.showEditorButton.setIconVisibleInMenu(True) self.showEditorButton.setToolTip(showEditor) self.showEditorButton.setText(showEditor) ## Action for Clear button clearBt = QCoreApplication.translate("PythonConsole", "Clear console") self.clearButton = QAction(self) self.clearButton.setCheckable(False) self.clearButton.setEnabled(True) self.clearButton.setIcon( QgsApplication.getThemeIcon("console/iconClearConsole.png")) self.clearButton.setMenuRole(QAction.PreferencesRole) self.clearButton.setIconVisibleInMenu(True) self.clearButton.setToolTip(clearBt) self.clearButton.setText(clearBt) ## Action for settings optionsBt = QCoreApplication.translate("PythonConsole", "Settings") self.optionsButton = QAction(self) self.optionsButton.setCheckable(False) self.optionsButton.setEnabled(True) self.optionsButton.setIcon( QgsApplication.getThemeIcon("console/iconSettingsConsole.png")) self.optionsButton.setMenuRole(QAction.PreferencesRole) self.optionsButton.setIconVisibleInMenu(True) self.optionsButton.setToolTip(optionsBt) self.optionsButton.setText(optionsBt) ## Action menu for class actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class") self.actionClass = QAction(self) self.actionClass.setCheckable(False) self.actionClass.setEnabled(True) self.actionClass.setIcon( QgsApplication.getThemeIcon("console/iconClassConsole.png")) self.actionClass.setMenuRole(QAction.PreferencesRole) self.actionClass.setIconVisibleInMenu(True) self.actionClass.setToolTip(actionClassBt) self.actionClass.setText(actionClassBt) ## Import Processing class loadProcessingBt = QCoreApplication.translate( "PythonConsole", "Import Processing class") self.loadProcessingButton = QAction(self) self.loadProcessingButton.setCheckable(False) self.loadProcessingButton.setEnabled(True) self.loadProcessingButton.setIcon( QgsApplication.getThemeIcon("console/iconProcessingConsole.png")) self.loadProcessingButton.setMenuRole(QAction.PreferencesRole) self.loadProcessingButton.setIconVisibleInMenu(True) self.loadProcessingButton.setToolTip(loadProcessingBt) self.loadProcessingButton.setText(loadProcessingBt) ## Import QtCore class loadQtCoreBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore class") self.loadQtCoreButton = QAction(self) self.loadQtCoreButton.setCheckable(False) self.loadQtCoreButton.setEnabled(True) self.loadQtCoreButton.setIcon( QgsApplication.getThemeIcon("console/iconQtCoreConsole.png")) self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole) self.loadQtCoreButton.setIconVisibleInMenu(True) self.loadQtCoreButton.setToolTip(loadQtCoreBt) self.loadQtCoreButton.setText(loadQtCoreBt) ## Import QtGui class loadQtGuiBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui class") self.loadQtGuiButton = QAction(self) self.loadQtGuiButton.setCheckable(False) self.loadQtGuiButton.setEnabled(True) self.loadQtGuiButton.setIcon( QgsApplication.getThemeIcon("console/iconQtGuiConsole.png")) self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole) self.loadQtGuiButton.setIconVisibleInMenu(True) self.loadQtGuiButton.setToolTip(loadQtGuiBt) self.loadQtGuiButton.setText(loadQtGuiBt) ## Action for Run script runBt = QCoreApplication.translate("PythonConsole", "Run command") self.runButton = QAction(self) self.runButton.setCheckable(False) self.runButton.setEnabled(True) self.runButton.setIcon( QgsApplication.getThemeIcon("console/iconRunConsole.png")) self.runButton.setMenuRole(QAction.PreferencesRole) self.runButton.setIconVisibleInMenu(True) self.runButton.setToolTip(runBt) self.runButton.setText(runBt) ## Help action helpBt = QCoreApplication.translate("PythonConsole", "Help") self.helpButton = QAction(self) self.helpButton.setCheckable(False) self.helpButton.setEnabled(True) self.helpButton.setIcon( QgsApplication.getThemeIcon("console/iconHelpConsole.png")) self.helpButton.setMenuRole(QAction.PreferencesRole) self.helpButton.setIconVisibleInMenu(True) self.helpButton.setToolTip(helpBt) self.helpButton.setText(helpBt) self.toolBar = QToolBar() self.toolBar.setEnabled(True) self.toolBar.setFocusPolicy(Qt.NoFocus) self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBar.setLayoutDirection(Qt.LeftToRight) self.toolBar.setIconSize(QSize(24, 24)) self.toolBar.setOrientation(Qt.Vertical) self.toolBar.setMovable(True) self.toolBar.setFloatable(True) self.toolBar.addAction(self.clearButton) self.toolBar.addAction(self.actionClass) self.toolBar.addAction(self.runButton) self.toolBar.addSeparator() self.toolBar.addAction(self.showEditorButton) self.toolBar.addSeparator() self.toolBar.addAction(self.optionsButton) self.toolBar.addAction(self.helpButton) self.toolBarEditor = QToolBar() # self.toolBarEditor.setStyleSheet('QToolBar{background-color: rgb(%s, %s, %s' % tuple(bkgrcolor) + ');\ # border-right: 1px solid rgb(%s, %s, %s' % tuple(bordercl) + ');}') self.toolBarEditor.setEnabled(False) self.toolBarEditor.setFocusPolicy(Qt.NoFocus) self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBarEditor.setLayoutDirection(Qt.LeftToRight) self.toolBarEditor.setIconSize(QSize(18, 18)) self.toolBarEditor.setOrientation(Qt.Vertical) self.toolBarEditor.setMovable(True) self.toolBarEditor.setFloatable(True) self.toolBarEditor.addAction(self.openFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.saveFileButton) self.toolBarEditor.addAction(self.saveAsFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.findTextButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.cutEditorButton) self.toolBarEditor.addAction(self.copyEditorButton) self.toolBarEditor.addAction(self.pasteEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.commentEditorButton) self.toolBarEditor.addAction(self.uncommentEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.objectListButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.runScriptEditorButton) ## Menu Import Class self.classMenu = QMenu() self.classMenu.addAction(self.loadProcessingButton) self.classMenu.addAction(self.loadQtCoreButton) self.classMenu.addAction(self.loadQtGuiButton) cM = self.toolBar.widgetForAction(self.actionClass) cM.setMenu(self.classMenu) cM.setPopupMode(QToolButton.InstantPopup) self.widgetButton = QWidget() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButton.sizePolicy().hasHeightForWidth()) self.widgetButton.setSizePolicy(sizePolicy) self.widgetButtonEditor = QWidget(self.widgetEditor) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButtonEditor.sizePolicy().hasHeightForWidth()) self.widgetButtonEditor.setSizePolicy(sizePolicy) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.shellOut.sizePolicy().hasHeightForWidth()) self.shellOut.setSizePolicy(sizePolicy) self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) ##------------ Layout ------------------------------- self.mainLayout = QGridLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1) self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1) self.layoutEditor = QGridLayout(self.widgetEditor) self.layoutEditor.setMargin(0) self.layoutEditor.setSpacing(0) self.layoutEditor.addWidget(self.widgetButtonEditor, 0, 0, 2, 1) self.layoutEditor.addWidget(self.tabEditorWidget, 0, 1, 1, 1) self.layoutEditor.addWidget(self.widgetFind, 1, 1, 1, 1) self.toolBarLayout = QGridLayout(self.widgetButton) self.toolBarLayout.setMargin(0) self.toolBarLayout.setSpacing(0) self.toolBarLayout.addWidget(self.toolBar) self.toolBarEditorLayout = QGridLayout(self.widgetButtonEditor) self.toolBarEditorLayout.setMargin(0) self.toolBarEditorLayout.setSpacing(0) self.toolBarEditorLayout.addWidget(self.toolBarEditor) ## Layout for the find widget self.layoutFind = QGridLayout(self.widgetFind) self.layoutFind.setContentsMargins(0, 0, 0, 0) self.lineEditFind = QgsFilterLineEdit() placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find...") if pyqtconfig.Configuration().qt_version >= 0x40700: self.lineEditFind.setPlaceholderText(placeHolderTxt) else: self.lineEditFind.setToolTip(placeHolderTxt) self.findNextButton = QToolButton() self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchNextEditorConsole.png")) self.findNextButton.setIconSize(QSize(24, 24)) self.findNextButton.setAutoRaise(True) self.findPrevButton = QToolButton() self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchPrevEditorConsole.png")) self.findPrevButton.setIconSize(QSize(24, 24)) self.findPrevButton.setAutoRaise(True) self.caseSensitive = QCheckBox() caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive") self.caseSensitive.setText(caseSensTr) self.wholeWord = QCheckBox() wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word") self.wholeWord.setText(wholeWordTr) self.wrapAround = QCheckBox() self.wrapAround.setChecked(True) wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around") self.wrapAround.setText(wrapAroundTr) self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1) self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1) self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1) self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1) self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1) self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1) ##------------ Add first Tab in Editor ------------------------------- #self.tabEditorWidget.newTabEditor(tabName='first', filename=None) ##------------ Signal ------------------------------- self.findTextButton.toggled.connect(self.findTextEditor) self.objectListButton.toggled.connect(self.toggleObjectListWidget) self.commentEditorButton.triggered.connect(self.commentCode) self.uncommentEditorButton.triggered.connect(self.uncommentCode) self.runScriptEditorButton.triggered.connect(self.runScriptEditor) self.cutEditorButton.triggered.connect(self.cutEditor) self.copyEditorButton.triggered.connect(self.copyEditor) self.pasteEditorButton.triggered.connect(self.pasteEditor) self.showEditorButton.toggled.connect(self.toggleEditor) self.clearButton.triggered.connect(self.shellOut.clearConsole) self.optionsButton.triggered.connect(self.openSettings) self.loadProcessingButton.triggered.connect(self.processing) self.loadQtCoreButton.triggered.connect(self.qtCore) self.loadQtGuiButton.triggered.connect(self.qtGui) self.runButton.triggered.connect(self.shell.entered) self.openFileButton.triggered.connect(self.openScriptFile) self.saveFileButton.triggered.connect(self.saveScriptFile) self.saveAsFileButton.triggered.connect(self.saveAsScriptFile) self.helpButton.triggered.connect(self.openHelp) self.connect(self.listClassMethod, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.onClickGoToLine) self.lineEditFind.returnPressed.connect(self._findText) self.findNextButton.clicked.connect(self._findNext) self.findPrevButton.clicked.connect(self._findPrev) self.lineEditFind.textChanged.connect(self._textFindChanged) def _findText(self): self.tabEditorWidget.currentWidget().newEditor.findText(True) def _findNext(self): self.tabEditorWidget.currentWidget().newEditor.findText(True) def _findPrev(self): self.tabEditorWidget.currentWidget().newEditor.findText(False) def _textFindChanged(self): if self.lineEditFind.text(): self.findNextButton.setEnabled(True) self.findPrevButton.setEnabled(True) else: self.lineEditFind.setStyleSheet('') self.findNextButton.setEnabled(False) self.findPrevButton.setEnabled(False) def onClickGoToLine(self, item, column): tabEditor = self.tabEditorWidget.currentWidget().newEditor if item.text(1) == 'syntaxError': check = tabEditor.syntaxCheck(fromContextMenu=False) if check and not tabEditor.isReadOnly(): self.tabEditorWidget.currentWidget().save() return linenr = int(item.text(1)) itemName = str(item.text(0)) charPos = itemName.find(' ') if charPos != -1: objName = itemName[0:charPos] else: objName = itemName tabEditor.goToLine(objName, linenr) def processing(self): self.shell.commandConsole('processing') def qtCore(self): self.shell.commandConsole('qtCore') def qtGui(self): self.shell.commandConsole('qtGui') def toggleEditor(self, checked): self.splitterObj.show() if checked else self.splitterObj.hide() if not self.tabEditorWidget: self.tabEditorWidget.enableToolBarEditor(checked) self.tabEditorWidget.restoreTabsOrAddNew() def toggleObjectListWidget(self, checked): self.listClassMethod.show() if checked else self.listClassMethod.hide() def findTextEditor(self, checked): self.widgetFind.show() if checked else self.widgetFind.hide() def pasteEditor(self): self.tabEditorWidget.currentWidget().newEditor.paste() def cutEditor(self): self.tabEditorWidget.currentWidget().newEditor.cut() def copyEditor(self): self.tabEditorWidget.currentWidget().newEditor.copy() def runScriptEditor(self): self.tabEditorWidget.currentWidget().newEditor.runScriptCode() def commentCode(self): self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(True) def uncommentCode(self): self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(False) def openScriptFile(self): lastDirPath = self.settings.value("pythonConsole/lastDirPath", "") openFileTr = QCoreApplication.translate("PythonConsole", "Open File") fileList = QFileDialog.getOpenFileNames(self, openFileTr, lastDirPath, "Script file (*.py)") if fileList: for pyFile in fileList: for i in range(self.tabEditorWidget.count()): tabWidget = self.tabEditorWidget.widget(i) if tabWidget.path == pyFile: self.tabEditorWidget.setCurrentWidget(tabWidget) break else: tabName = QFileInfo(pyFile).fileName() self.tabEditorWidget.newTabEditor(tabName, pyFile) lastDirPath = QFileInfo(pyFile).path() self.settings.setValue("pythonConsole/lastDirPath", pyFile) self.updateTabListScript(pyFile, action='append') def saveScriptFile(self): tabWidget = self.tabEditorWidget.currentWidget() try: tabWidget.save() except (IOError, OSError), error: msgText = QCoreApplication.translate( 'PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}').format( tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False)
class EditorWidget(QWidget): ''' classdocs ''' def __init__(self, parent=None): ''' Constructor ''' QWidget.__init__(self, parent) self.mainLayout = QVBoxLayout() self.setLayout(self.mainLayout) # # Import Layout # self.importLayout = QHBoxLayout() self.mainLayout.addLayout(self.importLayout) self.importTypeComboBox = QComboBox() self.importTypeComboBox.addItem("RSS") self.importTypeComboBox.addItem("CSV") self.importLayout.addWidget(self.importTypeComboBox) # # RSS Layout # self.rssWidget = QWidget() self.rssLayout = QHBoxLayout() self.rssWidget.setLayout(self.rssLayout) self.rssLabel = QLabel("URL") self.rssLineEdit = QLineEdit() if hasattr(QLineEdit(), 'setPlaceholderText'): self.rssLineEdit.setPlaceholderText("http://www.example.com/rss") self.rssLabel.setBuddy(self.rssLineEdit) self.rssPushButton = QPushButton("Load talks from RSS") rss_icon = QIcon() rss_icon.addPixmap(QPixmap(":/multimedia/rss.png"), QIcon.Normal, QIcon.Off) self.rssPushButton.setIcon(rss_icon) self.rssLayout.addWidget(self.rssLabel) self.rssLayout.addWidget(self.rssLineEdit) self.rssLayout.addWidget(self.rssPushButton) self.importLayout.addWidget(self.rssWidget) # # CSV Layout # self.csvWidget = QWidget() self.csvWidget.hide() self.csvLayout = QHBoxLayout() self.csvWidget.setLayout(self.csvLayout) self.csvLabel = QLabel("File") self.csvLineEdit = QLineEdit() if sys.platform == 'win32': if hasattr(QLineEdit(), 'setPlaceholderText'): self.csvLineEdit.setPlaceholderText("C:\Example\Freeseer2011.csv") else: if hasattr(QLineEdit(), 'setPlaceholderText'): self.csvLineEdit.setPlaceholderText("/home/freeseer/Example/Freeseer2011.csv") self.csvLabel.setBuddy(self.csvLineEdit) self.csvFileSelectButton = QToolButton() self.csvFileSelectButton.setText("...") self.csvPushButton = QPushButton("Load talks from CSV") self.csvLayout.addWidget(self.csvLabel) self.csvLayout.addWidget(self.csvLineEdit) self.csvLayout.addWidget(self.csvFileSelectButton) self.csvLayout.addWidget(self.csvPushButton) self.importLayout.addWidget(self.csvWidget) # # Editor Layout # self.editorLayout = QHBoxLayout() self.mainLayout.addLayout(self.editorLayout) self.buttonsLayout = QVBoxLayout() self.editorLayout.addLayout(self.buttonsLayout) addIcon = QIcon.fromTheme("list-add") removeIcon = QIcon.fromTheme("list-remove") clearIcon = QIcon.fromTheme("edit-clear") closeIcon = QIcon.fromTheme("application-exit") self.addButton = QPushButton("Add") self.addButton.setIcon(addIcon) self.removeButton = QPushButton("Remove") self.removeButton.setIcon(removeIcon) self.clearButton = QPushButton("Clear") self.clearButton.setIcon(clearIcon) self.closeButton = QPushButton("Close") self.closeButton.setIcon(closeIcon) self.buttonsLayout.addWidget(self.addButton) self.buttonsLayout.addWidget(self.removeButton) self.buttonsLayout.addWidget(self.clearButton) self.buttonsLayout.addStretch(0) self.buttonsLayout.addWidget(self.closeButton) self.editor = QTableView() self.editor.setAlternatingRowColors(True) self.editor.setSortingEnabled(True) self.editorLayout.addWidget(self.editor) # # Widget Connections # self.connect(self.importTypeComboBox, SIGNAL('currentIndexChanged(const QString&)'), self.switch_import_plugin) def switch_import_plugin(self, plugin): self.rssWidget.hide() self.csvWidget.hide() if plugin == "RSS": self.rssWidget.show() elif plugin == "CSV": self.csvWidget.show()
class _StatusBar(QStatusBar): def __init__(self): super(_StatusBar, self).__init__() self._widgetStatus = QWidget() vbox = QVBoxLayout(self._widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) #Search Layout self._searchWidget = SearchWidget(self) vbox.addWidget(self._searchWidget) #Replace Layout self._replaceWidget = ReplaceWidget(self) vbox.addWidget(self._replaceWidget) self._replaceWidget.setVisible(False) #Code Locator self._codeLocator = locator.CodeLocatorWidget(self) vbox.addWidget(self._codeLocator) self._codeLocator.setVisible(False) #File system completer self._fileSystemOpener = FileSystemOpener() vbox.addWidget(self._fileSystemOpener) self._fileSystemOpener.setVisible(False) self.addWidget(self._widgetStatus) # Not Configurable Shortcuts shortEscStatus = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end) self.connect(self._replaceWidget._btnCloseReplace, SIGNAL("clicked()"), lambda: self._replaceWidget.setVisible(False)) self.connect(self._replaceWidget._btnReplace, SIGNAL("clicked()"), self.replace) self.connect(self._replaceWidget._btnReplaceAll, SIGNAL("clicked()"), self.replace_all) self.connect(self._replaceWidget._btnReplaceSelection, SIGNAL("clicked()"), self.replace_selected) self.connect(self._fileSystemOpener.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self._fileSystemOpener, SIGNAL("requestHide()"), self.hide_status) self.connect(shortEscStatus, SIGNAL("activated()"), self.hide_status) #Register signals connections connections = ( {'target': 'main_container', 'signal_name': 'currentEditorChanged(QString)', 'slot': self.handle_tab_changed}, {'target': 'main_container', 'signal_name': 'updateLocator(QString)', 'slot': self.explore_file_code}, {'target': 'explorer_container', 'signal_name': 'updateLocator()', 'slot': self.explore_code}, ) IDE.register_signals('status_bar', connections) IDE.register_service('status_bar', self) def install(self): self.hide() ide = IDE.get_service('ide') ide.setStatusBar(self) ui_tools.install_shortcuts(self, actions.ACTIONS_STATUS, ide) def find_next_result(self): self._searchWidget.find_next() def find_previous_result(self): self._searchWidget.find_previous() def handle_tab_changed(self, new_tab): """ Re-run search if tab changed, we use the find of search widget because we want the widget to be updated. """ editor = main_container.MainContainer().get_actual_editor() if self._searchWidget.isVisible(): self._searchWidget.find_matches(editor) if editor: self.disconnect(editor, SIGNAL("textChanged()"), self._notify_editor_changed) self.connect(editor, SIGNAL("textChanged()"), self._notify_editor_changed) def _notify_editor_changed(self): """ Lets search widget know that the editor contents changed and find needs to be re-run """ if self._searchWidget.isVisible(): editor = main_container.MainContainer().get_actual_editor() self._searchWidget.contents_changed(editor) def explore_code(self): self._codeLocator.explore_code() def explore_file_code(self, path): self._codeLocator.explore_file_code(path) def show(self): self.clearMessage() QStatusBar.show(self) editor = main_container.MainContainer().get_actual_editor() if editor and editor.textCursor().hasSelection(): text = editor.textCursor().selectedText() self._searchWidget._line.setText(text) self._searchWidget.find_matches(editor, True) if self._widgetStatus.isVisible(): self._searchWidget._line.setFocus() self._searchWidget._line.selectAll() def show_replace(self): self.clearMessage() self.show() editor = main_container.MainContainer().get_actual_editor() if editor: if editor.textCursor().hasSelection(): word = editor.textCursor().selectedText() self._searchWidget._line.setText(word) self._replaceWidget.setVisible(True) def show_with_word(self): self.clearMessage() editor = main_container.MainContainer().get_actual_editor() if editor: word = editor._text_under_cursor() self._searchWidget._line.setText(word) editor = main_container.MainContainer().get_actual_editor() editor.moveCursor(QTextCursor.WordLeft) self._searchWidget.find_matches(editor) self.show() def show_locator(self): if not self._codeLocator.isVisible(): self.clearMessage() self._searchWidget.setVisible(False) self.show() self._codeLocator.setVisible(True) self._codeLocator._completer.setFocus() self._codeLocator.show_suggestions() def show_file_opener(self): self.clearMessage() self._searchWidget.setVisible(False) self._fileSystemOpener.setVisible(True) self.show() self._fileSystemOpener.pathLine.setFocus() def hide_status(self): self._searchWidget._checkSensitive.setCheckState(Qt.Unchecked) self._searchWidget._checkWholeWord.setCheckState(Qt.Unchecked) self.hide() self._searchWidget.setVisible(True) self._replaceWidget.setVisible(False) self._codeLocator.setVisible(False) self._fileSystemOpener.setVisible(False) widget = main_container.MainContainer().get_actual_widget() if widget: widget.setFocus() def replace(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match(self._searchWidget._line.text(), self._replaceWidget._lineReplace.text(), flags) if not editor.textCursor().hasSelection(): self.find() def replace_selected(self): self.replace_all(True) def replace_all(self, selected=False): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match(self._searchWidget._line.text(), self._replaceWidget._lineReplace.text(), flags, True, selected) def find(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags) def find_next(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags, True) def find_previous(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 1 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags, True) def showMessage(self, message, timeout): if settings.SHOW_STATUS_NOTIFICATIONS: self._widgetStatus.hide() self._replaceWidget.setVisible(False) self.show() QStatusBar.showMessage(self, message, timeout) def message_end(self, message): if message == '': self.hide() QStatusBar.clearMessage(self) self._widgetStatus.show()
class Window(QMainWindow): def __init__(self,parent = None): QMainWindow.__init__(self,parent) self.setObjectName("self") self.resize(758, 673) self.setWindowTitle("Sabel") self.setWindowIcon(Icons.sabel) self.centralwidget = QWidget(self) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.horizontalLayout.setMargin(0) self.styleIndex = styleIndex #TabWidgets self.tab_1 = QWidget(self) self.tab_1.setObjectName("tab_1") self.tab_1.setMinimumWidth(800) self.tabWidget = Tab(self.tab_1) self.tabWidget.setObjectName("tabWidget") self.VericalLayout = QVBoxLayout(self.tab_1) self.VericalLayout.setMargin(0) self.VericalLayout.setObjectName("VericalLayout") self.VericalLayout.addWidget(self.tabWidget) self.tabWidget_2 = QTabWidget(self) #self.tabWidget_2.setMaximumWidth(200) self.tabWidget_2.setObjectName("tabWidget_2") self.tabWidget_3 = QTabWidget(self) self.tabWidget_3.setMaximumHeight(260) self.tabWidget_3.setObjectName("tabWidget_3") #Tree self.tab_5 = QWidget() self.tab_5.setObjectName("tab_5") #self.tab_5.setMaximumWidth(200) self.VerticalLayout_2 = QVBoxLayout(self.tab_5)#QHBoxLayout(self.tab_5) self.VerticalLayout_2.setMargin(0) self.VerticalLayout_2.setObjectName("horizontalLayout_3") self.treeWidget = Tree(self.tab_5) self.treeWidget.setObjectName("treeWidget") self.treeWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.treeWidget.horizontalScrollBar().show() self.treebar = QToolBar() action_Folder = QAction(Icons.newfolder,'New Folder', self) action_Folder.triggered.connect(self.about) action_Android = QAction(Icons.android,'Android', self) action_Android.triggered.connect(self.android) action_Ant = QAction(Icons.ant_view,'Ant', self) action_Ant.triggered.connect(self.ant) self.treebar.addAction(action_Folder) self.treebar.addAction(action_Android) self.treebar.addAction(action_Ant) self.treebar.setIconSize(QSize(16,16)) self.VerticalLayout_2.addWidget(self.treebar) self.VerticalLayout_2.addWidget(self.treeWidget) #Outline self.tab_2 = QWidget() self.tab_2.setObjectName("tab_2") #self.tab_2.setMaximumWidth(200) self.VerticalLayout_3 = QVBoxLayout(self.tab_2) self.VerticalLayout_3.setMargin(0) self.VerticalLayout_3.setObjectName("VerticalLayout_3") self.outlineWidget = Tree(self.tab_2) self.outlineWidget.setObjectName("outlineWidget") self.VerticalLayout_3.addWidget(self.outlineWidget) #Output self.tab_6 = QWidget() self.tab_6.setObjectName("tab_6") #GGGGGGGGGGGGGGGGGGGG AWESOME self.horizontalLayout_2 = QVBoxLayout(self.tab_6) self.horizontalLayout_2.setMargin(0) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.textEdit = QTextEdit(self.tab_6) self.textEdit.setObjectName("textEdit") self.lineeEdit = QLineEdit(self.tab_6) self.lineeEdit.setObjectName("lineeEdit") self.label = QLabel(self.tab_6) self.label.setText("Input:") self.horizontalLayout_2.addWidget(self.textEdit) self.horizontalLayout_2.addWidget(self.label) self.horizontalLayout_2.addWidget(self.lineeEdit) #Error self.tab_7 = QWidget() self.tab_7.setObjectName("tab_7") self.horizontalLayout_4 = QHBoxLayout(self.tab_7) self.horizontalLayout_4.setMargin(0) self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.textEdit_2 = QTextEdit(self.tab_7) self.textEdit_2.setObjectName("textEdit_2") self.horizontalLayout_4.addWidget(self.textEdit_2) #Find self.tab_8 = QWidget() self.tab_8.setObjectName("tab_8") self.horizontalLayout_5 = QHBoxLayout(self.tab_8) self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.lineEdit = QLineEdit(self.tab_8) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QLineEdit(self.tab_8) self.lineEdit_2.setObjectName("lineEdit_2") self.findClose = QPushButton(self.tab_8) self.findClose.setIcon(Icons.close_view) self.findClose.setFlat(True) self.findClose.clicked.connect(self.findBarShow) self.find = QPushButton(self.tab_8) self.find.setText("Find") self.find.clicked.connect(self.findCurrentText) self.replacefind = QPushButton(self.tab_8) self.replacefind.setText("Replace/Find") self.replace = QPushButton(self.tab_8) self.replace.setText("Replace") self.replace.clicked.connect(self.replaceCurrentText) self.replaceAll = QPushButton(self.tab_8) self.replaceAll.setText("Replace All") self.replaceAll.clicked.connect(self.replaceAllText) self.caseSensitive = QToolButton(self.tab_8) self.caseSensitive.setText("cs") self.caseSensitive.setCheckable(True) self.wholeWord = QToolButton(self.tab_8) self.wholeWord.setText("ww") self.wholeWord.setCheckable(True) self.regex = QToolButton(self.tab_8) self.regex.setText("re") self.regex.setCheckable(True) self.backward = QToolButton(self.tab_8) self.backward.setText("bk") self.backward.setCheckable(True) self.backward.setDisabled(True) self.horizontalLayout_5.addWidget(self.findClose) self.horizontalLayout_5.addWidget(self.find) self.horizontalLayout_5.addWidget(self.lineEdit) self.horizontalLayout_5.addWidget(self.lineEdit_2) self.horizontalLayout_5.addWidget(self.caseSensitive) self.horizontalLayout_5.addWidget(self.wholeWord) self.horizontalLayout_5.addWidget(self.regex) self.horizontalLayout_5.addWidget(self.backward) self.horizontalLayout_5.addWidget(self.replacefind) self.horizontalLayout_5.addWidget(self.replace) self.horizontalLayout_5.addWidget(self.replaceAll) self.horizontalLayout_5.setMargin(0) self.tab_8.setMaximumHeight(25) self.VericalLayout.addWidget(self.tab_8) self.tab_8.hide() self.tabWidget_2.addTab(self.tab_5,"Projects") self.tabWidget_2.addTab(self.tab_2,"Outline") self.tabWidget_3.addTab(self.tab_7,"Error") self.tabWidget_3.addTab(self.tab_6,"Output") self.tabWidget_3.setTabIcon(0,Icons.error) self.tabWidget_3.setTabIcon(1,Icons.console_view) self.tabWidget.setTabsClosable(True) self.tabWidget.setTabShape(0) #Splitters self.split1 = QSplitter(Qt.Horizontal) self.split1.addWidget(self.tabWidget_2) self.split1.addWidget(self.tab_1) #self.split1.addWidget(self.tab_5) self.split2 = QSplitter(Qt.Vertical) self.split2.addWidget(self.split1) self.split2.addWidget(self.tabWidget_3) self.tabWidget_3.hide() self.horizontalLayout.addWidget(self.split2) #Status self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.aboutButton = QPushButton(self) self.aboutButton.setFlat(True) self.aboutButton.setIcon(Icons.anchor) self.aboutButton.clicked.connect(self.about) self.cmdButton = QPushButton(self) self.cmdButton.setFlat(True) self.cmdButton.setIcon(Icons.console_view) self.cmdButton.clicked.connect(self.cmd) self.cmdButton.setShortcut('Ctrl+O') self.findButton = QPushButton(self) self.findButton.setFlat(True) self.findButton.setIcon(Icons.find) self.findButton.setShortcut("Ctrl+F") self.findButton.clicked.connect(self.findBarShow) self.zoominButton = QPushButton(self) self.zoominButton.setFlat(True) self.zoominButton.setIcon(Icons.zoomplus) self.zoominButton.clicked.connect(self.zoomin) self.zoomoutButton = QPushButton(self) self.zoomoutButton.setFlat(True) self.zoomoutButton.setIcon(Icons.zoomminus) self.zoomoutButton.clicked.connect(self.zoomout) self.fontButton = QPushButton(self) self.fontButton.setFlat(True) self.fontButton.setIcon(Icons.font) self.fontButton.clicked.connect(self.setFont) self.statusbar.addWidget(self.aboutButton) self.statusbar.addWidget(self.cmdButton) self.statusbar.addWidget(self.findButton) self.statusbar.addWidget(self.zoominButton) self.statusbar.addWidget(self.zoomoutButton) self.statusbar.addWidget(self.fontButton) #self.statusbar.setFixedHeight(18) #Init colorstyling self.colorStyle = None self.initColorStyle() #Init self.setCentralWidget(self.centralwidget) self.setStatusBar(self.statusbar) self.textEdit.setReadOnly(True) self.fontName = fontName #QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks')) def findBarShow(self): if(self.tab_8.isHidden()): self.tab_8.show() else: self.tab_8.hide() def initToolBar(self): self.action_NewProject = QAction(Icons.newprj, 'Project', self) self.action_NewProject.setShortcut('Ctrl+P') self.action_NewProject.triggered.connect(self.newProject) self.action_NewProject.setToolTip("Create a New Project") self.action_NewProject.setStatusTip("Create a New Project") self.action_Open = QAction(Icons.open, 'Open', self) self.action_Open.setShortcut('Ctrl+O') self.action_Open.triggered.connect(self.fileOpen) self.action_Open.setToolTip("Open File") self.action_Open.setStatusTip("Open File") self.action_Save = QAction(Icons.save, 'Save', self) self.action_Save.setShortcut('Ctrl+S') self.action_Save.triggered.connect(self.fileSave) self.action_Save.setToolTip("Save Current File") self.action_SaveAll = QAction(Icons.saveall, 'SaveAll', self) self.action_SaveAll.setShortcut('Ctrl+A') self.action_SaveAll.triggered.connect(self.fileSaveAll) self.action_SaveAll.setToolTip("Save All Files") self.action_Help = QAction(Icons.toc_open, 'Help', self) self.action_Help.triggered.connect(self.help) self.action_Run = QAction(Icons.run, 'Run', self) self.action_Run.setShortcut('Ctrl+R') self.action_Run.triggered.connect(self.adb.run) self.action_RunFile = QAction(Icons.go, 'File', self) self.action_RunFile.triggered.connect(self.command.setCmd) self.lineeEdit.returnPressed.connect(self.command.setCmdLine) self.action_Stop = QAction(Icons.stop, 'Stop', self) self.action_Stop.setShortcut('Ctrl+Q') self.action_Stop.triggered.connect(self.adb.stop) self.action_Design = QAction(Icons.task_set, 'Design', self) self.action_Todo = QAction(Icons.task_set, 'Todo', self) #self.action_Todo.triggered.connect(self.stop) #Only variation CHeck Later men = QMenu() self.threshSlider = QSlider() self.threshSlider.setTickPosition(QSlider.TicksLeft) self.threshSlider.setOrientation(Qt.Horizontal) self.threshSlider.setValue(threshold) self.threshSlider.setMinimum(0) self.threshSlider.setMaximum(5) self.threshSlider.valueChanged.connect(self.setThreshold) #self.threshSlider.setInvertedAppearance(True) self.threshSliderAction = QWidgetAction(men) self.threshSliderAction.setDefaultWidget(self.threshSlider) men.addAction(QAction("Ident",self)) men.addAction(QAction("Edit",self)) men.addAction(QAction("Paste",self)) men.addAction(QAction("Tabs",self)) men.addSeparator() men.addAction(QAction("Threshold",self)) men.addAction(self.threshSliderAction) self.action_Options = QAction(Icons.thread_view, 'Options', self) self.action_Options.setMenu(men) self.action_Options.triggered.connect(self.options) self.action_Full = QAction(Icons.fullscreen, 'Full', self) self.action_Full.setShortcut('Shift+Enter') self.action_Full.triggered.connect(self.full) self.action_Style = QAction(Icons.style, 'Style', self) men1 = QMenu() self.styleslist = [] self.style1 = QAction("All Hallow's Eve",self) self.style1.triggered.connect(lambda:self.style_clicked(1)) self.style1.setCheckable(True) self.style2 = QAction("Amy",self) self.style2.triggered.connect(lambda:self.style_clicked(2)) self.style2.setCheckable(True) self.style3 = QAction("Aptana Studio",self) self.style3.triggered.connect(lambda:self.style_clicked(3)) self.style3.setCheckable(True) self.style4 = QAction("Bespin",self) self.style4.triggered.connect(lambda:self.style_clicked(4)) self.style4.setCheckable(True) self.style5 = QAction("Blackboard",self) self.style5.triggered.connect(lambda:self.style_clicked(5)) self.style5.setCheckable(True) self.style6 = QAction("Choco",self) self.style6.triggered.connect(lambda:self.style_clicked(6)) self.style6.setCheckable(True) self.style7 = QAction("Cobalt",self) self.style7.triggered.connect(lambda:self.style_clicked(7)) self.style7.setCheckable(True) self.style8 = QAction("Dawn",self) self.style8.triggered.connect(lambda:self.style_clicked(8)) self.style8.setCheckable(True) self.style9 = QAction("Eclipse",self) self.style9.triggered.connect(lambda:self.style_clicked(9)) self.style9.setCheckable(True) self.styleslist.append(self.style1) self.styleslist.append(self.style2) self.styleslist.append(self.style3) self.styleslist.append(self.style4) self.styleslist.append(self.style5) self.styleslist.append(self.style6) self.styleslist.append(self.style7) self.styleslist.append(self.style8) self.styleslist.append(self.style9) men1.addActions(self.styleslist) self.action_Style.setMenu(men1) self.styleslist[self.styleIndex].setChecked(True) self.action_Stop.setDisabled(True) self.toolbar = self.addToolBar('ToolBar') self.toolbar.setIconSize(QSize(16,16)) self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.toolbar.setAllowedAreas(Qt.AllToolBarAreas) #self.toolbar.setFixedHeight(40) self.toolbar.addAction(self.action_NewProject) self.toolbar.addAction(self.action_Open) self.toolbar.addAction(self.action_Save) self.toolbar.addAction(self.action_SaveAll) self.toolbar.addSeparator() self.toolbar.addAction(self.action_Run) self.toolbar.addAction(self.action_RunFile) self.toolbar.addAction(self.action_Stop) self.toolbar.addSeparator() self.toolbar.addAction(self.action_Design) self.toolbar.addAction(self.action_Todo) self.toolbar.addAction(self.action_Options) self.toolbar.addAction(self.action_Style) self.toolbar.addSeparator() self.toolbar.addAction(self.action_Help) self.toolbar.addAction(self.action_Full) def about(self): QMessageBox.about(self, "About Sabel IDE", """ <b>Sabel</b> v%s <p> All rights reserved in accordance with GPL v3 or later. <p>This application can be used for Squirrel and EmoFramework Projects. <p>Squirrel Shell Copyright (c) 2006-2011, Constantin Makshin <p>Squirrel Copyright (c) Alberto Demichelis <p>zlib Copyright (c) Jean-loup Gailly and Mark Adler <p>Icons Copyright (c) Eclipse EPL <p>Emo-Framework Copyright (c) 2011 Kota Iguchi <p>Python %s - Qt %s - PyQt %s on %s <p>Created By: pyros2097 <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ % ( __version__,PY_VERSION, QT_VERSION_STR, PYQT_VERSION_STR,OS_NAME)) def help(self): QMessageBox.about(self, "About Simple Editor","This is The Help") def full(self): if not self.isFull: self.setWindowState(Qt.WindowFullScreen) self.isFull = True else: self.setWindowState(Qt.WindowMaximized) self.isFull = False def android(self): form = DialogAndroid(self) form.show() def ant(self): pass def cmd(self): if(self.tabWidget_3.isHidden()): self.tabWidget_3.show() else: self.tabWidget_3.hide() def findCurrentText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked()) def replaceCurrentText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) done = edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked()) if(done): edt.replaceText(self.lineEdit_2.text()) else: QMessageBox.about(self, "About Sabel IDE","Could Not Find Text") return done def replaceAllText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) while(edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked())): edt.replaceText(self.lineEdit_2.text()) def zoomin(self): for i in range(len(self.files)): self.tabWidget.widget(i).zoomin() def zoomout(self): for i in range(len(self.files)): self.tabWidget.widget(i).zoomout() def setFont(self): font = QFont() font.setFamily(self.fontName) fdialog = QFontDialog(self) fdialog.show() fdialog.setCurrentFont(font) fdialog.accepted.connect(lambda:self.setFontName(fdialog.currentFont())) def setFontName(self,font): #print "accepted" #print font.family() self.fontName = str(font.family()) config.setFontName(self.fontName) for i in range(len(self.files)): self.tabWidget.widget(i).setFontName(self.fontName) def setThreshold(self,val): config.setThresh(val) for i in range(len(self.files)): self.tabWidget.widget(i).setThreshold(val) def initColorStyle(self): self.colorStyle = Styles[self.styleIndex] pal = QPalette(self.tabWidget_2.palette()) #print pal.color(QPalette.Base).name() #print pal.color(QPalette.Window).name() pal.setColor(QPalette.Base,self.colorStyle.paper) pal.setColor(QPalette.Text,self.colorStyle.color) self.tabWidget_2.setPalette(pal) self.tabWidget_3.setPalette(pal) def style_clicked(self,no): self.styleIndex = no -1 #print self.styleIndex for i in self.styleslist: if self.styleslist.index(i) == self.styleIndex: i.setChecked(True) else: i.setChecked(False) config.setstyleIndex(self.styleIndex) #self.initColorStyle() for i in range(len(self.files)): pass #self.tabWidget. #self.tabWidget.widget(i).setColorStyle(self.colorStyle)
class MusicPreviewWidget(QWidget): def __init__(self, parent=None): super(MusicPreviewWidget, self).__init__(parent) self._lastbuildtime = 10.0 self._running = None self._current = None self._chooserLabel = QLabel() self._chooser = QComboBox(self, activated=self.selectDocument) self._log = log.Log() self._view = popplerview.View() self._progress = widgets.progressbar.TimedProgressBar() self._stack = QStackedLayout() self._top = QWidget() layout = QVBoxLayout() self.setLayout(layout) layout.addWidget(self._top) layout.addLayout(self._stack) layout.addWidget(self._progress) top = QHBoxLayout() top.setContentsMargins(0, 0, 0, 0) top.setSpacing(2) self._top.setLayout(top) top.addWidget(self._chooserLabel) top.addWidget(self._chooser) top.addStretch(1) self._stack.addWidget(self._log) self._stack.addWidget(self._view) self._top.hide() app.aboutToQuit.connect(self.cleanup) app.translateUI(self) def translateUI(self): self._chooserLabel.setText(_("Document:")) def preview(self, text, title=None): """Runs LilyPond on the given text and shows the resulting PDF.""" j = self._running = MusicPreviewJob(text, title) j.done.connect(self._done) self._log.clear() self._log.connectJob(j) j.start() self._progress.start(self._lastbuildtime) def _done(self, success): self._progress.stop(False) pdfs = self._running.resultfiles() self.setDocuments(pdfs) if not pdfs: self._stack.setCurrentWidget(self._log) return self._lastbuildtime = self._running.elapsed_time() self._stack.setCurrentWidget(self._view) if self._current: self._current.cleanup() self._current = self._running # keep the tempdir self._running = None def setDocuments(self, pdfs): """Loads the given PDF path names in the UI.""" self._documents = [popplertools.Document(name) for name in pdfs] self._chooser.clear() self._chooser.addItems([d.name() for d in self._documents]) self._top.setVisible(len(self._documents) > 1) if pdfs: self._chooser.setCurrentIndex(0) self.selectDocument(0) else: self._view.clear() def selectDocument(self, index): doc = self._documents[index].document() if doc: self._view.load(doc) def cleanup(self): if self._running: self._running.abort() self._running.cleanup() self._running = None if self._current: self._current.cleanup() self._current = None self._stack.setCurrentWidget(self._log) self._top.hide() self._view.clear() def print_(self): """Prints the currently displayed document.""" if self._documents: doc = self._documents[self._chooser.currentIndex()] import popplerprint popplerprint.printDocument(doc, self)
class PreviewWindow(QFrame): minsize = (32, 32) maxsize = None last_save_dir = "" raise_window = False key_signal = pyqtSignal(int, int, int) move_signal = pyqtSignal() def __init__(self, manager, name, image=None, message=None, position=None, size=None, high_quality=False): super(PreviewWindow, self).__init__() self.setObjectName("Preview window {}".format(name)) self.setWindowTitle(name) self.manager = manager desktop = QApplication.instance().desktop() if self.maxsize: self.maxsize = QSize(*self.maxsize) else: self.maxsize = desktop.screenGeometry(desktop.screenNumber(self)).size() * 0.95 self.setMinimumSize(*self.minsize) self.setMaximumSize(self.maxsize) self.image = None self.original = None self.message = message self.scale = 1. self.rotation = 0 self.quality = Qt.SmoothTransformation if high_quality else Qt.FastTransformation self.fixed_size = size self.scrollarea = PreviewScrollArea() self.scrollarea.setFrameStyle(0) self.scrollarea.setFocusPolicy(Qt.NoFocus) layout = QGridLayout() layout.setMargin(0) layout.setContentsMargins(0,0,0,0) self.setLayout(layout) layout.addWidget(self.scrollarea, 0, 0) self.preview = QLabel() self.preview.setMouseTracking(False) self.preview.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.scrollarea.setWidget(self.preview) self.message_label = QLabel(" ") self.layout().addWidget(self.message_label, 0, 0, Qt.AlignTop) self.message_label.setStyleSheet("QLabel {color:black;background:rgba(255,255,255,32)}") self.message_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.message_label.setText("") shadow = QGraphicsDropShadowEffect() shadow.setBlurRadius(4) shadow.setColor(Qt.white) shadow.setOffset(0,0) self.message_label.setGraphicsEffect(shadow) self.blink_widget = QWidget() self.blink_widget.hide() self.blink_widget.setStyleSheet("border:3px solid red") self.blink_timer = QTimer() self.blink_timer.setInterval(1000) self.blink_timer.timeout.connect(self.blink_) layout.addWidget(self.blink_widget, 0, 0) self.setImage(image, show=False) if image is not None and not size: size = self.autoSize() if size: self.resize(*size) if position == 'cursor': position = (QCursor.pos().x() - self.size().width()//2, QCursor.pos().y() - self.size().height()//2) if position: self.move(*position) self.showNormal() def setImage(self, image, show=True, scale=None, blink=False): if image is None: return self.original = image if isinstance(image, QImage): image = QPixmap.fromImage(image) elif isinstance(image, QPixmap): pass else: image = array_to_pixmap(image) self.image = image if not scale: scale = self.scale if image.width()*scale > self.maxsize.width(): scale = self.maxsize.width() / image.width() if image.height()*scale > self.maxsize.height(): scale = self.maxsize.height() / image.height() self.setZoom(scale) if self.message is not None: self.message_label.setText(self.message) if blink: self.blink(True) if show: self.setShown(True) if self.raise_window: self.raise_() def closeEvent(self, event): self.scale = 1.0 self.fixed_size = None def setImageAndParams(self, image, show=True, scale=None, position=None, size=None, hq=None, message=None, blink=False): if size: self.fixed_size = size if position: self.move(*position) if hq is not None: if hq: self.quality = Qt.SmoothTransformation else: self.quality = Qt.FastTransformation if message is not None: self.message = message self.setImage(image, show=show, scale=scale, blink=blink) def setZoom(self, scale): self.setParams(scale=scale) def setRotation(self, rotation): self.setParams(rotation=rotation) def setParams(self, scale=None, rotation=None): assert isinstance(self.image, QPixmap) if scale is None: scale = self.scale if rotation is None: rotation = self.rotation if scale != 1.0 or rotation: transform = QTransform().rotate(rotation).scale(scale,scale) pixmap = self.image.transformed(transform, self.quality) else: pixmap = self.image w = pixmap.width() h = pixmap.height() self.scale = scale self.rotation = rotation self.preview.setPixmap(pixmap) self.preview.setFixedSize(pixmap.size()) if not self.fixed_size: self.resize(w, h) def autoSize(self): size = self.image.size() w = size.width() h = size.height() return w, h def wheelEvent(self, event): assert isinstance(event, QWheelEvent) event.accept() if event.delta() > 0: s = 1.1 else: s = 1 / 1.1 self.setZoom(s * self.scale) scrollX = self.scrollarea.horizontalScrollBar().value() posX = event.x() newX = s * (scrollX + posX) - posX self.scrollarea.horizontalScrollBar().setValue(int(newX)) scrollY = self.scrollarea.verticalScrollBar().value() posY = event.y() newY = s * (scrollY + posY) - posY self.scrollarea.verticalScrollBar().setValue(int(newY)) self.blink(False) def mousePressEvent(self, event): assert isinstance(event, QMouseEvent) self.key_signal.emit(KEY_MOUSE, event.x(), event.y()) self.blink(False) event.accept() def keyPressEvent(self, event): assert isinstance(event, QKeyEvent) self.key_signal.emit(int(event.key()), 0, 0) self.blink(False) if event.key() == Qt.Key_Escape: self.close() event.accept() def moveEvent(self, event): self.move_signal.emit() def contextMenuEvent(self, event): assert isinstance(event, QContextMenuEvent) self.blink(False) menu = QMenu() copy = menu.addAction("Copy to clipboard") reset = menu.addAction("Reset view") hq = menu.addAction("High quality") hq.setCheckable(True) if self.quality == Qt.SmoothTransformation: hq.setChecked(True) fixed = menu.addAction("Fixed size") fixed.setCheckable(True) if self.fixed_size: fixed.setChecked(True) rotate_right = menu.addAction("Rotate +") rotate_left = menu.addAction("Rotate -") save = menu.addAction("Save...") quit = menu.addAction("Close") action = menu.exec_(self.mapToGlobal(event.pos())) if action == quit: self.close() elif action == reset: self.setParams(1,0) elif action == hq: if self.quality == Qt.SmoothTransformation: self.quality = Qt.FastTransformation else: self.quality = Qt.SmoothTransformation self.setZoom(self.scale) elif action == rotate_right: rotation = (self.rotation + 90) % 360 self.setRotation(rotation) elif action == rotate_left: rotation = (self.rotation + 270) % 360 self.setRotation(rotation) elif action == save: filename, filter = QFileDialog.getSaveFileNameAndFilter(self, "Save image...", filter="*.png;;*.jpg;;*.bmp;;*.tiff;;*.gif", directory=self.last_save_dir) if filename: try: if not str(filename).endswith(filter[1:]): filename = filename + filter[1:] PreviewWindow.last_save_dir = path.dirname(str(filename)) success = self.image.save(filename, quality=100) if not success: raise Exception("unknown error") except Exception as e: QMessageBox.critical(self, "Saving error", "Cannot save.\nError: {}".format(e.message)) print("Saving error:", e) elif action == fixed: if self.fixed_size: self.fixed_size = None else: self.fixed_size = self.size() elif action == copy: print("copy") clipboard = QApplication.instance().clipboard() clipboard.setPixmap(self.image) def blink(self, enable): if enable: self.blink_timer.start() else: self.blink_timer.stop() self.blink_widget.hide() @pyqtSlot() def blink_(self): if self.blink_widget.isHidden(): self.blink_widget.show() else: self.blink_widget.hide()
class __StatusBar(QStatusBar): def __init__(self, parent=None): QStatusBar.__init__(self, parent) self._widgetStatus = QWidget() vbox = QVBoxLayout(self._widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) #Search Layout self._searchWidget = SearchWidget(self) vbox.addWidget(self._searchWidget) #Replace Layout self._replaceWidget = ReplaceWidget(self) vbox.addWidget(self._replaceWidget) self._replaceWidget.setVisible(False) #Code Locator self._codeLocator = locator.CodeLocatorWidget(self) vbox.addWidget(self._codeLocator) self._codeLocator.setVisible(False) #File system completer self._fileSystemOpener = FileSystemOpener() vbox.addWidget(self._fileSystemOpener) self._fileSystemOpener.setVisible(False) self.addWidget(self._widgetStatus) self._shortEsc = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end) self.connect(self._replaceWidget._btnCloseReplace, SIGNAL("clicked()"), lambda: self._replaceWidget.setVisible(False)) self.connect(self._replaceWidget._btnReplace, SIGNAL("clicked()"), self.replace) self.connect(self._replaceWidget._btnReplaceAll, SIGNAL("clicked()"), self.replace_all) self.connect(self._replaceWidget._btnReplaceSelection, SIGNAL("clicked()"), self.replace_selected) self.connect(self._shortEsc, SIGNAL("activated()"), self.hide_status) self.connect(self._fileSystemOpener.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self._fileSystemOpener, SIGNAL("requestHide()"), self.hide_status) def handle_tab_changed(self, new_tab): """ Re-run search if tab changed, we use the find of search widget because we want the widget to be updated. """ if self._searchWidget.isVisible(): editor = main_container.MainContainer().get_actual_editor() self._searchWidget.find_matches(editor) def explore_code(self): self._codeLocator.explore_code() def explore_file_code(self, path): self._codeLocator.explore_file_code(path) def show(self): self.clearMessage() QStatusBar.show(self) if self._widgetStatus.isVisible(): self._searchWidget._line.setFocus() self._searchWidget._line.selectAll() def show_replace(self): self.clearMessage() self.show() editor = main_container.MainContainer().get_actual_editor() if editor: if editor.textCursor().hasSelection(): word = editor.textCursor().selectedText() self._searchWidget._line.setText(word) self._replaceWidget.setVisible(True) def show_with_word(self): self.clearMessage() editor = main_container.MainContainer().get_actual_editor() if editor: word = editor._text_under_cursor() self._searchWidget._line.setText(word) editor = main_container.MainContainer().get_actual_editor() editor.moveCursor(QTextCursor.WordLeft) self._searchWidget.find_matches(editor) self.show() def show_locator(self): if not self._codeLocator.isVisible(): self.clearMessage() self._searchWidget.setVisible(False) self.show() self._codeLocator.setVisible(True) self._codeLocator._completer.setFocus() self._codeLocator.show_suggestions() def show_file_opener(self): self.clearMessage() self._searchWidget.setVisible(False) self._fileSystemOpener.setVisible(True) self.show() self._fileSystemOpener.pathLine.setFocus() def hide_status(self): self._searchWidget._checkSensitive.setCheckState(Qt.Unchecked) self._searchWidget._checkWholeWord.setCheckState(Qt.Unchecked) self.hide() self._searchWidget.setVisible(True) self._replaceWidget.setVisible(False) self._codeLocator.setVisible(False) self._fileSystemOpener.setVisible(False) widget = main_container.MainContainer().get_actual_widget() if widget: widget.setFocus() def replace(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match( unicode(self._searchWidget._line.text()), unicode(self._replaceWidget._lineReplace.text()), flags) if not editor.textCursor().hasSelection(): self.find() def replace_selected(self): self.replace_all(True) def replace_all(self, selected=False): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match( unicode(self._searchWidget._line.text()), unicode(self._replaceWidget._lineReplace.text()), flags, True, selected) def find(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(unicode(self._searchWidget._line.text()), flags) def find_next(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(unicode(self._searchWidget._line.text()), flags, True) def find_previous(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 1 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(unicode(self._searchWidget._line.text()), flags, True) def showMessage(self, message, timeout): self._widgetStatus.hide() self._replaceWidget.setVisible(False) self.show() QStatusBar.showMessage(self, message, timeout) def message_end(self, message): if message == '': self.hide() QStatusBar.clearMessage(self) self._widgetStatus.show() widget = main_container.MainContainer().get_actual_widget() if widget: widget.setFocus()
class NavigatorDock(DockWidget): def __init__(self): DockWidget.__init__(self, core.mainWindow(), '&Navigator', QIcon(':/enkiicons/goto.png'), "Alt+N") self._tags = [] self._tree = QTreeView(self) self._tree.installEventFilter(self) self._tree.setHeaderHidden(True) self.setFocusProxy(self._tree) self._filterEdit = LineEdit(self) self._filterEdit.setClearButtonVisible(True) self._filterEdit.textEdited.connect(self._applyFilter) self._filterEdit.clearButtonClicked.connect(self._applyFilter) self._filterEdit.clearButtonClicked.connect(self._tree.setFocus) self._filterEdit.clearButtonClicked.connect(self._hideFilter) self._filterEdit.installEventFilter(self) self._displayWidget = QWidget(self) layout = QVBoxLayout(self._displayWidget) layout.addWidget(self._tree) layout.addWidget(self._filterEdit) layout.setContentsMargins(0, 0, 0, 0) self.setWidget(self._displayWidget) self._tagModel = _TagModel(self._tree) self._tagModel.jumpToTagDone.connect(self._hideFilter) self._tree.setModel(self._tagModel) self._tree.activated.connect(self._tagModel.onActivated) self._tree.clicked.connect(self._tagModel.onActivated) self._tagModel.modelAboutToBeReset.connect(self._onModelAboutToBeReset) self._tagModel.modelReset.connect(self._onModelReset) self._currentTagPath = None self._errorLabel = None self._installed = False def install(self): if not self._installed: core.mainWindow().addDockWidget(Qt.RightDockWidgetArea, self) core.actionManager().addAction("mView/aNavigator", self.showAction()) self._installed = True def remove(self): if self._installed: core.mainWindow().removeDockWidget(self) core.actionManager().removeAction("mView/aNavigator") self.hide() self._installed = False def setTags(self, tags): self._tags = tags self._setFilteredTags(tags) self._hideFilter() if self.widget() is not self._displayWidget: self.setWidget(self._displayWidget) self._displayWidget.show() if self._errorLabel is not None: self._errorLabel.hide() def _setFilteredTags(self, tags): self._tagModel.setTags(tags) def onError(self, error): self._displayWidget.hide() if self._errorLabel is None: self._errorLabel = QLabel(self) self._errorLabel.setWordWrap(True) self._errorLabel.setText(error) if not self.widget() is self._errorLabel: self.setWidget(self._errorLabel) self._errorLabel.show() self._displayWidget.hide() def _onModelAboutToBeReset(self): currIndex = self._tree.currentIndex() self._currentTagPath = self._tagModel.tagPathForIndex( currIndex) if currIndex.isValid() else None def _onModelReset(self): self._tree.expandAll() # restore current item if self._currentTagPath is not None: index = self._tagModel.indexForTagPath(self._currentTagPath) if index.isValid(): self._tree.setCurrentIndex(index) def eventFilter(self, object_, event): if object_ is self._tree: if event.type() == QEvent.KeyPress: if event.key() == Qt.Key_Backspace: if event.modifiers() == Qt.ControlModifier: self._onTreeCtrlBackspace() else: self._onTreeBackspace() return True elif event.text() and \ (event.text().isalnum() or event.text() == '_'): self._onTreeTextTyped(event.text()) return True elif object_ is self._filterEdit: if event.type() == QEvent.KeyPress: if event.key() in (Qt.Key_Up, Qt.Key_Down): self._tree.setFocus() self._tree.event(event) return True elif event.key() in (Qt.Key_Enter, Qt.Key_Return): currIndex = self._tree.currentIndex() if currIndex.isValid(): self._tagModel.onActivated(currIndex) return DockWidget.eventFilter(self, object_, event) def _hideFilter(self): hadText = self._filterEdit.text() != '' self._filterEdit.clear() self._filterEdit.hide() if hadText: self._applyFilter() def _applyFilter(self): text = self._filterEdit.text() if text: if not text.startswith('*'): text = '*' + text if not text.endswith('*'): text = text + '*' wildcard = text.lower() filteredTags = _filterTags(wildcard, self._tags) self._setFilteredTags(filteredTags) self._tree.expandAll() if filteredTags: firstMatchingTag = _findFirstMatching(wildcard, filteredTags) path = _tagPath(firstMatchingTag) index = self._tagModel.indexForTagPath(path) self._tree.setCurrentIndex(index) else: self._setFilteredTags(self._tags) if text: self._filterEdit.show() elif not self._filterEdit.hasFocus(): self._hideFilter() def _onTreeTextTyped(self, text): self._filterEdit.setText(self._filterEdit.text() + text) self._applyFilter() def _onTreeBackspace(self): text = self._filterEdit.text() if text: self._filterEdit.setText(text[:-1]) self._applyFilter() def _onTreeCtrlBackspace(self): self._hideFilter() self._applyFilter()
def hide(self): if self.__allowHide: QWidget.hide(self)
class MainGUI(QObject): """ Class MainGUI uses PyQt elements to build up the main gui with all the gui elements of trees, editors, menu and so on. @author: ssimons """ MAIN_TREE = True SECOND_TREE = False signal_treeview1_expand_all = pyqtSignal() signal_treeview2_expand_all = pyqtSignal() signal_treeview1_collapse_all = pyqtSignal() signal_treeview2_collapse_all = pyqtSignal() signal_treeview1_clicked = pyqtSignal() signal_treeview2_clicked = pyqtSignal() signal_editor_of_tree1_clear = pyqtSignal() signal_editor_of_tree2_clear = pyqtSignal() def __init__(self): """ Initializes the gui elements """ super(MainGUI, self).__init__() app = QApplication(sys.argv) self.window = QWidget() self._conf = self._config_read_config_from_file_or_new() self.text_output_1 = QTextEdit() self.text_output_1_string = QString() self.text_output_2 = QTextEdit() self.text_output_2_string = QString() self.widget_right_window = QWidget() self.main_window = QMainWindow() self.tree_main = Tree(self._conf) self.tree_model_main = TreeModel(self.tree_main) self.tree_second = Tree(self._conf) self.tree_model_second = TreeModel(self.tree_second) self._init_gui() self.gui_menu = GuiMenu(self. tree_main, self.tree_second, self._conf, self.widget_right_window, self.main_window, SignalWrapper(self.signal_treeview1_expand_all, self.signal_treeview2_expand_all, self.signal_treeview1_collapse_all, self.signal_treeview2_collapse_all, self.signal_treeview1_clicked, self.signal_treeview2_clicked, self.signal_editor_of_tree1_clear, self.signal_editor_of_tree2_clear)) self.main_window.setMenuBar(self.gui_menu) gui_helper.open_last_opened_file_when_configured(self._conf, self.main_window, self.tree_main) self.main_window.show() app.exec_() def _init_gui(self): """ Initializes some widgets and delegates tree initializing to another function """ self.text_output_1.setWindowTitle("Output Tree1") self.text_output_1.setReadOnly(True) self.text_output_2.setWindowTitle("Output Tree2") self.text_output_2.setReadOnly(True) self.signal_editor_of_tree1_clear.connect(self.text_output_1.clear) self.signal_editor_of_tree2_clear.connect(self.text_output_2.clear) self.main_window.setCentralWidget(self.window) self.main_window.resize(500, 300) widget_left_window = QWidget() widget_left_window.setLayout( self._initialize_create_tree(self.MAIN_TREE, self.tree_model_main, self.text_output_1)) self.widget_right_window.setLayout( self._initialize_create_tree(self.SECOND_TREE, self.tree_model_second, self.text_output_2)) self.widget_right_window.hide() widget_two_windows = QSplitter() layout_two_windows = QHBoxLayout() layout_two_windows.addWidget(widget_left_window) layout_two_windows.addWidget(self.widget_right_window) widget_two_windows.setLayout(layout_two_windows) self.window.setLayout(layout_two_windows) def _initialize_create_tree(self, is_main_tree, tree_model_instance, text_output_instance): """ Creates gui elements for the tree-gui given as parameter. Also binds the given text output to this tree. Will be used for both tree widgets. @param is_main_tree: to differ between main and second tree. @param tree_model_instance: TreeModel object that should be used. @param text_output_instance: QTextEdit object which should be used / bind with the tree wiget. """ widget_tree_and_editor = QSplitter() layout_tree_and_editor = QHBoxLayout() tree_view = QTreeView() tree_view.setModel(tree_model_instance) tree_view.clicked[QModelIndex].connect( lambda: self.tree_element_clicked_event(is_main_tree)) if is_main_tree == self.SECOND_TREE: self.signal_treeview2_expand_all.connect(tree_view.expandAll) self.signal_treeview2_collapse_all.connect(tree_view.collapseAll) self.signal_treeview2_clicked.connect( lambda: tree_view.clicked.emit(QModelIndex())) else: self.signal_treeview1_expand_all.connect(tree_view.expandAll) self.signal_treeview1_collapse_all.connect(tree_view.collapseAll) self.signal_treeview1_clicked.connect( lambda: tree_view.clicked.emit(QModelIndex())) layout_tree_and_editor.addWidget(tree_view) layout_tree_and_editor.addWidget(text_output_instance) widget_tree_and_editor.setLayout(layout_tree_and_editor) layout_window = QVBoxLayout() layout_window.addWidget(widget_tree_and_editor) return layout_window def tree_element_clicked_event(self, is_main_tree): """ Action to display information of all selected tree elements in the text area. Selected means that the checkboxes of the tree element is checked. @param is_main_tree: to differ between main and second tree. """ if is_main_tree == self.SECOND_TREE: tree_operations.show_data_text_of_checked_tree_elements( self.tree_second.get_root_elements(), self._conf, self.text_output_2, self.text_output_2_string) else: tree_operations.show_data_text_of_checked_tree_elements( self.tree_main.get_root_elements(), self._conf, self.text_output_1, self.text_output_1_string) def _config_read_config_from_file_or_new(self): """Opens configuration from file - or if isn't possible return a new one""" config_filename = Configuration.CONFIG_FILENAME if not os.path.isfile(config_filename): logging.debug("configuration file %s doesn't exist.", config_filename) QMessageBox.information(self.window, "Info", '''No configuration file (''' + config_filename + ''') found. The default configuration is used. Change it in the configuration window (see menu View - Help). Afterwards a text file should be opened (menu MainFile - Open file).''') return Configuration() try: #try to open saved configuration and use it conf = Configuration() conf.data = ConfigurationFileReader.read_config() return conf except IOError, exc: logging.info("Couldn't open configuration file. " + config_filename + "Use the default values.") logging.exception(exc) return Configuration()
class TwitterGui(QWidget): URL_REGEX = re.compile(r'''((?:mailto:|ftp://|http://|https://)[^ <>'"{}|\\^`[\]]*)''') def __init__(self, parent, logger, db_conn, update_func, safe_conn): super(TwitterGui, self).__init__(parent) self._db_conn = db_conn self.logger = logger self._reply_to_id = 0 self._update_func = update_func self._list = None if get_settings().get_proxy(): u = urlparse.urlsplit(get_settings().get_proxy()) proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(u.hostname); proxy.setPort(u.port) QNetworkProxy.setApplicationProxy(proxy); self.msgview = QWebView(self) self.msgview.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) self.msgview.linkClicked.connect(self.link_clicked) self.userCombo = QComboBox(self) self.userCombo.setEditable(True) self.userCombo.activated.connect(self.toggle_user_in_list) self.showButton = QPushButton(chr(94), self) self.showButton.setMaximumHeight(13) self.showButton.clicked.connect(self.show_hide_animation) self.post_field = QTextEdit(self) self.post_field.setMaximumHeight(50) self.post_field.textChanged.connect(self.text_changed) self.send_button = QPushButton("Post", self) self.send_button.clicked.connect(self.post_status_clicked) self.refresh_button = QPushButton("Refresh", self) self.refresh_button.clicked.connect(self._update_func) self.attach_button = QPushButton("Attach", self) self.attach_button.clicked.connect(lambda _ : self.set_status("Attach something")) self.lists_box = QComboBox(self) self.lists_box.currentIndexChanged.connect(self.list_changed) self.lists_box.setEditable(False) self.lists_box.addItems([u"Home"] + self._db_conn.get_lists()) self.statusLabel = QLabel("Status", self) self.charCounter = QLabel("0", self) self.gridw = QWidget(self) self.gridw.setContentsMargins(0, 0, 0, 0) gridlay = QGridLayout(self.gridw) gridlay.setContentsMargins(0, 0, 0, 0) gridlay.addWidget(self.post_field, 0, 0, 2, 1) gridlay.addWidget(self.attach_button, 0, 1, 1, 1) gridlay.addWidget(self.send_button, 1, 1, 1, 1) gridlay.addWidget(self.lists_box, 0, 2, 1, 1) gridlay.addWidget(self.refresh_button, 1, 2, 1, 1) gridlay.addWidget(self.statusLabel, 2, 0, 1, 1) gridlay.addWidget(self.charCounter, 2, 1, 1, 2) hlay = QVBoxLayout(self) hlay.addWidget(self.msgview) hlay.addWidget(self.userCombo) hlay.addWidget(self.showButton) hlay.addWidget(self.gridw) safe_conn.connect_home_timeline_updated(self.update_view) safe_conn.connect_twitter_loop_started(self.start_refresh_animation) safe_conn.connect_twitter_loop_stopped(self.stop_refresh_animation) safe_conn.connect_update_posted(self.enable_posting) safe_conn.connect_range_limit_exceeded(lambda _ : self.set_status("Range limit exceeded")) safe_conn.connect_not_authenticated(lambda _ : self.set_status("Authentication failed")) self.gridw.hide() self.update_view() self.set_status("Twitter plugin initialized") def enable_posting(self, q_id, m_id): if m_id>1: self.post_field.setText("") self.set_status("Tweet posted") else: self.set_status("Failed to post tweet, Error: " + str(abs(m_id))) self.post_field.setEnabled(True) def link_clicked(self, url): if not url.host(): if url.hasQueryItem("reply-to") and url.hasQueryItem("screen-name"): self._reply_to_id = long(convert_string(url.queryItemValue("reply-to"))) self.post_field.setPlainText("@"+convert_string(url.queryItemValue("screen-name"))+" ") self.set_status("Reply to @"+convert_string(url.queryItemValue("screen-name"))) else: self.logger.error("Unknown command from link: "+str(url.toString())) else: webbrowser.open(str(url.toString())) def list_changed(self, list_idx): if list_idx: self._list = convert_string(self.lists_box.currentText()) self.userCombo.clear() self.userCombo.addItems(self._db_conn.get_known_users()) self.userCombo.completer().setCompletionMode(QCompleter.PopupCompletion) self.userCombo.show() self.set_status(self._list) else: self.userCombo.hide() self._list = None self.update_view() def post_status_clicked(self): msg = unicode(self.post_field.toPlainText().toUtf8(), encoding="UTF-8") if msg: self._db_conn.insert_post_queue(msg, self._reply_to_id) self._reply_to_id = 0 self._update_func() self.post_field.setDisabled(True) def start_refresh_animation(self): self.refresh_button.setDisabled(True) def stop_refresh_animation(self): self.refresh_button.setEnabled(True) def show_hide_animation(self): if self.gridw.isHidden(): self.gridw.show() self.showButton.setText("v") else: self.gridw.hide() self.showButton.setText(chr(94)) def text_changed(self): count = len(self.post_field.toPlainText()) if count==0: self._reply_to_id = 0 if self._reply_to_id: self.charCounter.setText(str(count) + " - reply to ") else: self.charCounter.setText(str(count)) def toggle_user_in_list(self, _): user = convert_string(self.userCombo.currentText()) if user in self._db_conn.get_users_from_list(self._list): self._db_conn.delete_user_from_list(user, self._list) self.set_status("Removed user %s from list %s"%(user, self._list)) else: self._db_conn.add_user_to_list(user, self._list) self.set_status("Added user %s to list %s"%(user, self._list)) self.update_view() @pyqtSlot(object) def update_view(self, _ = None): template_file_path = os.path.join(get_settings().get_main_config_dir(),"tweet.thtml") tweets = self._db_conn.get_last_tweets(user_list = self._list) if len(tweets)==0: return 0 templ_text = '<div>\ <a href="http://twitter.com/$NAME$/status/$ID$">\ <img src="$IMAGE$" style="float: left; margin-right: 2px" alt="$NAME$" title="$NAME$"/>\ </a>\ <p>$TEXT$</p>\ <span><a href="http://twitter.com/$RT_USER$">$RT_USER$</a></span>\ <span style="float: right">$CREATE_TIME$ <a href="?retweet=$ID$">retweet</a> <a href="?reply-to=$ID$&screen-name=$NAME$">reply</a></span>\ </div>\ <hr style="clear: both" />\ ' if os.path.exists(template_file_path): t_file = open(template_file_path, "r") templ_text = t_file.read() t_file.close() txt = "" for t in tweets: """m_id, screen_name, user_image, create_time, message_text, retweeted_by""" text = self.URL_REGEX.sub(r'<a href="\1">\1</a>', t[4]) t_txt = templ_text.replace("$IMAGE$", t[2]).replace("$NAME$", t[1]) t_txt = t_txt.replace("$ID$", str(t[0])).replace("$TEXT$", text) t_txt = t_txt.replace("$CREATE_TIME$", self.humanReadableTime(t[3])) t_txt = t_txt.replace("$RT_USER$", t[5] if t[5] else "") txt += t_txt txt += "<p style=\"float:right\">Updated: %s</p>"%time.strftime("%H:%M") self.msgview.setHtml(txt) """helper:""" def set_status(self, status_text): self.statusLabel.setText(status_text) self.showButton.setToolTip(status_text) def humanReadableTime(self, post_time): fudge = 1.25 delta = long(time.time()) - long(post_time) if delta < (1 * fudge): return 'about a second ago' elif delta < (60 * (1 / fudge)): return 'about %d seconds ago' % (delta) elif delta < (60 * fudge): return 'about a minute ago' elif delta < (60 * 60 * (1 / fudge)): return 'about %d minutes ago' % (delta / 60) elif delta < (60 * 60 * fudge) or delta / (60 * 60) == 1: return 'about an hour ago' elif delta < (60 * 60 * 24 * (1 / fudge)): return 'about %d hours ago' % (delta / (60 * 60)) elif delta < (60 * 60 * 24 * fudge) or delta / (60 * 60 * 24) == 1: return 'about a day ago' else: return 'about %d days ago' % (delta / (60 * 60 * 24))
def hide(self): self.active = False QWidget.hide(self)
class MainWindow(QMainWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.dirty = False self.isLoaded = False self.calibration_enabled = False self.aggregate_enabled = False self.setObjectName("MainWindow") self.resize(800, 600) self.setWindowTitle("OpenFisca") app_icon = get_icon('OpenFisca22.png') self.setWindowIcon(app_icon) self.setLocale(QLocale(QLocale.French, QLocale.France)) self.setDockOptions(QMainWindow.AllowNestedDocks|QMainWindow.AllowTabbedDocks|QMainWindow.AnimatedDocks) self.centralwidget = QWidget(self) self.gridLayout = QGridLayout(self.centralwidget) self.setCentralWidget(self.centralwidget) self.centralwidget.hide() self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) # Showing splash screen pixmap = QPixmap(':/images/splash.png', 'png') self.splash = QSplashScreen(pixmap) font = self.splash.font() font.setPixelSize(10) self.splash.setFont(font) self.splash.show() self.splash.showMessage("Initialisation...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # if CONF.get('main', 'current_version', '') != __version__: # CONF.set('main', 'current_version', __version__) # Execute here the actions to be performed only once after # each update (there is nothing there for now, but it could # be useful some day... self.scenario = Scenario() # Preferences self.general_prefs = [SimConfigPage, PathConfigPage, CalConfigPage] self.oldXAXIS = 'sal' self.reforme = False self.apply_settings() # Dockwidgets creation self.splash.showMessage("Creating widgets...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.create_dockwidgets() self.populate_mainwidow() ################################################################# ## Menu initialization ################################################################# self.splash.showMessage("Creating menubar...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # Menu Fichier self.file_menu = self.menuBar().addMenu("Fichier") action_export_png = create_action(self, 'Exporter le graphique', icon = 'document-save png.png', triggered = self._graph.save_figure) action_export_csv = create_action(self, 'Exporter la table', icon = 'document-save csv.png', triggered = self._table.saveCsv) action_pref = create_action(self, u'Préférences', QKeySequence.Preferences, icon = 'preferences-desktop.png', triggered = self.edit_preferences) action_quit = create_action(self, 'Quitter', QKeySequence.Quit, icon = 'process-stop.png', triggered = SLOT('close()')) file_actions = [action_export_png, action_export_csv,None, action_pref, None, action_quit] add_actions(self.file_menu, file_actions) # Menu Edit self.edit_menu = self.menuBar().addMenu(u"Édition") action_copy = create_action(self, 'Copier', QKeySequence.Copy, triggered = self.global_callback, data = 'copy') edit_actions = [None, action_copy] add_actions(self.edit_menu, edit_actions) # Menu Simulation self.simulation_menu = self.menuBar().addMenu(u"Simulation") self.action_refresh_bareme = create_action(self, u'Calculer barèmes', shortcut = 'F8', icon = 'view-refresh.png', triggered = self.refresh_bareme) self.action_refresh_calibration = create_action(self, u'Calibrer', shortcut = 'F9', icon = 'view-refresh.png', triggered = self.refresh_calibration) self.action_refresh_aggregate = create_action(self, u'Calculer aggrégats', shortcut = 'F10', icon = 'view-refresh.png', triggered = self.refresh_aggregate) action_bareme = create_action(self, u'Barème', icon = 'bareme22.png', toggled = self.modeBareme) action_cas_type = create_action(self, u'Cas type', icon = 'castype22.png', toggled = self.modeCasType) action_mode_reforme = create_action(self, u'Réforme', icon = 'comparison22.png', toggled = self.modeReforme, tip = u"Différence entre la situation simulée et la situation actuelle") mode_group = QActionGroup(self) mode_group.addAction(action_bareme) mode_group.addAction(action_cas_type) self.mode = 'bareme' action_bareme.trigger() simulation_actions = [self.action_refresh_bareme, self.action_refresh_calibration, self.action_refresh_aggregate , None, action_bareme, action_cas_type, None, action_mode_reforme] add_actions(self.simulation_menu, simulation_actions) # Menu Help help_menu = self.menuBar().addMenu("&Aide") action_about = create_action(self, u"&About OpenFisca", triggered = self.helpAbout) action_help = create_action(self, "&Aide", QKeySequence.HelpContents, triggered = self.helpHelp) help_actions = [action_about, action_help] add_actions(help_menu, help_actions) # Display Menu view_menu = self.createPopupMenu() view_menu.setTitle("&Affichage") self.menuBar().insertMenu(help_menu.menuAction(), view_menu) # Toolbar self.main_toolbar = self.create_toolbar(u"Barre d'outil", 'main_toolbar') toolbar_actions = [action_export_png, action_export_csv, None, self.action_refresh_bareme, self.action_refresh_calibration, self.action_refresh_aggregate, None, action_bareme, action_cas_type, None, action_mode_reforme] add_actions(self.main_toolbar, toolbar_actions) self.connect(self._menage, SIGNAL('changed()'), self.changed_bareme) self.connect(self._parametres, SIGNAL('changed()'), self.changed_param) self.connect(self._aggregate_output, SIGNAL('calculated()'), self.calculated) self.connect(self._calibration, SIGNAL('param_or_margins_changed()'), self.param_or_margins_changed) self.connect(self._calibration, SIGNAL('calibrated()'), self.calibrated) # Window settings self.splash.showMessage("Restoring settings...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) settings = QSettings() size = settings.value('MainWindow/Size', QVariant(QSize(800,600))).toSize() self.resize(size) position = settings.value('MainWindow/Position', QVariant(QPoint(0,0))).toPoint() self.move(position) self.restoreState(settings.value("MainWindow/State").toByteArray()) self.splash.showMessage("Loading survey data...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.enable_aggregate(True) self.enable_calibration(True) self.refresh_bareme() self.isLoaded = True self.splash.hide() def create_toolbar(self, title, object_name, iconsize=24): toolbar = self.addToolBar(title) toolbar.setObjectName(object_name) toolbar.setIconSize( QSize(iconsize, iconsize) ) return toolbar def create_dockwidgets(self): # Création des dockwidgets self._parametres = ParamWidget('data/param.xml', self) self._menage = ScenarioWidget(self.scenario, self) self._graph = Graph(self) self._table = OutTable(self) self._aggregate_output = AggregateOutputWidget(self) self._calibration = CalibrationWidget(self) self._dataframe_widget = DataFrameDock(self) def populate_mainwidow(self): self.addDockWidget(Qt.RightDockWidgetArea, self._parametres) self.addDockWidget(Qt.RightDockWidgetArea, self._menage) self.addDockWidget(Qt.LeftDockWidgetArea, self._graph) self.addDockWidget(Qt.LeftDockWidgetArea, self._table) self.addDockWidget(Qt.LeftDockWidgetArea, self._aggregate_output) self.addDockWidget(Qt.LeftDockWidgetArea, self._calibration) self.addDockWidget(Qt.LeftDockWidgetArea, self._dataframe_widget) self.tabifyDockWidget(self._dataframe_widget, self._aggregate_output) self.tabifyDockWidget(self._aggregate_output, self._calibration) self.tabifyDockWidget(self._calibration, self._table) self.tabifyDockWidget(self._table, self._graph) def global_callback(self): """Global callback""" widget = QApplication.focusWidget() action = self.sender() callback = unicode(action.data().toString()) if hasattr(widget, callback): getattr(widget, callback)() def load_survey_data(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: # liberate some memory before loading new data self.reset_aggregate() gc.collect() fname = CONF.get('paths', 'survey_data_file') self.survey = DataTable(InputTable, survey_data = fname) self._dataframe_widget.set_dataframe(self.survey.table) return True except Exception, e: self.aggregate_enabled = False QMessageBox.warning(self, u"Impossible de lire les données", u"OpenFisca n'a pas réussi à lire les données d'enquête et passe en mode barème. L'erreur suivante a été renvoyé:\n%s\n\nVous pouvez charger des nouvelles données d'enquête dans Fichier>Paramètres>Chemins>Données d'enquête"%e) return False finally:
class PreprocessorModule(gui.OWComponent, QWidget): """The base widget for the pre-processing modules.""" change_signal = Signal() # Emitted when the settings are changed. title = NotImplemented attribute = NotImplemented methods = NotImplemented single_method = True toggle_enabled = True enabled = settings.Setting(True) disabled_value = None Layout = QtGui.QGridLayout def __init__(self, master): QWidget.__init__(self) gui.OWComponent.__init__(self, master) self.master = master self.preprocessor = master.preprocessor self.value = getattr(self.preprocessor, self.attribute) # Title bar. title_holder = QWidget() title_holder.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) title_holder.setStyleSheet( """ .QWidget { background: qlineargradient( x1:0 y1:0, x2:0 y2:1, stop:0 #F8F8F8, stop:1 #C8C8C8); border-bottom: 1px solid #B3B3B3; } """ ) self.titleArea = QHBoxLayout() self.titleArea.setContentsMargins(10, 5, 10, 5) self.titleArea.setSpacing(0) title_holder.setLayout(self.titleArea) self.title_label = QLabel(self.title) self.title_label.mouseDoubleClickEvent = self.on_toggle self.title_label.setStyleSheet("font-size: 12px; border: 2px solid red;") self.titleArea.addWidget(self.title_label) self.off_label = QLabel("[disabled]") self.off_label.setStyleSheet("color: #B0B0B0; margin-left: 5px;") self.titleArea.addWidget(self.off_label) self.off_label.hide() self.titleArea.addStretch() # Root. self.rootArea = QVBoxLayout() self.rootArea.setContentsMargins(0, 0, 0, 0) self.rootArea.setSpacing(0) self.setLayout(self.rootArea) self.rootArea.addWidget(title_holder) self.contents = QWidget() contentArea = QVBoxLayout() contentArea.setContentsMargins(15, 10, 15, 10) self.contents.setLayout(contentArea) self.rootArea.addWidget(self.contents) self.method_layout = self.Layout() self.setup_method_layout() self.contents.layout().addLayout(self.method_layout) if self.toggle_enabled: self.on_off_button = OnOffButton(enabled=self.enabled) self.on_off_button.stateChanged.connect(self.on_toggle) self.on_off_button.setContentsMargins(0, 0, 0, 0) self.titleArea.addWidget(self.on_off_button) self.display_widget(update_master_width=False) @staticmethod def get_tooltip(method): return " ".join([l.strip() for l in method.__doc__.split("\n")]).strip(".") if method.__doc__ else None @staticmethod def textify(text): return text.replace("&", "&&") @property def value(self): return getattr(self.preprocessor, self.attribute) @value.setter def value(self, value): setattr(self.preprocessor, self.attribute, value) self.change_signal.emit() def setup_method_layout(self): raise NotImplementedError def on_toggle(self, event=None): # Activated when the widget is enabled/disabled. self.enabled = not self.enabled self.display_widget() def display_widget(self, update_master_width=True): if self.enabled: self.off_label.hide() self.contents.show() self.title_label.setStyleSheet("color: #000000;") else: self.off_label.show() self.contents.hide() self.title_label.setStyleSheet("color: #B0B0B0;") if update_master_width: self.master.set_minimal_width() # set value at the end since widget should be displayed before recalculation is triggered self.value = self.get_value() if self.enabled else self.disabled_value def get_value(self): raise NotImplemented def update_value(self): self.value = self.get_value()
class RemoconMain(QMainWindow): def __init__(self, parent, title, application): self._context = parent super(RemoconMain, self).__init__() self.initialised = False self.setObjectName('Remocon') self.host_name = "localhost" self.master_uri = "http://%s:11311" % (self.host_name) self.env_host_name = os.getenv("ROS_HOSTNAME") self.env_master_uri = os.getenv("ROS_MASTER_URI") if self.env_host_name == None: self.env_host_name = 'localhost' if self.env_master_uri == None: self.env_master_uri = "http://%s:11311" % (self.env_host_name) self.application = application self._widget_main = QWidget() self.rocon_master_list = {} self.cur_selected_rocon_master = None self.is_init = False path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../ui/remocon.ui") uic.loadUi(path, self._widget_main) utils.setup_home_dirs() self.rocon_master_list_cache_path = os.path.join(utils.get_settings_cache_home(), "rocon_master.cache") self.icon_paths = {} try: self.icon_paths['unknown'] = rocon_python_utils.ros.find_resource_from_string('rocon_icons/unknown', extension='png') except (rospkg.ResourceNotFound, ValueError): console.logerror("Remocon : couldn't find icons on the ros package path (install rocon_icons and rocon_bubble_icons") sys.exit(1) self.scripts_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../scripts/") #main widget self._widget_main.list_widget.setIconSize(QSize(50, 50)) self._widget_main.list_widget.itemDoubleClicked.connect(self._connect_rocon_master) # list item double click event self._widget_main.list_widget.itemClicked.connect(self._select_rocon_master) # list item double click event self._widget_main.add_concert_btn.pressed.connect(self._set_add_rocon_master) # add button event self._widget_main.delete_btn.pressed.connect(self._delete_rocon_master) # delete button event self._widget_main.delete_all_btn.pressed.connect(self._delete_all_rocon_masters) # delete all button event self._widget_main.refresh_btn.pressed.connect(self._refresh_rocon_master_list) # refresh all button event #init self._init() self._widget_main.show() self._widget_main.activateWindow() # give it the focus self._widget_main.raise_() # make sure it is on top def __del__(self): print '[RemoconMain]: Destroy' def _init(self): self._connect_dlg_isValid = False self.cur_selected_rocon_master = None self._refresh_rocon_master_list() self.is_init = True pass def _check_up(self): for k in self.rocon_master_list.values(): print("Concert: %s" % k) rocon_master_uri = k['master_uri'] host_name = k['host_name'] print "[_check_up]:MASTER_URI[%s], HOST_NAME[%s]" % (rocon_master_uri, host_name) output = subprocess.Popen([self.scripts_path + "rocon_remocon_check_up", rocon_master_uri, host_name], stdout=subprocess.PIPE) time_out_cnt = 0 while True: print "checking: " + rocon_master_uri result = output.poll() if time_out_cnt > 30: print "timeout: " + rocon_master_uri try: output.terminate() except: print "Error: output.terminate()" k['name'] = "Unknown" k['description'] = "Unknown." k['icon'] = "unknown.png" k['flag'] = '0' break elif result == 0: args = output.communicate()[0] k['name'] = args.split('\n')[0] k['description'] = args.split('\n')[1] k['icon'] = args.split('\n')[2] if k['name'] == "Unknown": k['flag'] = '0' else: k['flag'] = '1' break time.sleep(0.1) time_out_cnt += 1 def _read_cache(self): #read cache and display the rocon master list try: cache_rocon_master_info_list = open(self.rocon_master_list_cache_path, 'r') except: console.logdebug("Remocon : no cached settings found, moving on.") return lines = cache_rocon_master_info_list.readlines() for line in lines: if line.count("[index="): rocon_master_index = line[string.find(line, "[index=") + len("[index="):string.find(line, ",name=")] rocon_master_name = line[string.find(line, "name=") + len("name="):string.find(line, ",master_uri=")] rocon_master_uri = line[string.find(line, ",master_uri=") + len(",master_uri="):string.find(line, ",host_name=")] rocon_master_host_name = line[string.find(line, ",host_name=") + len(",host_name="):string.find(line, ",description=")] rocon_master_description = line[string.find(line, ",description=") + len(",description="):string.find(line, ",icon=")] rocon_master_icon = line[string.find(line, ",icon=") + len(",icon="):string.find(line, ",flag=")] rocon_master_flag = line[string.find(line, ",flag=") + len(",flag="):string.find(line, "]")] self.rocon_master_list[rocon_master_index] = {} self.rocon_master_list[rocon_master_index]['index'] = rocon_master_index self.rocon_master_list[rocon_master_index]['name'] = rocon_master_name self.rocon_master_list[rocon_master_index]['master_uri'] = rocon_master_uri self.rocon_master_list[rocon_master_index]['host_name'] = rocon_master_host_name self.rocon_master_list[rocon_master_index]['icon'] = rocon_master_icon self.rocon_master_list[rocon_master_index]['description'] = rocon_master_description self.rocon_master_list[rocon_master_index]['flag'] = rocon_master_flag cache_rocon_master_info_list.close() def _delete_all_rocon_masters(self): for k in self.rocon_master_list.values(): del self.rocon_master_list[k["index"]] self._update_rocon_master_list() def _delete_rocon_master(self): if self.cur_selected_rocon_master in self.rocon_master_list.keys(): del self.rocon_master_list[self.cur_selected_rocon_master] self._update_rocon_master_list() def _add_rocon_master(self, params): rocon_master_uri = str(params['param1'].toPlainText()) rocon_master_host_name = str(params['param2'].toPlainText()) rocon_master_index = str(uuid.uuid4()) self.rocon_master_list[rocon_master_index] = {} self.rocon_master_list[rocon_master_index]['index'] = rocon_master_index self.rocon_master_list[rocon_master_index]['name'] = "Unknown" self.rocon_master_list[rocon_master_index]['master_uri'] = rocon_master_uri self.rocon_master_list[rocon_master_index]['host_name'] = rocon_master_host_name self.rocon_master_list[rocon_master_index]['icon'] = "unknown.png" self.rocon_master_list[rocon_master_index]['description'] = "" self.rocon_master_list[rocon_master_index]['flag'] = "0" self._update_rocon_master_list() self._refresh_rocon_master_list() def _set_add_rocon_master(self): print '_add_rocon_master' if self._connect_dlg_isValid: print "Dialog is live!!" self._connect_dlg.done(0) #dialog self._connect_dlg = QDialog(self._widget_main) self._connect_dlg.setWindowTitle("Add Ros Master") self._connect_dlg.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored) self._connect_dlg.setMinimumSize(350, 0) # dlg_rect = self._connect_dlg.geometry() #dialog layout ver_layout = QVBoxLayout(self._connect_dlg) ver_layout.setContentsMargins(9, 9, 9, 9) #param layout text_grid_sub_widget = QWidget() text_grid_layout = QGridLayout(text_grid_sub_widget) text_grid_layout.setColumnStretch(1, 0) text_grid_layout.setRowStretch(2, 0) #param 1 title_widget1 = QLabel("MASTER_URI: ") context_widget1 = QTextEdit() context_widget1.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored) context_widget1.setMinimumSize(0, 30) context_widget1.append(self.master_uri) #param 2 title_widget2 = QLabel("HOST_NAME: ") context_widget2 = QTextEdit() context_widget2.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored) context_widget2.setMinimumSize(0, 30) context_widget2.append(self.host_name) #add param text_grid_layout.addWidget(title_widget1) text_grid_layout.addWidget(context_widget1) text_grid_layout.addWidget(title_widget2) text_grid_layout.addWidget(context_widget2) #add param layout ver_layout.addWidget(text_grid_sub_widget) #button layout button_hor_sub_widget = QWidget() button_hor_layout = QHBoxLayout(button_hor_sub_widget) params = {} params['param1'] = context_widget1 params['param2'] = context_widget2 #check box use_env_var_check = QCheckBox("Use environment variables") use_env_var_check.setCheckState(Qt.Unchecked) def set_use_env_var(data, text_widget1, text_widget2): if data == Qt.Unchecked: text_widget1.setText(self.master_uri) text_widget2.setText(self.host_name) elif data == Qt.Checked: self.master_uri = str(text_widget1.toPlainText()) self.host_name = str(text_widget2.toPlainText()) text_widget1.setText(self.env_master_uri) text_widget2.setText(self.env_host_name) def check_event(data): set_use_env_var(data, context_widget1, context_widget2) use_env_var_check.stateChanged.connect(check_event) ver_layout.addWidget(use_env_var_check) #button btn_call = QPushButton("Add") btn_cancel = QPushButton("Cancel") btn_call.clicked.connect(lambda: self._connect_dlg.done(0)) btn_call.clicked.connect(lambda: self._add_rocon_master(params)) btn_cancel.clicked.connect(lambda: self._connect_dlg.done(0)) #add button button_hor_layout.addWidget(btn_call) button_hor_layout.addWidget(btn_cancel) #add button layout ver_layout.addWidget(button_hor_sub_widget) self._connect_dlg.setVisible(True) self._connect_dlg.finished.connect(self._destroy_connect_dlg) self._connect_dlg_isValid = True def _refresh_rocon_master_list(self): print '_refresh_rocon_master_list' if self.is_init: self._update_rocon_master_list() self._read_cache() self._widget_main.list_info_widget.clear() self._check_up() self._update_rocon_master_list() def _update_rocon_master_list(self): print '_update_rocon_master_list' self._widget_main.list_widget.clear() try: cache_rocon_master_info_list = open(self.rocon_master_list_cache_path, 'w') except: print "No directory or file: %s" % (self.rocon_master_list_cache_path) return for k in self.rocon_master_list.values(): self._add_rocon_master_list_item(k) rocon_master_index = k['index'] rocon_master_name = k['name'] rocon_master_uri = k['master_uri'] rocon_master_host_name = k['host_name'] rocon_master_icon = k['icon'] rocon_master_description = k['description'] rocon_master_flag = k['flag'] rocon_master_elem = '[' rocon_master_elem += 'index=' + str(rocon_master_index) + ',' rocon_master_elem += 'name=' + str(rocon_master_name) + ',' rocon_master_elem += 'master_uri=' + str(rocon_master_uri) + ',' rocon_master_elem += 'host_name=' + str(rocon_master_host_name) + ',' rocon_master_elem += 'description=' + str(rocon_master_description) + ',' rocon_master_elem += 'icon=' + rocon_master_icon + ',' rocon_master_elem += 'flag=' + rocon_master_flag rocon_master_elem += ']\n' cache_rocon_master_info_list.write(rocon_master_elem) cache_rocon_master_info_list.close() def _add_rocon_master_list_item(self, rocon_master): print('_add_rocon_master_list_item [%s]' % rocon_master['name']) rocon_master_index = rocon_master['index'] rocon_master_name = rocon_master['name'] rocon_master_uri = rocon_master['master_uri'] rocon_master_host_name = rocon_master['host_name'] rocon_master_icon = rocon_master['icon'] rocon_master_description = rocon_master['description'] rocon_master['cur_row'] = str(self._widget_main.list_widget.count()) display_name = str(rocon_master_name) + "\n" + "[" + str(rocon_master_uri) + "]" self._widget_main.list_widget.insertItem(self._widget_main.list_widget.count(), display_name) #setting the list font font = self._widget_main.list_widget.item(self._widget_main.list_widget.count() - 1).font() font.setPointSize(13) self._widget_main.list_widget.item(self._widget_main.list_widget.count() - 1).setFont(font) #setToolTip rocon_master_info = "" rocon_master_info += "rocon_master_index: " + str(rocon_master_index) + "\n" rocon_master_info += "rocon_master_name: " + str(rocon_master_name) + "\n" rocon_master_info += "master_uri: " + str(rocon_master_uri) + "\n" rocon_master_info += "host_name: " + str(rocon_master_host_name) + "\n" rocon_master_info += "description: " + str(rocon_master_description) self._widget_main.list_widget.item(self._widget_main.list_widget.count() - 1).setToolTip(rocon_master_info) #set icon if rocon_master_icon == "unknown.png": icon = QIcon(self.icon_paths['unknown']) self._widget_main.list_widget.item(self._widget_main.list_widget.count() - 1).setIcon(icon) elif len(rocon_master_icon): icon = QIcon(os.path.join(utils.get_icon_cache_home(), rocon_master_icon)) self._widget_main.list_widget.item(self._widget_main.list_widget.count() - 1).setIcon(icon) else: print rocon_master_name + ': No icon' pass def _select_rocon_master(self, Item): list_widget = Item.listWidget() for k in self.rocon_master_list.values(): if k["cur_row"] == str(list_widget.currentRow()): self.cur_selected_rocon_master = k['index'] break self._widget_main.list_info_widget.clear() info_text = "<html>" info_text += "<p>-------------------------------------------</p>" info_text += "<p><b>name: </b>" + str(self.rocon_master_list[self.cur_selected_rocon_master]['name']) + "</p>" info_text += "<p><b>master_uri: </b>" + str(self.rocon_master_list[self.cur_selected_rocon_master]['master_uri']) + "</p>" info_text += "<p><b>host_name: </b>" + str(self.rocon_master_list[self.cur_selected_rocon_master]['host_name']) + "</p>" info_text += "<p><b>description: </b>" + str(self.rocon_master_list[self.cur_selected_rocon_master]['description']) + "</p>" info_text += "<p>-------------------------------------------</p>" info_text += "</html>" self._widget_main.list_info_widget.appendHtml(info_text) def _destroy_connect_dlg(self): print "[Dialog] Destroy!!!" self._connect_dlg_isValid = False def _connect_rocon_master(self): rocon_master_name = str(self.rocon_master_list[self.cur_selected_rocon_master]['name']) rocon_master_uri = str(self.rocon_master_list[self.cur_selected_rocon_master]['master_uri']) rocon_master_host_name = str(self.rocon_master_list[self.cur_selected_rocon_master]['host_name']) rocon_master_index = str(self.cur_selected_rocon_master) if self.rocon_master_list[rocon_master_index]['flag'] == '0': # DJS: unused reply box? # reply = QMessageBox.warning(self, 'ERROR', "YOU SELECT NO CONCERT", QMessageBox.Ok|QMessageBox.Ok) return execute_path = self.scripts_path + 'rocon_remocon_sub' # command execute_path += " " + "'" + rocon_master_index + "'" # arg1 execute_path += " " + "'" + rocon_master_name + "'" # arg2 execute_path += " " + "'" + rocon_master_uri + "'" # arg3 execute_path += " " + "'" + rocon_master_host_name + "'" # arg4 self._widget_main.hide() os.execv(self.scripts_path + 'rocon_remocon_sub', ["", rocon_master_index, rocon_master_name, rocon_master_uri, rocon_master_host_name]) print "Spawning: %s" % (execute_path)
class GithubRepoWizardPage(QWizardPage): def __init__(self, github, parent=None): super(GithubRepoWizardPage, self).__init__(parent, title="Github Repository", subTitle="Configure the new Github repository") self.github = github # moreButton self.moreButton = QPushButton("More", checkable=True, clicked=self.more) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) moreButtonHBox = QHBoxLayout() moreButtonHBox.addWidget(spacer) moreButtonHBox.addWidget(self.moreButton) # LineEdits self.nameEdit = QLineEdit(textChanged=self.update) self.nameEdit.setValidator( QRegExpValidator(QRegExp(r'[a-zA-Z0-9-_]+[a-zA-Z0-9-_]*'))) self.descriptionEdit = QLineEdit(textChanged=self.update) self.homepageEdit = QLineEdit(textChanged=self.update) # CheckBox self.privateCheckBox = QCheckBox(stateChanged=self.update) self.initCheckBox = QCheckBox(stateChanged=self.update) self.hasWikiCheckBox = QCheckBox(stateChanged=self.update) self.hasDownloadsCheckBox = QCheckBox(stateChanged=self.update) self.hasIssuesCheckBox = QCheckBox(stateChanged=self.update) # gitignoreComboBox self.gitignoreComboBox = QComboBox(currentIndexChanged=self.update) self.gitignoreComboBox.addItem('None') for i in gitignore_types(self.github): self.gitignoreComboBox.addItem(i) hbox2 = QHBoxLayout() hbox2.addWidget( QLabel('Initialize this repository with a README and .gitignore')) hbox2.addWidget(self.initCheckBox) # Extension Form self.form_extension = QFormLayout() self.form_extension.addRow("Homepage", self.homepageEdit) self.form_extension.addRow("Has wiki", self.hasWikiCheckBox) self.form_extension.addRow("Has issues", self.hasIssuesCheckBox) self.form_extension.addRow("Has downloads", self.hasDownloadsCheckBox) # Extension self.extension = QWidget() self.extension.setLayout(self.form_extension) # Form self.form = QFormLayout() self.form.addRow("Name: ", self.nameEdit) self.form.addRow("Description: ", self.descriptionEdit) self.form.addRow('Private', self.privateCheckBox) self.form.addRow(hbox2) self.form.addRow('Add .gitignore', self.gitignoreComboBox) self.form.addRow(moreButtonHBox) self.form.addRow(self.extension) # Layout self.mainLayout = QVBoxLayout() self.mainLayout.addLayout(self.form) self.setLayout(self.mainLayout) # Fields self.registerField('name*', self.nameEdit) self.registerField('description', self.descriptionEdit) self.registerField('private', self.privateCheckBox) self.registerField('auto_init', self.initCheckBox) self.registerField('gitignore', self.gitignoreComboBox, 'currentText') self.registerField('homepage', self.homepageEdit) self.registerField('has_issues', self.hasIssuesCheckBox) self.registerField('has_downloads', self.hasDownloadsCheckBox) self.registerField('has_wiki', self.hasWikiCheckBox) # Setup self.hasWikiCheckBox.toggle() self.hasDownloadsCheckBox.toggle() self.hasIssuesCheckBox.toggle() if not self.github.get_user().plan: self.privateCheckBox.setEnabled(False) self.extension.hide() def update(self): if self.initCheckBox.isChecked(): self.gitignoreComboBox.setEnabled(True) else: self.gitignoreComboBox.setEnabled(False) def more(self): if self.moreButton.isChecked(): self.moreButton.setText("Less") self.extension.show() self.wizard().resize(self.wizard().sizeHint()) else: self.moreButton.setText("More") self.extension.hide() size = self.sizeHint() wizard_size = self.wizard().sizeHint() self.wizard().resize(wizard_size.width(), size.height())
class MainWindow(QMainWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.dirty = False self.setObjectName("MainWindow") self.resize(800, 600) self.setWindowTitle("GA") # TODO # TODO app_icon = get_icon('OpenFisca22.png') # self.setWindowIcon(app_icon) self.setLocale(QLocale(QLocale.French, QLocale.France)) self.setDockOptions(QMainWindow.AllowNestedDocks|QMainWindow.AllowTabbedDocks|QMainWindow.AnimatedDocks) self.centralwidget = QWidget(self) self.gridLayout = QGridLayout(self.centralwidget) self.setCentralWidget(self.centralwidget) self.centralwidget.hide() self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) # Showing splash screen pixmap = QPixmap(':/images/splash.png', 'png') self.splash = QSplashScreen(pixmap) font = self.splash.font() font.setPixelSize(10) self.splash.setFont(font) self.splash.show() self.splash.showMessage("Initialisation...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # if CONF.get('main', 'current_version', '') != __version__: # CONF.set('main', 'current_version', __version__) # Execute here the actions to be performed only once after # each update (there is nothing there for now, but it could # be useful some day... self.start() def start(self, restart = False): ''' Starts main process ''' # Preferences self.general_prefs = [PathConfigPage] self.apply_settings() # Dockwidgets creation self.splash.showMessage("Creating widgets...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.create_dockwidgets() self.populate_mainwidow() ################################################################# ## Menu initialization ################################################################# self.splash.showMessage("Creating menubar...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # Menu Fichier self.file_menu = self.menuBar().addMenu("Fichier") action_export_png = create_action(self, 'Exporter le graphique', icon = 'document-save png.png') #, triggered = None) action_export_csv = create_action(self, 'Exporter la table', icon = 'document-save csv.png') #, triggered = None) action_pref = create_action(self, u'Préférences', QKeySequence.Preferences, icon = 'preferences-desktop.png', triggered = self.edit_preferences) action_quit = create_action(self, 'Quitter', QKeySequence.Quit, icon = 'process-stop.png', triggered = SLOT('close()')) file_actions = [action_export_png, action_export_csv,None, action_pref, None, action_quit] add_actions(self.file_menu, file_actions) # Menu Edit self.edit_menu = self.menuBar().addMenu(u"Édition") action_copy = create_action(self, 'Copier', QKeySequence.Copy, triggered = self.global_callback, data = 'copy') edit_actions = [None, action_copy] add_actions(self.edit_menu, edit_actions) # Menu Projection self.projection_menu = self.menuBar().addMenu(u"Projection") # self.action_refresh_project_population = create_action(self, u'Calculer les projections de population', shortcut = 'F9', icon = 'calculator_green.png', triggered = self.project_population) projection_actions = [self.action_refresh_project_population, None ] add_actions(self.projection_menu, projection_actions) # Menu Help help_menu = self.menuBar().addMenu("&Aide") action_about = create_action(self, u"&About GA", triggered = self.helpAbout) action_help = create_action(self, "&Aide", QKeySequence.HelpContents, triggered = self.helpHelp) help_actions = [action_about, action_help] add_actions(help_menu, help_actions) # Display Menu view_menu = self.createPopupMenu() view_menu.setTitle("&Affichage") self.menuBar().insertMenu(help_menu.menuAction(), view_menu) # Toolbar self.main_toolbar = self.create_toolbar(u"Barre d'outil", 'main_toolbar') toolbar_actions = [action_export_png, action_export_csv, None, self.action_refresh_project_population,] add_actions(self.main_toolbar, toolbar_actions) # Window settings self.splash.showMessage("Restoring settings...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) settings = QSettings() size = settings.value('MainWindow/Size', QVariant(QSize(800,600))).toSize() self.resize(size) position = settings.value('MainWindow/Position', QVariant(QPoint(0,0))).toPoint() self.move(position) self.restoreState(settings.value("MainWindow/State").toByteArray()) # Connectors self.connect(self._param_widget, SIGNAL('population_changed()'), self.refresh_population) # self.connect(self._param_widget, SIGNAL('rates_changed()'), self.refresh_cohorts) self.connect(self._param_widget, SIGNAL('state_proj_changed()'), self.refresh_cohorts) self.refresh_population() self.load_data() self.splash.showMessage("Loading survey data...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.splash.hide() return def create_toolbar(self, title, object_name, iconsize=24): toolbar = self.addToolBar(title) toolbar.setObjectName(object_name) toolbar.setIconSize( QSize(iconsize, iconsize) ) return toolbar def create_dockwidgets(self): ''' Creates dockwidgets ''' self._population_widget = PopulationDataWidget(self) self._cohorts_widget = PopulationDataWidget(self) self._profiles_widget = ProfilesDataWidget(self) self._param_widget = ParametersWidget(self) self._plot_widget = PlotWidget(self) # TODO # plot population pyramides/expenses pyramides # générational flow def populate_mainwidow(self): ''' Creates all dockwidgets ''' left_widgets = [self._profiles_widget, self._population_widget , self._cohorts_widget, self._plot_widget] first_left_widget = None for widget in left_widgets: self.addDockWidget(Qt.LeftDockWidgetArea, widget) if first_left_widget is None: first_left_widget = widget else: self.tabifyDockWidget(first_left_widget, widget) def global_callback(self): """Global callback""" widget = QApplication.focusWidget() action = self.sender() callback = unicode(action.data().toString()) if hasattr(widget, callback): getattr(widget, callback)() def load_data(self): ''' Loads population and profiles data ''' QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: profiles_file = CONF.get('paths', 'profiles_file') store = HDFStore(profiles_file,'r') profiles = store['profiles'] except Exception, e: self.population_loaded = False QMessageBox.warning(self, u"Impossible de lire les données de population", u"GA n'a pas réussi à lire les données de population. L'erreur suivante a été renvoyée:\n%s\n\nVous pouvez configuer le chemin vers le fichier de données Fichier>Paramètres>Chemins>Fichier données population"%e) return False finally:
class GithubRepoWizardPage(QWizardPage): def __init__(self, github, parent=None): super(GithubRepoWizardPage, self).__init__( parent, title="Github Repository", subTitle="Configure the new Github repository") self.github = github # moreButton self.moreButton = QPushButton( "More", checkable=True, clicked=self.more) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) moreButtonHBox = QHBoxLayout() moreButtonHBox.addWidget(spacer) moreButtonHBox.addWidget(self.moreButton) # LineEdits self.nameEdit = QLineEdit(textChanged=self.update) self.nameEdit.setValidator(QRegExpValidator( QRegExp(r'[a-zA-Z0-9-_]+[a-zA-Z0-9-_]*'))) self.descriptionEdit = QLineEdit(textChanged=self.update) self.homepageEdit = QLineEdit(textChanged=self.update) # CheckBox self.privateCheckBox = QCheckBox(stateChanged=self.update) self.initCheckBox = QCheckBox(stateChanged=self.update) self.hasWikiCheckBox = QCheckBox(stateChanged=self.update) self.hasDownloadsCheckBox = QCheckBox(stateChanged=self.update) self.hasIssuesCheckBox = QCheckBox(stateChanged=self.update) # gitignoreComboBox self.gitignoreComboBox = QComboBox(currentIndexChanged=self.update) self.gitignoreComboBox.addItem('None') for i in gitignore_types(self.github): self.gitignoreComboBox.addItem(i) hbox2 = QHBoxLayout() hbox2.addWidget(QLabel( 'Initialize this repository with a README and .gitignore')) hbox2.addWidget(self.initCheckBox) # Extension Form self.form_extension = QFormLayout() self.form_extension.addRow("Homepage", self.homepageEdit) self.form_extension.addRow("Has wiki", self.hasWikiCheckBox) self.form_extension.addRow("Has issues", self.hasIssuesCheckBox) self.form_extension.addRow("Has downloads", self.hasDownloadsCheckBox) # Extension self.extension = QWidget() self.extension.setLayout(self.form_extension) # Form self.form = QFormLayout() self.form.addRow("Name: ", self.nameEdit) self.form.addRow("Description: ", self.descriptionEdit) self.form.addRow('Private', self.privateCheckBox) self.form.addRow(hbox2) self.form.addRow('Add .gitignore', self.gitignoreComboBox) self.form.addRow(moreButtonHBox) self.form.addRow(self.extension) # Layout self.mainLayout = QVBoxLayout() self.mainLayout.addLayout(self.form) self.setLayout(self.mainLayout) # Fields self.registerField('name*', self.nameEdit) self.registerField('description', self.descriptionEdit) self.registerField('private', self.privateCheckBox) self.registerField('auto_init', self.initCheckBox) self.registerField('gitignore', self.gitignoreComboBox, 'currentText') self.registerField('homepage', self.homepageEdit) self.registerField('has_issues', self.hasIssuesCheckBox) self.registerField('has_downloads', self.hasDownloadsCheckBox) self.registerField('has_wiki', self.hasWikiCheckBox) # Setup self.hasWikiCheckBox.toggle() self.hasDownloadsCheckBox.toggle() self.hasIssuesCheckBox.toggle() if not self.github.get_user().plan: self.privateCheckBox.setEnabled(False) self.extension.hide() def update(self): if self.initCheckBox.isChecked(): self.gitignoreComboBox.setEnabled(True) else: self.gitignoreComboBox.setEnabled(False) def more(self): if self.moreButton.isChecked(): self.moreButton.setText("Less") self.extension.show() self.wizard().resize(self.wizard().sizeHint()) else: self.moreButton.setText("More") self.extension.hide() size = self.sizeHint() wizard_size = self.wizard().sizeHint() self.wizard().resize(wizard_size.width(), size.height())
class Window(QMainWindow): def __init__(self,parent = None): QMainWindow.__init__(self,parent) self.resize(1024,768) self.setWindowTitle("Sabel") self.setWindowIcon(Icons.sabel) self.centralwidget = QWidget(self) self.horizontalLayout = QHBoxLayout(self.centralwidget) self.horizontalLayout.setMargin(0) self.cmdList = config.cmds() self.paramList = config.params() '''A.Editor TabWidget''' '''This parent is for findbar and vertical layout''' self.editorLayoutWidget = QWidget(self) self.editorLayoutWidget.setMinimumWidth(800) self.tabWidget = EditorTab(self) self.editorLayout = QVBoxLayout(self.editorLayoutWidget) self.editorLayout.setMargin(0) self.editorLayout.addWidget(self.tabWidget) "0.Style Layout" self.styleLayoutWidget = QFrame() self.styleLayoutWidget.setFrameShape(QFrame.StyledPanel) self.styleLayout = QHBoxLayout(self.styleLayoutWidget) self.styleTest = QPushButton(self.styleLayoutWidget) self.styleTest.setText("Change Styles") self.styleTest.clicked.connect(self.changeStyleSheet) self.popWidget = Popup(self.styleLayoutWidget) self.styleLayout.addWidget(self.styleTest) self.styleLayout.addWidget(self.popWidget) self.styleLayout.setMargin(0) self.editorLayout.addWidget(self.styleLayoutWidget) self.styleLayoutWidget.hide() "1.Find Layout" self.findLayoutWidget = QFrame() self.findLayoutWidget.setFrameShape(QFrame.StyledPanel) self.findLayout = QHBoxLayout(self.findLayoutWidget) self.lineEdit = QLineEdit(self.findLayoutWidget) self.lineEdit_2 = QLineEdit(self.findLayoutWidget) self.findClose = QPushButton(self.findLayoutWidget) self.findClose.setIcon(Icons.close_view) self.findClose.setFlat(True) self.findClose.clicked.connect(self.findBarShow) self.find = QPushButton(self.findLayoutWidget) self.find.setText("Find") self.find.clicked.connect(self.findCurrentText) self.replacefind = QPushButton(self.findLayoutWidget) self.replacefind.setText("Replace/Find") self.replacefind.clicked.connect(self.replaceFindText) self.replace = QPushButton(self.findLayoutWidget) self.replace.setText("Replace") self.replace.clicked.connect(self.replaceCurrentText) self.replaceAll = QPushButton(self.findLayoutWidget) self.replaceAll.setText("Replace All") self.replaceAll.clicked.connect(self.replaceAllText) self.caseSensitive = QToolButton(self.findLayoutWidget) self.caseSensitive.setIcon(Icons.font) self.caseSensitive.setCheckable(True) self.wholeWord = QToolButton(self.findLayoutWidget) self.wholeWord.setText("ww") self.wholeWord.setCheckable(True) self.regex = QToolButton(self.findLayoutWidget) self.regex.setText("re") self.regex.setCheckable(True) self.backward = QToolButton(self.findLayoutWidget) self.backward.setText("bk") self.backward.setCheckable(True) self.backward.setDisabled(True) self.findLayout.addWidget(self.findClose) self.findLayout.addWidget(self.find) self.findLayout.addWidget(self.lineEdit) self.findLayout.addWidget(self.lineEdit_2) self.findLayout.addWidget(self.caseSensitive) self.findLayout.addWidget(self.wholeWord) self.findLayout.addWidget(self.regex) self.findLayout.addWidget(self.backward) self.findLayout.addWidget(self.replacefind) self.findLayout.addWidget(self.replace) self.findLayout.addWidget(self.replaceAll) self.findLayout.setMargin(0) self.findLayoutWidget.setMaximumHeight(25) self.editorLayout.addWidget(self.findLayoutWidget) self.findLayoutWidget.hide() '''B.Designer''' '''This parent is for widgetsbar and design layout''' self.designerLayoutWidget = QWidget(self) self.designerLayoutWidget.setMinimumWidth(800) self.designerWidget = Screen(self) self.designerLayoutWidget.hide() self.designerLayout = QVBoxLayout(self.designerLayoutWidget) self.designerLayout.setMargin(0) self.designerLayout.addWidget(self.designerWidget) '''C.Level Editor''' '''This parent is for spritesheets and level layout''' self.levelLayoutWidget = QWidget(self) self.levelLayoutWidget.setMinimumWidth(800) self.levelWidget = Level(self) self.levelLayoutWidget.hide() self.levelLayout = QVBoxLayout(self.levelLayoutWidget) self.levelLayout.setMargin(0) self.levelLayout.addWidget(self.levelWidget) '''D.Explorer TabWidget''' self.explorerTabWidget = TreeTab(self) #self.explorerTabWidget.setMaximumWidth(200) '''1.Project Tree''' self.tab_5 = QWidget() #self.tab_5.setMaximumWidth(200) self.VerticalLayout_2 = QVBoxLayout(self.tab_5)#QHBoxLayout(self.tab_5) self.VerticalLayout_2.setMargin(0) self.treeWidget = ProjectTree(self.tab_5) #self.treeWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) #self.treeWidget.horizontalScrollBar().show() self.VerticalLayout_2.addWidget(self.treeWidget) '''2.Outline Tree''' self.tab_2 = QWidget() #self.tab_2.setMaximumWidth(200) self.VerticalLayout_3 = QVBoxLayout(self.tab_2) self.VerticalLayout_3.setMargin(0) self.outlineWidget = OutlineTree(self.tab_2) self.outlineWidget.itemDoubleClicked.connect(self.gotoLine) self.VerticalLayout_3.addWidget(self.outlineWidget) '''E.Output TabWidget''' self.outputTabWidget = OutputTab(self) self.tabWidget.currentChanged.connect(self.fileChanged) self.explorerTabWidget.currentChanged.connect(self.closeExplorer) self.outputTabWidget.currentChanged.connect(self.closeConsole) self.tabWidget.setTabsClosable(True) self.tabWidget.setTabShape(0) '''1.Output layout''' #must check self.tab_6 = QWidget() self.horizontalLayout_2 = QVBoxLayout(self.tab_6) self.horizontalLayout_2.setMargin(0) self.textEdit = QTextEdit() self.inputLayout = QHBoxLayout() self.inputLayout.setMargin(0) self.fileButton = QPushButton() self.fileButton.setText("File") self.fileButton.clicked.connect(self.getFile) self.runButton = QPushButton() self.runButton.setFlat(True) self.runButton.setIcon(Icons.go) self.combo = QComboBox() self.combo.setFixedWidth(100) self.comboAdd = QPushButton() self.comboAdd.setIcon(Icons.add) self.comboAdd.setFlat(True) self.comboAdd.clicked.connect(self.addCmd) self.comboDel = QPushButton() self.comboDel.setIcon(Icons.close_view) self.comboDel.setFlat(True) self.comboDel.clicked.connect(self.delCmd) self.combo2 = QComboBox() self.combo2.setFixedWidth(500) self.combo2Add = QPushButton() self.combo2Add.setIcon(Icons.add) self.combo2Add.setFlat(True) self.combo2Add.clicked.connect(self.addParam) self.combo2Del = QPushButton() self.combo2Del.setIcon(Icons.close_view) self.combo2Del.setFlat(True) self.combo2Del.clicked.connect(self.delParam) if(self.checkHasValue(self.cmdList)): for cmd in self.cmdList: self.combo.addItem(cmd) else: self.cmdList = [] if(self.checkHasValue(self.paramList)): for param in self.paramList: self.combo2.addItem(param) else: self.paramList = [] self.horizontalLayout_2.addWidget(self.textEdit) self.inputLayout.addWidget(QLabel("<b>Command:</b>")) self.inputLayout.addWidget(self.combo) self.inputLayout.addWidget(self.comboAdd) self.inputLayout.addWidget(self.comboDel) self.inputLayout.addWidget(QLabel("<b>Parameters:</b>")) self.inputLayout.addWidget(self.combo2) self.inputLayout.addWidget(self.combo2Add) self.inputLayout.addWidget(self.combo2Del) self.inputLayout.addWidget(self.fileButton) self.inputLayout.addWidget(self.runButton) self.horizontalLayout_2.addLayout(self.inputLayout) '''2.Error Layout''' self.tab_7 = QWidget() self.horizontalLayout_4 = QHBoxLayout(self.tab_7) self.horizontalLayout_4.setMargin(0) self.errorTree = ErrorTree(self.tab_7) self.errorTree.itemDoubleClicked.connect(self.errorLine) self.horizontalLayout_4.addWidget(self.errorTree) '''TabWidgets tabs''' #self.designerWidget.addTab(QWidget(self),"") #self.designerWidget.setTabIcon(0,Icons.close_view) #self.levelWidget.addTab(QWidget(self),"") #self.levelWidget.setTabIcon(0,Icons.close_view) self.explorerTabWidget.addTab(self.tab_5,"Projects") self.explorerTabWidget.addTab(self.tab_2,"Outline") self.explorerTabWidget.addTab(QWidget(self),"") self.explorerTabWidget.setTabIcon(0,Icons.cprj) self.explorerTabWidget.setTabIcon(1,Icons.envvar) self.explorerTabWidget.setTabIcon(2,Icons.close_view) self.outputTabWidget.addTab(self.tab_7,"Error") self.outputTabWidget.addTab(self.tab_6,"Output") self.outputTabWidget.addTab(QWidget(self),"") self.outputTabWidget.setTabIcon(0,Icons.error) self.outputTabWidget.setTabIcon(1,Icons.console_view) self.outputTabWidget.setTabIcon(2,Icons.close_view) '''Splitters''' self.split1 = QSplitter(Qt.Horizontal) self.split1.addWidget(self.explorerTabWidget) self.split1.addWidget(self.editorLayoutWidget) self.split1.addWidget(self.designerLayoutWidget) self.split1.addWidget(self.levelLayoutWidget) #self.split1.addWidget(self.tab_5) self.split2 = QSplitter(Qt.Vertical) self.split2.addWidget(self.split1) self.split2.addWidget(self.outputTabWidget) self.horizontalLayout.addWidget(self.split2) '''Status Bar''' self.statusbar = QStatusBar(self) self.aboutButton = QPushButton(self) self.aboutButton.setFlat(True) self.aboutButton.setIcon(Icons.anchor) self.aboutButton.clicked.connect(self.about) self.expButton = QPushButton(self) self.expButton.setFlat(True) self.expButton.setIcon(Icons.prj) self.expButton.clicked.connect(self.exp) self.cmdButton = QPushButton(self) self.cmdButton.setFlat(True) self.cmdButton.setIcon(Icons.console_view) self.cmdButton.clicked.connect(self.cmd) self.cmdButton.setShortcut('Ctrl+D') self.imgButton = QPushButton(self) self.imgButton.setFlat(True) self.imgButton.setIcon(Icons.color_palette) self.imgButton.clicked.connect(self.design) self.imgButton.setShortcut('Ctrl+I') self.findButton = QPushButton(self) self.findButton.setFlat(True) self.findButton.setIcon(Icons.find) self.findButton.setShortcut("Ctrl+F") self.findButton.clicked.connect(self.findBarShow) ''' self.zoominButton = QPushButton(self) self.zoominButton.setFlat(True) self.zoominButton.setIcon(Icons.zoomplus) self.zoominButton.clicked.connect(self.zoomin) self.zoomoutButton = QPushButton(self) self.zoomoutButton.setFlat(True) self.zoomoutButton.setIcon(Icons.zoomminus) self.zoomoutButton.clicked.connect(self.zoomout) ''' '''Status Text,Line Text, Progress Bar and Stop Button''' self.statusText = QLabel("Writable") #self.statusText.setAlignment(Qt.AlignCenter) self.statusText.setFixedWidth(200) self.lineText = QLabel("") self.lineText.setFixedWidth(50) self.progressbar = QProgressBar() self.progressbar.setMinimum(0) self.progressbar.setMaximum(100) self.stopButton = QPushButton(self) self.stopButton.setFlat(True) self.stopButton.setIcon(Icons.stop) self.stopButton.clicked.connect(self.forceStop) self.progressbar.hide() self.stopButton.hide() self.temp = False self.progress = False self.counter = 0 '''Adding all widgets to Status Bar''' self.statusbar.addWidget(self.aboutButton) self.statusbar.addWidget(self.expButton) self.statusbar.addWidget(self.cmdButton) self.statusbar.addWidget(self.imgButton) self.statusbar.addWidget(self.findButton) #self.statusbar.addWidget(QWidget(self)) #self.statusbar.addWidget(self.zoominButton) #self.statusbar.addWidget(self.zoomoutButton) self.statusbar.addWidget(self.statusText) self.statusbar.addWidget(self.lineText) self.statusbar.addWidget(self.progressbar) self.statusbar.addWidget(self.stopButton) #self.statusbar.setFixedHeight(18) ''''Initializing Coloring Style''' self.initEditorStyle() self.initStyleSheet() '''Adding Cental Widget and Status Bar''' self.setCentralWidget(self.centralwidget) self.setStatusBar(self.statusbar) self.textEdit.setReadOnly(True) def initStyleSheet(self): import stylesheet self.setStyleSheet(stylesheet.mainstyl) self.tabWidget.tabBar().setStyleSheet(stylesheet.stletabb) self.explorerTabWidget.tabBar().setStyleSheet(stylesheet.stletabb) self.outputTabWidget.tabBar().setStyleSheet(stylesheet.stletabb) self.popWidget.setStyleSheet(stylesheet.popbg) self.popWidget.hide() ''' This is for changing the palette/window colors to Theme ''' def initEditorStyle(self): pass #editStyle = config.readStyle() #print editStyle #pal = QPalette(self.explorerTabWidget.palette()) #print pal.color(QPalette.Base).name() #print pal.color(QPalette.Window).name() #pal.setColor(QPalette.Base,self.colorStyle.paper) #pal.setColor(QPalette.Text,self.colorStyle.color) #self.explorerTabWidget.setPalette(pal) #self.outputTabWidget.setPalette(pal) ''' This is only for testing dont know if it works for builds ''' def changeStyleSheet(self): ''' Dynamically load the changed stylesheet.py and load the modules and change the style at runtime saves countless deploys ''' import imp foo = imp.load_source('stletabb', workDir+"/stylesheet.py") #print foo.stletabb #self.setStyleSheet(stylesheet.mainstyl) self.tabWidget.tabBar().setStyleSheet(foo.stletabb) self.popWidget.setStyleSheet(foo.popbg) if(self.popWidget.isHidden()): self.popWidget.showPopup() def build_project(self): #current_file = self.files[self.tabWidget.currentIndex()] prj = self.treeWidget.getProject() if(prj != None): self.treeWidget.build(prj) def run_project(self): #current_file = self.files[self.tabWidget.currentIndex()] prj = self.treeWidget.getProject()#current_file) if(prj != None): self.treeWidget.run(prj) def forceStop(self): self.ant.kill() self.progressStop() def kill(self): self.deleteLater() #-----------------------------------------------------------------------------------# # Menu Actions Functions # #-----------------------------------------------------------------------------------# def run(self): if(config.mode() == 0): self.sq.run() elif(config.mode() == 1): self.adb.run() elif(config.mode() == 2): self.ios.run() elif(config.mode() == 3): self.c.run() def setMode(self, action): if(action.text() == "Squ"): config.setMode(0) self.toolBar.action_Build.setEnabled(False) self.toolBar.action_Run.setEnabled(False) elif(action.text() == "Emo"): config.setMode(1) self.toolBar.action_Build.setEnabled(True) self.toolBar.action_Run.setEnabled(True) elif(action.text() == "Android"): config.setMode(2) self.toolBar.action_Build.setEnabled(True) self.toolBar.action_Run.setEnabled(True) elif(action.text() == "ios"): config.setMode(3) self.toolBar.action_Build.setEnabled(False) self.toolBar.action_Run.setEnabled(False) def openCommand(self): text, ok = QInputDialog.getText(self, 'Run Command', 'Command:') cmd = str(text) if ok and cmd != "": import subprocess subprocess.Popen(cmd) def about(self): form = DialogAbout(self) def todo(self): form = DialogTodo(self) form.show() def help(self): QMessageBox.about(self,"Help","This is about all The Help that i can Give you now") def full(self): if not self.isFull: self.setWindowState(Qt.WindowFullScreen) self.isFull = True else: self.setWindowState(Qt.WindowMaximized) self.isFull = False def android(self): form = DialogAndroid(self) form.show() def antt(self): form = DialogAnt(self) form.show() def squirrel(self): form = DialogSquirrel(self) form.show() def findBarShow(self): if(self.findLayoutWidget.isHidden()): self.findLayoutWidget.show() else: self.findLayoutWidget.hide() def exp(self): if(self.explorerTabWidget.isHidden()): self.explorerTabWidget.show() else: self.explorerTabWidget.hide() def cmd(self): if(self.outputTabWidget.isHidden()): self.outputTabWidget.show() else: self.outputTabWidget.hide() def editor(self): if(self.editorLayoutWidget.isHidden()): self.editorLayoutWidget.show() self.levelLayoutWidget.hide() self.designerLayoutWidget.hide() def design(self): if(self.designerLayoutWidget.isHidden()): self.designerLayoutWidget.show() self.editorLayoutWidget.hide() self.levelLayoutWidget.hide() else: self.designerLayoutWidget.hide() self.editorLayoutWidget.show() def level(self): if(self.levelLayoutWidget.isHidden()): self.levelLayoutWidget.show() self.editorLayoutWidget.hide() self.designerLayoutWidget.hide() else: self.levelLayoutWidget.hide() self.editorLayoutWidget.show() def closeDesigner(self,no): pass ''' if(no == self.tiler.closeIndex()): if(self.tiler.isHidden()): self.tiler.show() else: self.tiler.setCurrentIndex(1) self.tiler.hide() ''' '''The current Changed idx of outputTabWidget is passed to this a param''' def closeConsole(self,no = 2): if(no == 2): if(self.outputTabWidget.isHidden()): self.outputTabWidget.show() else: self.outputTabWidget.setCurrentIndex(1) self.outputTabWidget.hide() def popOutput(self): if(self.outputTabWidget.isHidden()): self.outputTabWidget.show() self.outputTabWidget.setCurrentIndex(1) def popError(self): if(self.outputTabWidget.isHidden()): self.outputTabWidget.show() self.outputTabWidget.setCurrentIndex(0) '''The current Changed idx of explorerTabWidget is passed to this a param''' def closeExplorer(self,no = 2): if(no == 2): if(self.explorerTabWidget.isHidden()): self.explorerTabWidget.show() else: self.explorerTabWidget.setCurrentIndex(0) self.explorerTabWidget.hide() elif(no == 1): self.fileChanged(no) ''' This is to refresh the outline widget''' def fileChanged(self,no): if(self.explorerTabWidget.currentIndex() == 1): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) source = edt.text() self.outlineWidget.parseText(source) def statusSaving(self): self.statusText.setText("Saving") def statusParsing(self): self.statusText.setText("Parsing") def statusWriting(self): self.statusText.setText("Writable") def statusRunning(self): self.statusText.setText("Running") def statusStopping(self): self.statusText.setText("Stopping") def statusCommand(self): self.statusText.setText("Command") def statusBuilding(self): self.statusText.setText("Building") def statusInstalling(self): self.statusText.setText("Installing") def statusCleaning(self): self.statusText.setText("Cleaning") def statusCreating(self): self.statusText.setText("Creating") def progressStart(self): self.progress == True self.temp == True if(self.progressbar.isHidden()): self.progressbar.show() if(self.stopButton.isHidden()): self.stopButton.show() self.progressbar.setValue(1) def progressStop(self): self.progress == False self.temp == False self.progressbar.setValue(100) if not(self.progressbar.isHidden()): self.progressbar.hide() if not(self.stopButton.isHidden()): self.stopButton.hide() def progressUpdate(self): if(self.progress): if(self.temp): self.counter += 1 self.progressbar.setValue(self.counter) if(self.counter == 100): self.temp = False else: self.counter -= 1 self.progressbar.setValue(self.counter) if(self.counter == 0): self.temp = True #-----------------------------------------------------------------------------------# # Editor Functions # #-----------------------------------------------------------------------------------# '''Search and Replace Functions''' def findCurrentText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked()) def replaceCurrentText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) edt.replaceText(self.lineEdit_2.text()) def replaceFindText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) edt.replaceText(self.lineEdit_2.text()) self.findCurrentText() def replaceAllText(self): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) while(edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked())): edt.replaceText(self.lineEdit_2.text()) def errorLine(self,error): index = self.tabWidget.currentIndex() edt = self.tabWidget.widget(index) '''To prevent File item double clicking''' if(error.isFile() == False): edt.setLine(error.line) '''Font Functions''' def zoomin(self): pass #for i in range(len(self.files)): # self.tabWidget.widget(i).zoomin() def zoomout(self): pass #for i in range(len(self.files)): # self.tabWidget.widget(i).zoomout() ''' Must implement Lexer ''' def setLexer(self, action): pass #print action.text() def setApi(self, action): #print action.text() for i in range(len(self.files)): #not QString self.tabWidget.widget(i).setApi(str(action.text())) def setFont(self,font): config.setFontName(str(font.family())) for i in range(len(self.files)): self.tabWidget.widget(i).setNewFont(font) def setFontSize(self,idx): fontSize = idx+1 config.setFontSize(fontSize) for i in range(len(self.files)): self.tabWidget.widget(i).setFontSize() def gotoLine(self,item): edt = self.tabWidget.widget(self.tabWidget.currentIndex()) edt.setLine(item.line) def updateLine(self,no,col): self.lineText.setText(str(no)+" : "+str(col)) def setMargin(self): mar = config.margin() if(mar == 0): config.setMargin(1) for i in range(len(self.files)): self.tabWidget.widget(i).setMargin(1) else: config.setMargin(0) for i in range(len(self.files)): self.tabWidget.widget(i).setMargin(0) ''' Toggle ''' def setIndent(self): indent = config.indent() if(indent == 0): config.setIndent(1) for i in range(len(self.files)): self.tabWidget.widget(i).setIndent(1) else: config.setIndent(0) for i in range(len(self.files)): self.tabWidget.widget(i).setIndent(0) ''' Toggle ''' def setWhiteSpace(self): white = config.whiteSpace() if(white == 0): config.setWhiteSpace(1) for i in range(len(self.files)): self.tabWidget.widget(i).setWhitespaceVisibility(True) else: config.setWhiteSpace(0) for i in range(len(self.files)): self.tabWidget.widget(i).setWhitespaceVisibility(False) ''' Toggle ''' def setEndLine(self): for i in range(len(self.files)): edt = self.tabWidget.widget(i) edt.setEolVisibility(not edt.eolVisibility()) def setEncoding(self, action): if(action.text() == "Ascii"): config.setAscii() for i in range(len(self.files)): self.tabWidget.widget(i).setUtf8(False) elif(action.text() == "Unicode"): config.setUnicode() for i in range(len(self.files)): self.tabWidget.widget(i).setUtf8(True) def setThreshold(self,val): config.setThresh(val) for i in range(len(self.files)): #print i self.tabWidget.widget(i).setThreshold(val) def setTabWidth(self,val): config.setTabWidth(val) for i in range(len(self.files)): #print i self.tabWidget.widget(i).setTabWidth(val) '''style Functions''' #-----------------------------------------------------------------------------------# # Command Functions # #-----------------------------------------------------------------------------------# def getFile(self): self.browsedialog = DialogBrowse(self) self.browsedialog.tree.itemDoubleClicked.connect(self.getName) self.browsedialog.show() def getName(self,item): if(item.isFile()): self.browsedialog.accept() fname = item.getPath() if not (fname == ""): index = self.combo2.currentIndex() text = str(self.combo2.itemText(index))+" "+fname self.combo2.setItemText(index,text) self.paramList.pop(index) self.paramList.insert(index,text) config.setParam(self.paramList) def addCmd(self,index): text, ok = QInputDialog.getText(self, 'Add Command', 'Command:') if(ok): if(str(text) != ''): cmd = str(text).upper() self.cmdList.append(cmd) #print self.cmdList self.combo.addItem(cmd) config.setCmd(self.cmdList) config.setParam(self.paramList) def delCmd(self): index = self.combo.currentIndex() self.combo.removeItem(index) self.cmdList.pop(index) #print self.cmdList config.setCmd(self.cmdList) def addParam(self,index): text, ok = QInputDialog.getText(self, 'Add Parameters', 'Params:') if(ok): if(str(text) != ''): param = str(text) self.paramList.append(param) self.combo2.addItem(param) config.setParam(self.paramList) def delParam(self): index = self.combo2.currentIndex() self.combo2.removeItem(index) self.paramList.pop(index) config.setParam(self.paramList) def checkHasValue(self,list): if(list != None and len(list) != 0): return True else: return False
def closeWidget(self): self.timer.stop() QWidget.hide(self)
def hideNow(self): if self.__allowHide: QWidget.hide(self) self.hidden.emit()
class ProfileWizard(StandaloneWizardPage): """Wizard for the creation of a new database profile. .. attribute:: languages .. attribute:: dialects A list of languages allowed in the profile selection, an empty list will allow all languages """ languages = [] dialects = [] def __init__(self, profiles, parent=None): super(ProfileWizard, self).__init__(parent) self._connection_valid = False self.network_reply = None self.profiles = profiles self.setWindowTitle(_('Profile Wizard')) self.set_banner_logo_pixmap(art.Icon('tango/22x22/categories/preferences-system.png').getQPixmap()) self.set_banner_title(_('Create New/Edit Profile')) self.set_banner_subtitle(_('Please enter the database settings')) self.banner_widget().setStyleSheet('background-color: white;') self.manager = QtNetwork.QNetworkAccessManager( self ) self.manager.finished.connect( self.update_network_status ) #self.manager.networkAccessibleChanged.connect( self.network_accessible_changed ) self.manager.proxyAuthenticationRequired.connect( self.proxy_authentication_required ) self.create_labels_and_widgets() self.create_buttons() self.set_tab_order() self.set_widgets_values() # note: connections come after labels and widgets are created # and have default values self.connect_widgets() self.connect_buttons() timer = QtCore.QTimer(self) timer.timeout.connect( self.new_network_request ) timer.setInterval( 3000 ) timer.start() self.new_network_request() def create_labels_and_widgets(self): assert object_thread( self ) self.profile_label = QLabel(_('Profile Name:')) self.dialect_label = QLabel(_('Driver:')) self.host_label = QLabel(_('Server Host:')) self.port_label = QLabel(_('Port:')) self.database_name_label = QLabel(_('Database Name:')) self.username_label = QLabel(_('Username:'******'Password:'******'Media Location:')) self.language_label = QLabel(_('Language:')) self.proxy_host_label = QLabel(_('Proxy Host:')) self.proxy_port_label = QLabel(_('Port:')) self.proxy_username_label = QLabel(_('Proxy Username:'******'Proxy Password:'******'Media location path '\ 'is not accessible.')) self.not_accessible_media_path_label.setStyleSheet('color: red') self.not_writable_media_path_label = QLabel(_('Media location path '\ 'is not writable.')) self.not_writable_media_path_label.setStyleSheet('color: red') layout = QGridLayout() layout.addWidget(self.profile_label, 0, 0, Qt.AlignRight) layout.addWidget(self.dialect_label, 1, 0, Qt.AlignRight) layout.addWidget(self.host_label, 2, 0, Qt.AlignRight) layout.addWidget(self.port_label, 2, 3, Qt.AlignRight) layout.addWidget(self.database_name_label, 3, 0, Qt.AlignRight) layout.addWidget(self.username_label, 4, 0, Qt.AlignRight) layout.addWidget(self.password_label, 5, 0, Qt.AlignRight) layout.addWidget(self.media_location_label, 7, 0, Qt.AlignRight) layout.addWidget(self.language_label, 8, 0, Qt.AlignRight) layout.addWidget(self.proxy_host_label, 10, 0, Qt.AlignRight) layout.addWidget(self.proxy_port_label, 10, 3, Qt.AlignRight) layout.addWidget(self.proxy_username_label, 11, 0, Qt.AlignRight) layout.addWidget(self.proxy_password_label, 12, 0, Qt.AlignRight) self.profile_editor = QComboBox(self) self.profile_editor.setEditable(True) # 32767 is Qt max length for string # should be more than enough for folders # http://doc.qt.nokia.com/latest/qlineedit.html#maxLength-prop self.dialect_editor = ChoicesEditor(parent=self) self.host_editor = TextLineEditor(self, length=32767) self.host_editor.set_value('') self.port_editor = TextLineEditor(self) self.port_editor.setFixedWidth(60) self.port_editor.set_value('') self.database_name_editor = TextLineEditor(self, length=32767) self.database_name_editor.set_value('') self.username_editor = TextLineEditor(self) self.username_editor.set_value('') self.password_editor = TextLineEditor(self) self.password_editor.setEchoMode(QLineEdit.Password) self.password_editor.set_value('') self.media_location_editor = TextLineEditor(self, length=32767) self.media_location_editor.set_value('') self.language_editor = LanguageEditor(languages=self.languages, parent=self) # # try to find a default language # system_language = QtCore.QLocale.system().name() if self.languages: if system_language in self.languages: self.language_editor.set_value( system_language ) else: self.language_editor.set_value( self.languages[0] ) else: self.language_editor.set_value( system_language ) self.proxy_host_editor = TextLineEditor(self, length=32767) self.proxy_host_editor.set_value('') self.proxy_port_editor = TextLineEditor(self) self.proxy_port_editor.setFixedWidth(60) self.proxy_port_editor.set_value('') self.proxy_username_editor = TextLineEditor(self) self.proxy_username_editor.set_value('') self.proxy_password_editor = TextLineEditor(self) self.proxy_password_editor.set_value('') self.proxy_password_editor.setEchoMode(QLineEdit.Password) layout.addWidget(self.profile_editor, 0, 1, 1, 1) layout.addWidget(self.dialect_editor, 1, 1, 1, 1) layout.addWidget(self.host_editor, 2, 1, 1, 1) layout.addWidget(self.port_editor, 2, 4, 1, 1) layout.addWidget(self.database_name_editor, 3, 1, 1, 1) layout.addWidget(self.username_editor, 4, 1, 1, 1) layout.addWidget(self.password_editor, 5, 1, 1, 1) layout.addWidget(HSeparator(), 6, 0, 1, 5) layout.addWidget(self.media_location_editor, 7, 1, 1, 1) layout.addWidget(self.language_editor, 8, 1, 1, 1) layout.addWidget(HSeparator(), 9, 0, 1, 5) layout.addWidget(self.proxy_host_editor, 10, 1, 1, 1) layout.addWidget(self.proxy_port_editor, 10, 4, 1, 1) layout.addWidget(self.proxy_username_editor, 11, 1, 1, 1) layout.addWidget(self.proxy_password_editor, 12, 1, 1, 1) layout.addWidget(self.network_status_label, 13, 1, 1, 4) self.main_widget().setLayout(layout) def set_widgets_values(self): self.dialect_editor.clear() self.profile_editor.clear() if self.dialects: dialects = self.dialects else: import sqlalchemy.dialects dialects = [name for _importer, name, is_package in \ pkgutil.iter_modules(sqlalchemy.dialects.__path__) \ if is_package] self.dialect_editor.set_choices([(dialect, dialect.capitalize()) \ for dialect in dialects]) self.profile_editor.insertItems(1, [''] + \ [item for item in fetch_profiles()]) self.profile_editor.setFocus() self.update_wizard_values() def connect_widgets(self): self.profile_editor.editTextChanged.connect(self.update_wizard_values) # self.dialect_editor.currentIndexChanged.connect(self.update_wizard_values) def create_buttons(self): self.more_button = QPushButton(_('More')) self.more_button.setCheckable(True) self.more_button.setAutoDefault(False) self.cancel_button = QPushButton(_('Cancel')) self.ok_button = QPushButton(_('OK')) layout = QHBoxLayout() layout.setDirection(QBoxLayout.RightToLeft) layout.addWidget(self.cancel_button) layout.addWidget(self.ok_button) layout.addStretch() layout.addWidget(self.more_button) self.buttons_widget().setLayout(layout) self.browse_button = QPushButton(_('Browse')) self.main_widget().layout().addWidget(self.browse_button, 7, 2, 1, 3) self.setup_extension() def setup_extension(self): self.extension = QWidget() self.load_button = QPushButton(_('Load profiles')) self.save_button = QPushButton(_('Save profiles')) extension_buttons_layout = QHBoxLayout() extension_buttons_layout.setContentsMargins(0, 0, 0, 0) extension_buttons_layout.addWidget(self.load_button) extension_buttons_layout.addWidget(self.save_button) extension_buttons_layout.addStretch() extension_layout = QVBoxLayout() extension_layout.setContentsMargins(0, 0, 0, 0) extension_layout.addWidget(HSeparator()) extension_layout.addLayout(extension_buttons_layout) self.extension.setLayout(extension_layout) self.main_widget().layout().addWidget(self.extension, 15, 0, 1, 5) self.extension.hide() def set_tab_order(self): all_widgets = [self.profile_editor, self.dialect_editor, self.host_editor, self.port_editor, self.database_name_editor, self.username_editor, self.password_editor, self.media_location_editor, self.browse_button, self.language_editor, self.proxy_host_editor, self.proxy_port_editor, self.proxy_username_editor, self.proxy_password_editor, self.ok_button, self.cancel_button] i = 1 while i != len(all_widgets): self.setTabOrder(all_widgets[i-1], all_widgets[i]) i += 1 def connect_buttons(self): self.cancel_button.pressed.connect(self.reject) self.ok_button.pressed.connect(self.proceed) self.browse_button.pressed.connect(self.fill_media_location) self.more_button.toggled.connect(self.extension.setVisible) self.save_button.pressed.connect(self.save_profiles_to_file) self.load_button.pressed.connect(self.load_profiles_from_file) def proceed(self): if self.is_connection_valid(): profilename, info = self.collect_info() if profilename in self.profiles: self.profiles[profilename].update(info) else: self.profiles[profilename] = info store_profiles(self.profiles) use_chosen_profile(profilename) self.accept() def is_connection_valid(self): profilename, info = self.collect_info() mt = SignalSlotModelThread(lambda:None) mt.start() progress = ProgressDialog(_('Verifying database settings')) mt.post(lambda:self.test_connection( info ), progress.finished, progress.exception) progress.exec_() return self._connection_valid def test_connection(self, profile): self._connection_valid = False connection_string = connection_string_from_profile( profile ) engine = create_engine(connection_string, pool_recycle=True) try: connection = engine.raw_connection() cursor = connection.cursor() cursor.close() connection.close() self._connection_valid = True except Exception, e: self._connection_valid = False raise UserException( _('Could not connect to database, please check host and port'), resolution = _('Verify driver, host and port or contact your system administrator'), detail = unicode(e) )
class ProfileWizard(StandaloneWizardPage): """Wizard for the creation of a new database profile. .. attribute:: languages .. attribute:: dialects A list of languages allowed in the profile selection, an empty list will allow all languages """ languages = [] dialects = [] def __init__(self, profiles, parent=None): super(ProfileWizard, self).__init__(parent) self._connection_valid = False self.network_reply = None self.profiles = profiles self.setWindowTitle(_('Profile Wizard')) self.set_banner_logo_pixmap( art.Icon( 'tango/22x22/categories/preferences-system.png').getQPixmap()) self.set_banner_title(_('Create New/Edit Profile')) self.set_banner_subtitle(_('Please enter the database settings')) self.banner_widget().setStyleSheet('background-color: white;') self.manager = QtNetwork.QNetworkAccessManager(self) self.manager.finished.connect(self.update_network_status) #self.manager.networkAccessibleChanged.connect( self.network_accessible_changed ) self.manager.proxyAuthenticationRequired.connect( self.proxy_authentication_required) self.create_labels_and_widgets() self.create_buttons() self.set_tab_order() self.set_widgets_values() # note: connections come after labels and widgets are created # and have default values self.connect_widgets() self.connect_buttons() timer = QtCore.QTimer(self) timer.timeout.connect(self.new_network_request) timer.setInterval(3000) timer.start() self.new_network_request() def create_labels_and_widgets(self): assert object_thread(self) self.profile_label = QLabel(_('Profile Name:')) self.dialect_label = QLabel(_('Driver:')) self.host_label = QLabel(_('Server Host:')) self.port_label = QLabel(_('Port:')) self.database_name_label = QLabel(_('Database Name:')) self.username_label = QLabel(_('Username:'******'Password:'******'Media Location:')) self.language_label = QLabel(_('Language:')) self.proxy_host_label = QLabel(_('Proxy Host:')) self.proxy_port_label = QLabel(_('Port:')) self.proxy_username_label = QLabel(_('Proxy Username:'******'Proxy Password:'******'Media location path '\ 'is not accessible.')) self.not_accessible_media_path_label.setStyleSheet('color: red') self.not_writable_media_path_label = QLabel(_('Media location path '\ 'is not writable.')) self.not_writable_media_path_label.setStyleSheet('color: red') layout = QGridLayout() layout.addWidget(self.profile_label, 0, 0, Qt.AlignRight) layout.addWidget(self.dialect_label, 1, 0, Qt.AlignRight) layout.addWidget(self.host_label, 2, 0, Qt.AlignRight) layout.addWidget(self.port_label, 2, 3, Qt.AlignRight) layout.addWidget(self.database_name_label, 3, 0, Qt.AlignRight) layout.addWidget(self.username_label, 4, 0, Qt.AlignRight) layout.addWidget(self.password_label, 5, 0, Qt.AlignRight) layout.addWidget(self.media_location_label, 7, 0, Qt.AlignRight) layout.addWidget(self.language_label, 8, 0, Qt.AlignRight) layout.addWidget(self.proxy_host_label, 10, 0, Qt.AlignRight) layout.addWidget(self.proxy_port_label, 10, 3, Qt.AlignRight) layout.addWidget(self.proxy_username_label, 11, 0, Qt.AlignRight) layout.addWidget(self.proxy_password_label, 12, 0, Qt.AlignRight) self.profile_editor = QComboBox(self) self.profile_editor.setEditable(True) # 32767 is Qt max length for string # should be more than enough for folders # http://doc.qt.nokia.com/latest/qlineedit.html#maxLength-prop self.dialect_editor = ChoicesEditor(parent=self) self.host_editor = TextLineEditor(self, length=32767) self.host_editor.set_value('') self.port_editor = TextLineEditor(self) self.port_editor.setFixedWidth(60) self.port_editor.set_value('') self.database_name_editor = TextLineEditor(self, length=32767) self.database_name_editor.set_value('') self.username_editor = TextLineEditor(self) self.username_editor.set_value('') self.password_editor = TextLineEditor(self) self.password_editor.setEchoMode(QLineEdit.Password) self.password_editor.set_value('') self.media_location_editor = TextLineEditor(self, length=32767) self.media_location_editor.set_value('') self.language_editor = LanguageEditor(languages=self.languages, parent=self) # # try to find a default language # system_language = QtCore.QLocale.system().name() if self.languages: if system_language in self.languages: self.language_editor.set_value(system_language) else: self.language_editor.set_value(self.languages[0]) else: self.language_editor.set_value(system_language) self.proxy_host_editor = TextLineEditor(self, length=32767) self.proxy_host_editor.set_value('') self.proxy_port_editor = TextLineEditor(self) self.proxy_port_editor.setFixedWidth(60) self.proxy_port_editor.set_value('') self.proxy_username_editor = TextLineEditor(self) self.proxy_username_editor.set_value('') self.proxy_password_editor = TextLineEditor(self) self.proxy_password_editor.set_value('') self.proxy_password_editor.setEchoMode(QLineEdit.Password) layout.addWidget(self.profile_editor, 0, 1, 1, 1) layout.addWidget(self.dialect_editor, 1, 1, 1, 1) layout.addWidget(self.host_editor, 2, 1, 1, 1) layout.addWidget(self.port_editor, 2, 4, 1, 1) layout.addWidget(self.database_name_editor, 3, 1, 1, 1) layout.addWidget(self.username_editor, 4, 1, 1, 1) layout.addWidget(self.password_editor, 5, 1, 1, 1) layout.addWidget(HSeparator(), 6, 0, 1, 5) layout.addWidget(self.media_location_editor, 7, 1, 1, 1) layout.addWidget(self.language_editor, 8, 1, 1, 1) layout.addWidget(HSeparator(), 9, 0, 1, 5) layout.addWidget(self.proxy_host_editor, 10, 1, 1, 1) layout.addWidget(self.proxy_port_editor, 10, 4, 1, 1) layout.addWidget(self.proxy_username_editor, 11, 1, 1, 1) layout.addWidget(self.proxy_password_editor, 12, 1, 1, 1) layout.addWidget(self.network_status_label, 13, 1, 1, 4) self.main_widget().setLayout(layout) def set_widgets_values(self): self.dialect_editor.clear() self.profile_editor.clear() if self.dialects: dialects = self.dialects else: import sqlalchemy.dialects dialects = [name for _importer, name, is_package in \ pkgutil.iter_modules(sqlalchemy.dialects.__path__) \ if is_package] self.dialect_editor.set_choices([(dialect, dialect.capitalize()) \ for dialect in dialects]) self.profile_editor.insertItems(1, [''] + \ [item for item in fetch_profiles()]) self.profile_editor.setFocus() self.update_wizard_values() def connect_widgets(self): self.profile_editor.editTextChanged.connect(self.update_wizard_values) # self.dialect_editor.currentIndexChanged.connect(self.update_wizard_values) def create_buttons(self): self.more_button = QPushButton(_('More')) self.more_button.setCheckable(True) self.more_button.setAutoDefault(False) self.cancel_button = QPushButton(_('Cancel')) self.ok_button = QPushButton(_('OK')) layout = QHBoxLayout() layout.setDirection(QBoxLayout.RightToLeft) layout.addWidget(self.cancel_button) layout.addWidget(self.ok_button) layout.addStretch() layout.addWidget(self.more_button) self.buttons_widget().setLayout(layout) self.browse_button = QPushButton(_('Browse')) self.main_widget().layout().addWidget(self.browse_button, 7, 2, 1, 3) self.setup_extension() def setup_extension(self): self.extension = QWidget() self.load_button = QPushButton(_('Load profiles')) self.save_button = QPushButton(_('Save profiles')) extension_buttons_layout = QHBoxLayout() extension_buttons_layout.setContentsMargins(0, 0, 0, 0) extension_buttons_layout.addWidget(self.load_button) extension_buttons_layout.addWidget(self.save_button) extension_buttons_layout.addStretch() extension_layout = QVBoxLayout() extension_layout.setContentsMargins(0, 0, 0, 0) extension_layout.addWidget(HSeparator()) extension_layout.addLayout(extension_buttons_layout) self.extension.setLayout(extension_layout) self.main_widget().layout().addWidget(self.extension, 15, 0, 1, 5) self.extension.hide() def set_tab_order(self): all_widgets = [ self.profile_editor, self.dialect_editor, self.host_editor, self.port_editor, self.database_name_editor, self.username_editor, self.password_editor, self.media_location_editor, self.browse_button, self.language_editor, self.proxy_host_editor, self.proxy_port_editor, self.proxy_username_editor, self.proxy_password_editor, self.ok_button, self.cancel_button ] i = 1 while i != len(all_widgets): self.setTabOrder(all_widgets[i - 1], all_widgets[i]) i += 1 def connect_buttons(self): self.cancel_button.pressed.connect(self.reject) self.ok_button.pressed.connect(self.proceed) self.browse_button.pressed.connect(self.fill_media_location) self.more_button.toggled.connect(self.extension.setVisible) self.save_button.pressed.connect(self.save_profiles_to_file) self.load_button.pressed.connect(self.load_profiles_from_file) def proceed(self): if self.is_connection_valid(): profilename, info = self.collect_info() if profilename in self.profiles: self.profiles[profilename].update(info) else: self.profiles[profilename] = info store_profiles(self.profiles) use_chosen_profile(profilename) self.accept() def is_connection_valid(self): profilename, info = self.collect_info() mt = SignalSlotModelThread(lambda: None) mt.start() progress = ProgressDialog(_('Verifying database settings')) mt.post(lambda: self.test_connection(info), progress.finished, progress.exception) progress.exec_() return self._connection_valid def test_connection(self, profile): self._connection_valid = False connection_string = connection_string_from_profile(profile) engine = create_engine(connection_string, pool_recycle=True) try: connection = engine.raw_connection() cursor = connection.cursor() cursor.close() connection.close() self._connection_valid = True except Exception, e: self._connection_valid = False raise UserException( _('Could not connect to database, please check host and port'), resolution= _('Verify driver, host and port or contact your system administrator' ), detail=unicode(e))
def hideNow(self): if self.__allowHide: QWidget.hide(self) self.treeItemView.model().clear()
def hide(self): self.hasValues = False QWidget.hide(self)
class LdapWidget(DirectoryWidget): def __init__(self, config, specific_config, mainwindow, parent=None): assert config is not None assert specific_config is not None DirectoryWidget.__init__(self, config, specific_config, mainwindow, parent) self.buildInterface(config) self.updateView(self.specific_config) def buildInterface(self, config): #<server uri> self.uri = QLineEdit() self.texts.add(self.uri) self.connect(self.uri, SIGNAL('textChanged(QString)'), self.setUri) self.connect(self.uri, SIGNAL('textChanged(QString)'), self.signalModified) self.connect(self.uri, SIGNAL('textEdited(QString)'), self.helpURI) self.connect(self.uri, SIGNAL('editingFinished()'), self.noHelpURI) self.connect(self.uri, SIGNAL('editingFinished()'), self.updateUri) self.form.addRow(tr('LDAP Server(s) uri'), self.uri) self.uri.setToolTip(help_uri_tooltip) self.connect(self.uri, SIGNAL('returnPressed()'), self.signalModified) self.uri_message_area = MessageArea() self.empty_uri_label = QLabel() self.form.addRow(self.empty_uri_label, self.uri_message_area) self.empty_uri_label.hide() self.uri_message_area.hide() self.uri_message_area.setMessage(help_uri_title, help_uri_message_area) self.numeric_uri_warning = MessageArea() empty = QLabel() self.form.addRow(empty, self.numeric_uri_warning) empty.hide() self.numeric_uri_warning.hide() self.numeric_uri_warning.warning(numeric_warning_title, numeric_warning) self.numeric_uri_warning.setWidth(60) #</server uri> #<other fields> for args in self._genTextFieldsData(): text_input = self.addTextInput(*args[1:]) setattr(self, args[0], text_input) self.connect(text_input, SIGNAL('editingFinished(QString)'), self.valid) #</other fields> self.ssl_box = self.mkSslBox() self.connect(self.ssl_box, SIGNAL('toggled(bool)'), self.toggleSsl) self.form.addRow(self.ssl_box) self.form.addRow(separator()) test_widget = QPushButton(tr("Test this configuration")) self.form.addRow("", test_widget) test_widget.connect(test_widget, SIGNAL('clicked()'), self.test_ldap) def _genTextFieldsData(self): return ( ('dn_users', tr('LDAP DN for users'), self.setDnUsers), ('dn_groups', tr('LDAP DN for groups'), self.setDnGroups), ('user', tr('DN used to log in on the LDAP server'), self.setUser), ('password', tr('Password used to log in on the LDAP server'), self.setPassword, False) ) def test_ldap(self): dc, base, uri, filter, password = self.specific_config.generateTest() if uri is None or uri == '': QMessageBox.critical( self, "Missing data", "Please fill URI field" ) return if dc is None: dc == '' filter, ok = QInputDialog.getText( self, tr("LDAP Filter"), tr("Please enter a filter:"), QLineEdit.Normal, filter ) if not ok: return async = self.mainwindow.client.async() async.call( 'nuauth', 'testLDAP', dc, base, uri, unicode(filter), password, callback = self.success_test, errback = self.error_test ) def success_test(self, result): ans_no = tr("OK") ans_yes = tr("Show the server's answer") show_details = QMessageBox.question( self, tr('LDAP test results'), tr('LDAP test completed without error'), ans_no, ans_yes ) if show_details == 0: return title = tr('LDAP test results') QMessageBox.information( self, title, '<span><h2>%s</h2><pre>%s</pre></span>' % (title, unicode(result)) ) def error_test(self, result): basic_text = tr('LDAP test completed with an error') formatted_text = u"""\ <span> %s <pre> %s </pre> </span> """ % (basic_text, unicode(result)) QMessageBox.warning( self, tr('LDAP test results'), formatted_text ) def helpURI(self, text): self.uri_message_area.show() def noHelpURI(self): self.uri_message_area.hide() def toggleSsl(self, value): if value: self.selectCustomOrNupki(NUPKI) else: self.specific_config.custom_or_nupki = SSL_DISABLED self.signalModified() def setUri(self, uris_text): self.specific_config.setUri(self.readString(uris_text)) self.signalModified() self.numeric_uri_warning.setVisible(ip_in_ldapuri(self.specific_config.uri)) def setUser(self, user): self.specific_config.user = self.readString(user) def setPassword(self, password): self.specific_config.password = self.readString(password) def setDnUsers(self, dn): self.specific_config.dn_users = self.readString(dn) def setDnGroups(self, dn): self.specific_config.dn_groups = self.readString(dn) def mkSslBox(self): group = QGroupBox(tr("Check server certificate")) group.setCheckable(True) box = QVBoxLayout(group) #id 0 nupki = QRadioButton(tr("Upload certificate")) #id 1 custom = QRadioButton(tr("Use an internal PKI")) hbox = QHBoxLayout() box.addLayout(hbox) self.nupki_or_custom = QButtonGroup() self.connect(self.nupki_or_custom, SIGNAL('buttonClicked(int)'), self.toggleCustomOrNupki) for index, radio in enumerate((custom, nupki)): hbox.addWidget(radio) self.nupki_or_custom.addButton(radio, index) self.file_selector_widget = QWidget() vbox = QVBoxLayout(self.file_selector_widget) selector_label = QLabel(tr("Manually uploaded LDAP certificate")) vbox.addWidget(selector_label) add_cert_trigger = AddButton(text=tr("Upload a certificate")) vbox.addWidget(add_cert_trigger) vbox.addWidget(separator()) self.has_cert_message = QLabel( tr("There is no manually uploaded server certificate") ) self.del_cert = RemButton( tr("Delete certificate file from server") ) vbox.addWidget(self.has_cert_message) vbox.addWidget(self.del_cert) self.connect(add_cert_trigger, SIGNAL('clicked()'), self.upload_server_cert) self.connect(self.del_cert, SIGNAL('clicked()'), self.delete_server_cert) self.nupki_message = MessageArea() self.nupki_message.setMessage(tr("Warning"), tr( "There is no server certificate in the internal PKI.<br/>" "Please import or generate one using an internal PKI." ) ) for anti_button, widget in ((custom, self.nupki_message), (nupki, self.file_selector_widget)): box.addWidget(widget) self.connect(anti_button, SIGNAL('toggled(bool)'), widget.setVisible) self.selectCustomOrNupki(CUSTOM) return group def upload_server_cert(self): dialog = UploadDialog( selector_label=tr("LDAP certificate"), filter=tr("Certificate file (*.crt *.pem *)") ) accepted = dialog.exec_() if accepted != QDialog.Accepted: return filename = dialog.filename if not filename: return with open(filename, 'rb') as fd: content = fd.read() content = encodeFileContent(content) self.mainwindow.addToInfoArea(tr('Uploading of a certificate file for the ldap server')) async = self.mainwindow.client.async() async.call("nuauth", "upload_ldap_server_cert", content, callback = self.success_upload, errback = self.error_upload ) def success_upload(self, value): self.mainwindow.addToInfoArea(tr('[LDAP server cert upload] Success!')) self.specific_config.server_cert_set = True self.setServerCert() self.signalModified() def error_upload(self, value): self.mainwindow.addToInfoArea(tr('[LDAP server cert upload] Error!'), COLOR_ERROR) self.mainwindow.addToInfoArea(tr('[LDAP server cert upload] %s') % value, COLOR_ERROR) def setServerCert(self): if self.specific_config.server_cert_set: self.del_cert.show() self.has_cert_message.hide() else: self.del_cert.hide() self.has_cert_message.show() def delete_server_cert(self): confirm_box = QMessageBox(self) confirm_box.setText( tr( "Please confirm the deletion of the " "manually uploaded LDAP server certificate." ) ) confirm_box.setInformativeText( tr("Do you really want to delete the certificate file?") ) confirm_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) confirm_box.setDefaultButton(QMessageBox.Cancel) confirm = confirm_box.exec_() if confirm != QMessageBox.Ok: return async = self.mainwindow.client.async() async.call("nuauth", "delete_ldap_server_cert", callback = self.success_delete, errback = self.error_delete ) def success_delete(self, value): self.mainwindow.addToInfoArea(tr('[LDAP server cert deletion] Success!')) self.specific_config.server_cert_set = False self.setServerCert() self.signalModified() def error_delete(self, value): self.mainwindow.addToInfoArea(tr('[LDAP server cert deletion] Error!'), COLOR_ERROR) self.mainwindow.addToInfoArea(tr('[LDAP server cert deletion] %s') % value, COLOR_ERROR) def toggleCustomOrNupki(self, id): if id == 0: self.specific_config.custom_or_nupki = NUPKI else: self.specific_config.custom_or_nupki = CUSTOM self.signalModified() def selectCustomOrNupki(self, custom_or_nupki): if custom_or_nupki == CUSTOM: self.file_selector_widget.setEnabled(True) self.nupki_message.hide() id = 1 else: custom_or_nupki = NUPKI self.file_selector_widget.hide() id = 0 self.nupki_or_custom.button(id).setChecked(True) def setSslData(self, config): ssl_enabled = (SSL_DISABLED != config.custom_or_nupki) self.ssl_box.setChecked(ssl_enabled) if ssl_enabled: self.selectCustomOrNupki(config.custom_or_nupki) def updateUri(self, config=None): if config is None: config = self.specific_config self.setText(self.uri, config.uri) def updateView(self, config=None): if config is None: config = self.specific_config self.updateUri(config=config) self.setSslData(config) #never copy this one: self.setDefaultText(self.dn_users, self.specific_config.dn_users) self.setDefaultText(self.dn_groups, self.specific_config.dn_groups) self.setDefaultText(self.user, config.user) self.setDefaultText(self.password, config.password) self.setServerCert()
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.dirty = False self.setObjectName("MainWindow") self.resize(800, 600) self.setWindowTitle("GA") # TODO # TODO app_icon = get_icon('OpenFisca22.png') # self.setWindowIcon(app_icon) self.setLocale(QLocale(QLocale.French, QLocale.France)) self.setDockOptions(QMainWindow.AllowNestedDocks | QMainWindow.AllowTabbedDocks | QMainWindow.AnimatedDocks) self.centralwidget = QWidget(self) self.gridLayout = QGridLayout(self.centralwidget) self.setCentralWidget(self.centralwidget) self.centralwidget.hide() self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) # Showing splash screen pixmap = QPixmap(':/images/splash.png', 'png') self.splash = QSplashScreen(pixmap) font = self.splash.font() font.setPixelSize(10) self.splash.setFont(font) self.splash.show() self.splash.showMessage( "Initialisation...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # if CONF.get('main', 'current_version', '') != __version__: # CONF.set('main', 'current_version', __version__) # Execute here the actions to be performed only once after # each update (there is nothing there for now, but it could # be useful some day... self.start() def start(self, restart=False): ''' Starts main process ''' # Preferences self.general_prefs = [PathConfigPage] self.apply_settings() # Dockwidgets creation self.splash.showMessage( "Creating widgets...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.create_dockwidgets() self.populate_mainwidow() ################################################################# ## Menu initialization ################################################################# self.splash.showMessage( "Creating menubar...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # Menu Fichier self.file_menu = self.menuBar().addMenu("Fichier") action_export_png = create_action( self, 'Exporter le graphique', icon='document-save png.png') #, triggered = None) action_export_csv = create_action( self, 'Exporter la table', icon='document-save csv.png') #, triggered = None) action_pref = create_action(self, u'Préférences', QKeySequence.Preferences, icon='preferences-desktop.png', triggered=self.edit_preferences) action_quit = create_action(self, 'Quitter', QKeySequence.Quit, icon='process-stop.png', triggered=SLOT('close()')) file_actions = [ action_export_png, action_export_csv, None, action_pref, None, action_quit ] add_actions(self.file_menu, file_actions) # Menu Edit self.edit_menu = self.menuBar().addMenu(u"Édition") action_copy = create_action(self, 'Copier', QKeySequence.Copy, triggered=self.global_callback, data='copy') edit_actions = [None, action_copy] add_actions(self.edit_menu, edit_actions) # Menu Projection self.projection_menu = self.menuBar().addMenu(u"Projection") # self.action_refresh_project_population = create_action( self, u'Calculer les projections de population', shortcut='F9', icon='calculator_green.png', triggered=self.project_population) projection_actions = [self.action_refresh_project_population, None] add_actions(self.projection_menu, projection_actions) # Menu Help help_menu = self.menuBar().addMenu("&Aide") action_about = create_action(self, u"&About GA", triggered=self.helpAbout) action_help = create_action(self, "&Aide", QKeySequence.HelpContents, triggered=self.helpHelp) help_actions = [action_about, action_help] add_actions(help_menu, help_actions) # Display Menu view_menu = self.createPopupMenu() view_menu.setTitle("&Affichage") self.menuBar().insertMenu(help_menu.menuAction(), view_menu) # Toolbar self.main_toolbar = self.create_toolbar(u"Barre d'outil", 'main_toolbar') toolbar_actions = [ action_export_png, action_export_csv, None, self.action_refresh_project_population, ] add_actions(self.main_toolbar, toolbar_actions) # Window settings self.splash.showMessage( "Restoring settings...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) settings = QSettings() size = settings.value('MainWindow/Size', QVariant(QSize(800, 600))).toSize() self.resize(size) position = settings.value('MainWindow/Position', QVariant(QPoint(0, 0))).toPoint() self.move(position) self.restoreState(settings.value("MainWindow/State").toByteArray()) # Connectors self.connect(self._param_widget, SIGNAL('population_changed()'), self.refresh_population) # self.connect(self._param_widget, SIGNAL('rates_changed()'), self.refresh_cohorts) self.connect(self._param_widget, SIGNAL('state_proj_changed()'), self.refresh_cohorts) self.refresh_population() self.load_data() self.splash.showMessage( "Loading survey data...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.splash.hide() return def create_toolbar(self, title, object_name, iconsize=24): toolbar = self.addToolBar(title) toolbar.setObjectName(object_name) toolbar.setIconSize(QSize(iconsize, iconsize)) return toolbar def create_dockwidgets(self): ''' Creates dockwidgets ''' self._population_widget = PopulationDataWidget(self) self._cohorts_widget = PopulationDataWidget(self) self._profiles_widget = ProfilesDataWidget(self) self._param_widget = ParametersWidget(self) self._plot_widget = PlotWidget(self) # TODO # plot population pyramides/expenses pyramides # générational flow def populate_mainwidow(self): ''' Creates all dockwidgets ''' left_widgets = [ self._profiles_widget, self._population_widget, self._cohorts_widget, self._plot_widget ] first_left_widget = None for widget in left_widgets: self.addDockWidget(Qt.LeftDockWidgetArea, widget) if first_left_widget is None: first_left_widget = widget else: self.tabifyDockWidget(first_left_widget, widget) def global_callback(self): """Global callback""" widget = QApplication.focusWidget() action = self.sender() callback = unicode(action.data().toString()) if hasattr(widget, callback): getattr(widget, callback)() def load_data(self): ''' Loads population and profiles data ''' QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: profiles_file = CONF.get('paths', 'profiles_file') store = HDFStore(profiles_file, 'r') profiles = store['profiles'] except Exception, e: self.population_loaded = False QMessageBox.warning( self, u"Impossible de lire les données de population", u"GA n'a pas réussi à lire les données de population. L'erreur suivante a été renvoyée:\n%s\n\nVous pouvez configuer le chemin vers le fichier de données Fichier>Paramètres>Chemins>Fichier données population" % e) return False finally:
class __StatusBar(QStatusBar): def __init__(self, parent=None): QStatusBar.__init__(self, parent) self._widgetStatus = QWidget() vbox = QVBoxLayout(self._widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) #Search Layout self._searchWidget = SearchWidget(self) vbox.addWidget(self._searchWidget) #Replace Layout self._replaceWidget = ReplaceWidget(self) vbox.addWidget(self._replaceWidget) self._replaceWidget.setVisible(False) #Code Locator self._codeLocator = locator.CodeLocatorWidget(self) vbox.addWidget(self._codeLocator) self._codeLocator.setVisible(False) #File system completer self._fileSystemOpener = FileSystemOpener() vbox.addWidget(self._fileSystemOpener) self._fileSystemOpener.setVisible(False) self.addWidget(self._widgetStatus) self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end) self.connect(self._replaceWidget._btnCloseReplace, SIGNAL("clicked()"), lambda: self._replaceWidget.setVisible(False)) self.connect(self._replaceWidget._btnReplace, SIGNAL("clicked()"), self.replace) self.connect(self._replaceWidget._btnReplaceAll, SIGNAL("clicked()"), self.replace_all) self.connect(self._replaceWidget._btnReplaceSelection, SIGNAL("clicked()"), self.replace_selected) self.connect(self._fileSystemOpener.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self._fileSystemOpener, SIGNAL("requestHide()"), self.hide_status) def handle_tab_changed(self, new_tab): """ Re-run search if tab changed, we use the find of search widget because we want the widget to be updated. """ if self._searchWidget.isVisible(): editor = main_container.MainContainer().get_actual_editor() self._searchWidget.find_matches(editor) def explore_code(self): self._codeLocator.explore_code() def explore_file_code(self, path): self._codeLocator.explore_file_code(path) def show(self): self.clearMessage() QStatusBar.show(self) editor = main_container.MainContainer().get_actual_editor() if editor and editor.textCursor().hasSelection(): text = editor.textCursor().selectedText() self._searchWidget._line.setText(text) if self._widgetStatus.isVisible(): self._searchWidget._line.setFocus() self._searchWidget._line.selectAll() def show_replace(self): self.clearMessage() self.show() editor = main_container.MainContainer().get_actual_editor() if editor: if editor.textCursor().hasSelection(): word = editor.textCursor().selectedText() self._searchWidget._line.setText(word) self._replaceWidget.setVisible(True) def show_with_word(self): self.clearMessage() editor = main_container.MainContainer().get_actual_editor() if editor: word = editor._text_under_cursor() self._searchWidget._line.setText(word) editor = main_container.MainContainer().get_actual_editor() editor.moveCursor(QTextCursor.WordLeft) self._searchWidget.find_matches(editor) self.show() def show_locator(self): if not self._codeLocator.isVisible(): self.clearMessage() self._searchWidget.setVisible(False) self.show() self._codeLocator.setVisible(True) self._codeLocator._completer.setFocus() self._codeLocator.show_suggestions() def show_file_opener(self): self.clearMessage() self._searchWidget.setVisible(False) self._fileSystemOpener.setVisible(True) self.show() self._fileSystemOpener.pathLine.setFocus() def hide_status(self): self._searchWidget._checkSensitive.setCheckState(Qt.Unchecked) self._searchWidget._checkWholeWord.setCheckState(Qt.Unchecked) self.hide() self._searchWidget.setVisible(True) self._replaceWidget.setVisible(False) self._codeLocator.setVisible(False) self._fileSystemOpener.setVisible(False) widget = main_container.MainContainer().get_actual_widget() if widget: widget.setFocus() def replace(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match(self._searchWidget._line.text(), self._replaceWidget._lineReplace.text(), flags) if not editor.textCursor().hasSelection(): self.find() def replace_selected(self): self.replace_all(True) def replace_all(self, selected=False): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match(self._searchWidget._line.text(), self._replaceWidget._lineReplace.text(), flags, True, selected) def find(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags) def find_next(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags, True) def find_previous(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 1 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags, True) def showMessage(self, message, timeout): self._widgetStatus.hide() self._replaceWidget.setVisible(False) self.show() QStatusBar.showMessage(self, message, timeout) def message_end(self, message): if message == '': self.hide() QStatusBar.clearMessage(self) self._widgetStatus.show() widget = main_container.MainContainer().get_actual_widget() if widget: widget.setFocus()
class RemoconSub(QMainWindow): def __init__(self, parent, title, application, rocon_master_index="", rocon_master_name="", rocon_master_uri='localhost', host_name='localhost'): self.rocon_master_index = rocon_master_index self.rocon_master_uri = rocon_master_uri self.rocon_master_name = rocon_master_name self.host_name = host_name self._context = parent self.application = application super(RemoconSub, self).__init__(parent) self.initialised = False self._widget_app_list = QWidget() self._widget_role_list = QWidget() self.rocon_master_list = {} self.cur_selected_role = 0 self.app_list = {} self.cur_selected_app = None self.remocon_info = RemoconInfo(stop_app_postexec_fn=self._set_stop_app_button) path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../ui/applist.ui") uic.loadUi(path, self._widget_app_list) path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../ui/rolelist.ui") uic.loadUi(path, self._widget_role_list) utils.setup_home_dirs() self.rocon_master_list_cache_path = os.path.join(utils.get_settings_cache_home(), "rocon_master.cache") self.scripts_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../scripts/") #role list widget self._widget_role_list.role_list_widget.setIconSize(QSize(50, 50)) self._widget_role_list.role_list_widget.itemDoubleClicked.connect(self._select_role_list) self._widget_role_list.back_btn.pressed.connect(self._back_role_list) self._widget_role_list.refresh_btn.pressed.connect(self._refresh_role_list) #app list widget self._widget_app_list.app_list_widget.setIconSize(QSize(50, 50)) self._widget_app_list.app_list_widget.itemDoubleClicked.connect(self._start_app) self._widget_app_list.back_btn.pressed.connect(self._uninit_app_list) self._widget_app_list.app_list_widget.itemClicked.connect(self._select_app_list) # rocon master item click event self._widget_app_list.stop_app_btn.pressed.connect(self._stop_app) self._widget_app_list.refresh_btn.pressed.connect(self._refresh_app_list) self._widget_app_list.stop_app_btn.setDisabled(True) #init self._init() def _init(self): self._init_role_list() # Ugly Hack : our window manager is not graying out the button when an app closes itself down and the appropriate # callback (_set_stop_app_button) is fired. It does otherwise though so it looks like the window manager # is getting confused when the original program doesn't have the focus. # # Taking control of it ourselves works... self._widget_app_list.stop_app_btn.setStyleSheet(QString.fromUtf8("QPushButton:disabled { color: gray }")) self._widget_role_list.show() self.initialised = True ################################################################################################################ ##role list widget ################################################################################################################ def _init_role_list(self): if not self.remocon_info._connect(self.rocon_master_name, self.rocon_master_uri, self.host_name): return False self._refresh_role_list() return True def _uninit_role_list(self): print "[RemoconSub]_uninit_role_list" self.remocon_info._shutdown() self.cur_selected_role = 0 def _select_role_list(self, Item): print '_select_role_list: ' + Item.text() self.cur_selected_role = str(Item.text()) self.remocon_info._select_role(self.cur_selected_role) self._widget_app_list.show() self._widget_app_list.move(self._widget_role_list.pos()) self._widget_role_list.hide() self._init_app_list() def _back_role_list(self): self._uninit_role_list() execute_path = self.scripts_path + 'rocon_remocon' # command execute_path += " " + "'" + self.host_name + "'" # arg1 os.execv(self.scripts_path + 'rocon_remocon', ['', self.host_name]) print "Spawning: %s" % (execute_path) def _refresh_role_list(self): self._widget_role_list.role_list_widget.clear() role_list = self.remocon_info.get_role_list() #set list widget item (reverse order because we push them on the top) for role in reversed(role_list): self._widget_role_list.role_list_widget.insertItem(0, role) #setting the list font font = self._widget_role_list.role_list_widget.item(0).font() font.setPointSize(13) self._widget_role_list.role_list_widget.item(0).setFont(font) ################################################################################################################ ##app list widget ################################################################################################################ def _init_app_list(self): self._refresh_app_list() def _uninit_app_list(self): self._widget_role_list.show() self._widget_role_list.move(self._widget_app_list.pos()) self._widget_app_list.hide() def _refresh_app_list(self): self.app_list = {} self.app_list = self.remocon_info._get_app_list() self._widget_app_list.app_list_widget.clear() index = 0 for k in self.app_list.values(): k['index'] = index index = index + 1 self._widget_app_list.app_list_widget.insertItem(0, k['display_name']) #setting the list font font = self._widget_app_list.app_list_widget.item(0).font() font.setPointSize(13) self._widget_app_list.app_list_widget.item(0).setFont(font) #setting the icon app_icon = k['icon'] print("Icon: %s" % app_icon) if app_icon == "unknown.png": icon = QIcon(self.icon_paths['unknown']) self._widget_app_list.app_list_widget.item(0).setIcon(icon) elif len(app_icon): icon = QIcon(os.path.join(utils.get_icon_cache_home(), app_icon)) self._widget_app_list.app_list_widget.item(0).setIcon(icon) else: print self.rocon_master_name + ': No icon' pass def _select_app_list(self, Item): list_widget = Item.listWidget() cur_index = list_widget.count() - list_widget.currentRow() - 1 for k in self.app_list.values(): if(k['index'] == cur_index): self.cur_selected_app = k break self._widget_app_list.app_info.clear() info_text = "<html>" info_text += "<p>-------------------------------------------</p>" info_text += "<p><b>name: </b>" + self.cur_selected_app['name'] + "</p>" info_text += "<p><b> ---------------------</b>" + "</p>" info_text += "<p><b>compatibility: </b>" + self.cur_selected_app['compatibility'] + "</p>" info_text += "<p><b>display name: </b>" + self.cur_selected_app['display_name'] + "</p>" info_text += "<p><b>description: </b>" + self.cur_selected_app['description'] + "</p>" info_text += "<p><b>namespace: </b>" + self.cur_selected_app['namespace'] + "</p>" info_text += "<p><b>max: </b>" + str(self.cur_selected_app['max']) + "</p>" info_text += "<p><b> ---------------------</b>" + "</p>" info_text += "<p><b>remappings: </b>" + str(self.cur_selected_app['remappings']) + "</p>" info_text += "<p><b>parameters: </b>" + str(self.cur_selected_app['parameters']) + "</p>" info_text += "</html>" self._widget_app_list.app_info.appendHtml(info_text) self._set_stop_app_button() def _set_stop_app_button(self): ''' This can be used by the underlying listeners to check, and if needed, toggle the state of the stop app button whenever a running app terminates itself. ''' if not self.app_list: return try: if self.cur_selected_app["launch_list"]: console.logdebug("Remocon : enabling stop app button") self._widget_app_list.stop_app_btn.setDisabled(False) else: console.logdebug("Remocon : disabling stop app button") self._widget_app_list.stop_app_btn.setEnabled(False) except KeyError: pass # do nothing def _stop_app(self): print "Stop app: " + str(self.cur_selected_app['name']) if self.remocon_info._stop_app(self.cur_selected_app['hash']): self._set_stop_app_button() #self._widget_app_list.stop_app_btn.setDisabled(True) def _start_app(self): print "Start app: " + str(self.cur_selected_app['name']) if self.remocon_info._start_app(self.cur_selected_app['hash']): self._widget_app_list.stop_app_btn.setDisabled(False)
class Regression_PLOT_PyQt(QDialog): """ This calss return a PyQt GUI with a regression plot """ def __init__(self, Minerals=None, string=None, flag=None): super(Regression_PLOT_PyQt, self).__init__() if string is not None: self.stringK, self.stringG, self.stringRho, self.user_input = string else: self.stringK = None self.stringG = None self.stringRho = None self.user_input = False self.resize(1400, 600) self.Minerals = Minerals self.dirty = False #self.user_input = user_input self.Minerals.original_flag() self.Minerals.read_data() self.table = QTableView() self.model = QStandardItemModel(25, 7, self) self.model.setHorizontalHeaderLabels([ 'flag', 'Water Content', 'Iron Content', 'K (Gpa)', 'G (Gpa)', 'Rho (g/cm³)', 'Reference' ]) for i in range(len(self.Minerals.Flag)): a = self.Minerals.Return_original_data(i) for j in range(0, 7): item = QStandardItem(str(a[j])) self.model.setItem(i, j, item) if j != 0: item.setFlags(Qt.ItemIsEnabled) item.setBackground(QColor(211, 211, 211)) if flag is not None: self.Minerals.change_flag(flag) for i in range(len(self.Minerals.Flag)): item = QStandardItem(str(self.Minerals.Flag[i])) self.model.setItem(i, 0, item) self.table.setModel(self.model) self.button = QPushButton('Update and use in thermoelastic model') self.button.clicked.connect(self.Update) self.button.setAutoDefault(False) self.button1 = QPushButton('Add data file ') self.button1.clicked.connect(self.Export) self.button1.setAutoDefault(False) self.layout = QGridLayout() self.label = QLabel() self.label.setText(''' Please input equation, Water: water content (wt%) and Fe: iron content (mol%) for example -2.41*Water-30*Fe+81,K'=4.1, ''') self.Kinput_formula = QLineEdit() self.Ginput_formula = QLineEdit() self.Rhoinput_formula = QLineEdit() if self.stringK is not None: self.Kinput_formula.setText(self.stringK) self.Ginput_formula.setText(self.stringG) self.Rhoinput_formula.setText(self.stringRho) self.Userinput() else: self.Kinput_formula.setText( self.Minerals.Show_fit_function(self.Minerals.function_K()[0], self.Minerals.function_K()[1], "K'", error=False)) self.Ginput_formula.setText( self.Minerals.Show_fit_function(self.Minerals.function_G()[0], self.Minerals.function_G()[1], "G'", error=False)) self.Rhoinput_formula.setText( self.Minerals.Show_fit_function( self.Minerals.function_Rho()[0], self.Minerals.function_Rho()[1], '', error=False)) self.Kinput_formula.returnPressed.connect(self.Kformula) self.Ginput_formula.returnPressed.connect(self.Gformula) self.Rhoinput_formula.returnPressed.connect(self.Rhoformula) #self.connect(self.Kinput_formula,SIGNAL("returnPressed()"),self.Kformula) #self.connect(self.Ginput_formula,SIGNAL("returnPressed()"),self.Gformula) #self.connect(self.Rhoinput_formula,SIGNAL("returnPressed()"),self.Rhoformula) self.user_change_confrim = QPushButton('Change to user input') self.user_change_confrim.clicked.connect(self.Userinput) self.user_change_confrim.setAutoDefault(False) self.extension = QWidget() self.extensionLayout = QGridLayout() self.extensionLayout.setContentsMargins(0, 0, 0, 0) labelK = QLabel() labelK.setText('K<sub>0</sub>=') labelG = QLabel() labelG.setText('G<sub>0</sub>=') labelRho = QLabel() labelRho.setText('Rho<sub>0</sub>=') self.extensionLayout.addWidget(labelK, 0, 0, 1, 3) self.extensionLayout.addWidget(labelG, 1, 0, 1, 3) self.extensionLayout.addWidget(labelRho, 2, 0, 1, 3) self.extensionLayout.addWidget(self.Kinput_formula, 0, 1, 1, 3) self.extensionLayout.addWidget(self.Ginput_formula, 1, 1, 1, 3) self.extensionLayout.addWidget(self.Rhoinput_formula, 2, 1, 1, 3) self.extensionLayout.addWidget(self.user_change_confrim, 3, 0, 9, 4) self.extension.setLayout(self.extensionLayout) self.check_change = QCheckBox("user input") self.check_change.setChecked(False) self.check_change.toggled.connect(self.extension.setVisible) #self.PLOT(switch=True) self.PLOT() self.layout.addWidget(self.table, 0, 1, 1, 17) self.layout.addWidget(self.button, 2, 0, 1, 9) self.layout.addWidget(self.button1, 2, 9, 1, 9) self.layout.addWidget(self.check_change, 3, 0, 1, 1) self.layout.addWidget(self.label, 3, 3, 1, 5) self.layout.addWidget(self.extension, 4, 0, 1, 9) self.setLayout(self.layout) self.extension.hide() def Kformula(self): self.stringK = str(self.Kinput_formula.text()) self.K0 = np.array( re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", self.stringK)) return self.K0, self.stringK def Gformula(self): self.stringG = str(self.Ginput_formula.text()) self.G0 = np.array( re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", self.stringG)) return self.G0, self.stringG def Rhoformula(self): self.stringRho = str(self.Rhoinput_formula.text()) self.Rho0 = np.array( re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", self.stringRho)) return self.Rho0, self.stringRho def Userinput(self): self.Minerals.User_Change(self.Kformula(), self.Gformula(), self.Rhoformula()) self.user_input = True self.PLOT() def PLOT(self, switch=True): if self.dirty == False: #self.Minerals.Clean_content() params = [] for i in range(20): index = self.model.index(i, 0) try: aa = (float(self.model.itemData(index)[0])) #print (aa) params.append(aa) except: break #print (params) self.Minerals.Change_data_from_table(params) #print ('wf') else: self.model.setHorizontalHeaderLabels([ 'flag', 'Water Content', 'Iron Content', 'K (Gpa)', 'G (Gpa)', 'Rho (g/cm3)', 'Reference' ]) for i in range(len(self.Minerals.Flag)): #a=self.Minerals.Return_original_data(i) item = QStandardItem(str(self.Minerals.Flag[i])) self.model.setItem(i, 0, item) #============================================================================== # for j in range(1,7): # item = QStandardItem(str(a[j])) # self.model.setItem(i, j,item) # if j != 0: # item.setFlags(Qt.ItemIsEnabled) # item.setBackground(QColor(211,211,211)) #============================================================================== #print (self.Minerals.Change) if self.user_input == False: self.a, self.b, self.c = self.Minerals.PLOT(return_fig=False) #print (self.Minerals.number_of_data) self.Kinput_formula.setText( self.Minerals.Show_fit_function(self.Minerals.function_K()[0], self.Minerals.function_K()[1], "K'", error=False)) self.Ginput_formula.setText( self.Minerals.Show_fit_function(self.Minerals.function_G()[0], self.Minerals.function_G()[1], "G'", error=False)) self.Rhoinput_formula.setText( self.Minerals.Show_fit_function( self.Minerals.function_Rho()[0], self.Minerals.function_Rho()[1], '', error=False)) else: self.a, self.b, self.c = self.Minerals.PLOT_input_formula( return_fig=False) self.canvas1 = FigureCanvas3D(self.a) self.canvas2 = FigureCanvas3D(self.b) self.canvas3 = FigureCanvas3D(self.c) self.canvas1.mpl_connect('pick_event', self.onpick) self.canvas2.mpl_connect('pick_event', self.onpick) self.canvas3.mpl_connect('pick_event', self.onpick) self.toolbar1 = NavigationToolbar(self.canvas1, self) self.toolbar2 = NavigationToolbar(self.canvas2, self) self.toolbar3 = NavigationToolbar(self.canvas3, self) self.layout1_widget = QWidget() self.layout1 = QGridLayout(self.layout1_widget) self.layout1_widget.setFixedSize(600, 600) self.layout1.addWidget(self.canvas1, 0, 1, 5, 5) self.layout1.addWidget(self.toolbar1, 5, 1, 1, 5) self.layout1.addWidget(self.canvas2, 6, 1, 5, 5) self.layout1.addWidget(self.toolbar2, 11, 1, 1, 5) self.layout1.addWidget(self.canvas3, 12, 1, 5, 5) self.layout1.addWidget(self.toolbar3, 17, 1, 1, 5) self.layout.addWidget(self.layout1_widget, 0, 0, 1, 1) def onpick(self, event): try: for i in range(6): self.model.item(self.ind, i + 1).setBackground(QColor(211, 211, 211)) except: pass count = -1 for j in range(len((self.Minerals.Flag))): if self.Minerals.Flag[j] == 1: count += 1 if count == event.ind[0]: self.ind = j break #print (self.ind) #self.ind = event.ind for i in range(6): self.model.item(self.ind, i + 1).setBackground(QColor(111, 111, 111)) def Update(self): self.user_input = False self.dirty = False self.check_change.setChecked(False) self.PLOT() def Export(self): self.dirty = True dialog = TextEditor(name=self.Minerals.name) if dialog.exec_(): pass self.Minerals.read_data() self.PLOT() def ReturnString(self): aa = self.Minerals.Flag bb = str(int(aa[0])) for i in range(1, len(aa)): bb += str(int(aa[i])) return [self.stringK, self.stringG, self.stringRho, self.user_input], bb
class PreprocessorModule(QWidget): """The base widget for the pre-processing modules.""" change_signal = Signal() # Emitted when the settings are changed. # Emitted when the module has a message to display in the main widget. error_signal = Signal(str) enabled = False # If the module is enabled. def __init__(self, title, toggle_enabled, is_enabled): super().__init__() # Title bar. title_holder = QWidget() title_holder.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) title_holder.setStyleSheet(""" .QWidget { background: qlineargradient( x1:0 y1:0, x2:0 y2:1, stop:0 #F8F8F8, stop:1 #C8C8C8); border-bottom: 1px solid #B3B3B3; } """) self.titleArea = QHBoxLayout() self.titleArea.setContentsMargins(15, 10, 15, 10) self.titleArea.setSpacing(0) title_holder.setLayout(self.titleArea) self.title_label = QLabel(title) self.title_label.setStyleSheet('font-size: 12px;') self.titleArea.addWidget(self.title_label) self.off_label = QLabel('[disabled]') self.off_label.setStyleSheet('color: #B0B0B0; margin-left: 5px;') self.titleArea.addWidget(self.off_label) self.off_label.hide() self.titleArea.addStretch() # Root. self.rootArea = QVBoxLayout() self.rootArea.setContentsMargins(0, 0, 0, 0) self.rootArea.setSpacing(0) self.setLayout(self.rootArea) self.rootArea.addWidget(title_holder) self.contents = QWidget() contentArea = QVBoxLayout() contentArea.setContentsMargins(15, 10, 15, 10) self.contents.setLayout(contentArea) self.rootArea.addWidget(self.contents) self.enabled = is_enabled if toggle_enabled: self.toggle_module_switch = QCheckBox() switch_icon_on_resource = _i('on_button.png') switch_icon_off_resource = _i('off_button.png') style_sheet = ''' QCheckBox::indicator { width: 23px; height: 23px; } QCheckBox::indicator:checked { image: url(%s); } QCheckBox::indicator:unchecked { image: url(%s); } ''' % (switch_icon_on_resource, switch_icon_off_resource) self.toggle_module_switch.setStyleSheet(style_sheet) self.toggle_module_switch.setChecked(self.enabled) self.toggle_module_switch.stateChanged.connect(self.on_toggle) # Change the view according to the flag. if self.enabled: self.off_label.hide() self.contents.show() self.title_label.setStyleSheet('color: #000000;') else: self.off_label.show() self.contents.hide() self.title_label.setStyleSheet('color: #B0B0B0;') self.titleArea.addWidget(self.toggle_module_switch) def add_to_content_area(self, new_widget): self.contents.layout().addWidget(new_widget) def add_layout_to_content_area(self, new_layout): self.contents.layout().addLayout(new_layout) def notify_on_change(self): # Emits signals corresponding to the changes done. self.change_signal.emit() def on_toggle(self): # Activated when the widget is enabled/disabled. self.enabled = not self.enabled if self.enabled: self.off_label.hide() self.contents.show() self.title_label.setStyleSheet('color: #000000;') else: self.off_label.show() self.contents.hide() self.title_label.setStyleSheet('color: #B0B0B0;') self.change_signal.emit() def restore_data(self, data): # Restores the widget state from the input data. raise NotImplementedError def export_data(self): # Export the settings for this module instance. return NotImplementedError @staticmethod def get_pp_settings(): # Returns the dict representation of this portion of a pre-processor. return NotImplementedError
class UiController: def __init__(self, controller, debug_mode, logger): self.controller = controller self.datahandler = controller.datahandler self.debug_mode = debug_mode self.logger = logger ### Main Window self.main_widget = QMainWindow() self.main_widget.setAttribute(Qt.WA_Maemo5StackedWindow) self.main_ui = Ui_DropN900Widget() self.main_ui.setupUi(self.main_widget) # Stacked layout for context switching self.stacked_layout = QtGui.QStackedLayout() self.main_ui.centralwidget.setLayout(self.stacked_layout) # Menu items self.action_transfers = QtGui.QAction("Transfers", self.main_widget) self.action_settings = QtGui.QAction("Settings", self.main_widget) self.action_sync = QtGui.QAction("Synchronize", self.main_widget) self.action_sync_photos = QtGui.QAction("Sync Media", self.main_widget) self.action_console = QtGui.QAction("Show Log", self.main_widget) self.action_about = QtGui.QAction("About", self.main_widget) self.action_exit = QtGui.QAction("Exit", self.main_widget) self.main_ui.menubar.addAction(self.action_transfers) self.main_ui.menubar.addAction(self.action_settings) self.main_ui.menubar.addAction(self.action_sync) self.main_ui.menubar.addAction(self.action_sync_photos) self.main_ui.menubar.addAction(self.action_console) self.main_ui.menubar.addAction(self.action_about) self.main_ui.menubar.addAction(self.action_exit) # Connects self.action_transfers.triggered.connect(self.show_transfer_widget) self.action_sync.triggered.connect(self.synchronize_now) self.action_sync_photos.triggered.connect(self.synchronize_now_photos) self.action_settings.triggered.connect(self.show_settings_widget) self.action_console.triggered.connect(self.show_console) self.action_about.triggered.connect(self.show_about) self.action_exit.triggered.connect(self.shut_down) ### Trusted Login Widget self.trusted_login_widget = QWidget() self.trusted_login_ui = Ui_TrustedLoginWidget() self.trusted_login_ui.setupUi(self.trusted_login_widget) self.trusted_login_ui.label_icon.setPixmap(QPixmap(self.datahandler.datapath("ui/images/dropn900_logo.png")).scaled(65,65)) # Connects self.trusted_login_ui.button_auth.clicked.connect(self.try_trusted_login) ### Manager Widget self.manager_widget = QWidget() self.manager_ui = Ui_ManagerWidget() self.manager_ui.setupUi(self.manager_widget) # Tree Controller tree = self.manager_ui.tree_widget self.tree_controller = TreeController(tree, self.manager_ui, self.controller, self.logger) # Hide public link elements on start self.manager_ui.button_copy_public_link.hide() self.manager_ui.button_open_public_link.hide() # Connects self.manager_ui.button_copy_public_link.clicked.connect(self.copy_item_link) self.manager_ui.button_open_public_link.clicked.connect(self.open_item_link) self.manager_ui.button_download.clicked.connect(self.item_download) self.manager_ui.button_upload.clicked.connect(self.item_upload) self.manager_ui.button_rename.clicked.connect(self.item_rename) self.manager_ui.button_remove.clicked.connect(self.item_remove) self.manager_ui.button_new_folder.clicked.connect(self.item_new_folder) self.manager_ui.sync_button.clicked.connect(self.synchronize_now) self.last_dl_location = None self.last_ul_location = None ### Console widget self.console_widget = QWidget(self.main_widget, Qt.Window) self.console_widget.setAttribute(Qt.WA_Maemo5StackedWindow) self.console_ui = Ui_ConsoleWidget() self.console_ui.setupUi(self.console_widget) self.console_ui.button_save.clicked.connect(self.save_log_to_file) self.console_ui.button_back.clicked.connect(self.hide_console) ### Settings widget self.settings_widget = None ### Fill stacked layout self.stacked_layout.addWidget(self.trusted_login_widget) self.stacked_layout.addWidget(self.manager_widget) self.stacked_layout.setCurrentWidget(self.trusted_login_widget) ### Loading Widget self.loading_widget = QWidget(self.manager_widget) self.loading_ui = Ui_LoadingWidget() self.loading_ui.setupUi(self.loading_widget) self.manager_ui.action_layout.insertWidget(3, self.loading_widget) self.loading_widget.hide() self.tree_controller.set_loading_ui(self.loading_ui) # Init loading animation self.loading_animation = QMovie(self.datahandler.datapath("ui/images/loading.gif"), "GIF", self.loading_ui.load_animation_label) self.loading_animation.setCacheMode(QMovie.CacheAll) self.loading_animation.setSpeed(150) self.loading_animation.setScaledSize(QtCore.QSize(48,48)) self.loading_ui.load_animation_label.setMovie(self.loading_animation) # Init hide timer and icons for information messages self.information_message_timer = QTimer() self.information_message_timer.setSingleShot(True) self.information_message_timer.timeout.connect(self.hide_information_message) self.information_icon_ok = QPixmap(self.datahandler.datapath("ui/icons/check.png")).scaled(24,24) self.information_icon_error = QPixmap(self.datahandler.datapath("ui/icons/cancel.png")).scaled(24,24) self.information_icon_queue = QPixmap(self.datahandler.datapath("ui/icons/queue.png")).scaled(24,24) ### About dialog self.about_dialog = AboutDialog(self) self.set_synching(False) def set_synching(self, syncing): self.manager_ui.sync_button.setVisible(not syncing) self.manager_ui.sync_label.setVisible(syncing) def set_settings_widget(self, settings_widget): self.settings_widget = settings_widget def set_transfer_widget(self, transfer_widget): self.transfer_widget = transfer_widget def synchronize_now(self): self.settings_widget.sync_now_clicked() def synchronize_now_photos(self): self.controller.sync_manager.sync_media() def show(self): # Nokia N900 screen resolution, full screen self.main_widget.resize(800, 480) self.main_widget.show() self.main_widget.showMaximized() def show_settings_widget(self): if self.settings_widget != None: if not self.settings_widget.isVisible(): self.settings_widget.show() self.settings_widget.check_settings() def show_transfer_widget(self): if self.settings_widget.isVisible(): self.settings_widget.hide() self.transfer_widget.show() def show_about(self): if not self.about_dialog.isVisible(): self.about_dialog.show() def show_note(self, message): QMaemo5InformationBox.information(None, QString(message), 0) def show_banner(self, message, timeout = 5000): QMaemo5InformationBox.information(None, QString(message), timeout) def show_loading_ui(self, message = "", loading = True): self.loading_ui.info_label.setText(message) self.loading_ui.info_label_icon.hide() self.thumb_was_visible = self.manager_ui.thumb_container.isVisible() self.manager_ui.thumb_container.hide() self.loading_widget.show() self.loading_ui.load_animation_label.setVisible(loading) if loading: self.loading_animation.start() else: self.loading_animation.stop() def show_information_ui(self, message, succesfull, timeout = 4000): self.loading_ui.load_animation_label.hide() self.thumb_was_visible = self.manager_ui.thumb_container.isVisible() if self.thumb_was_visible: self.manager_ui.thumb_container.hide() self.loading_ui.info_label.setText(message) if succesfull == None: icon = self.information_icon_queue elif succesfull: icon = self.information_icon_ok else: icon = self.information_icon_error self.loading_ui.info_label_icon.setPixmap(icon) self.loading_ui.info_label_icon.show() self.loading_widget.show() self.information_message_timer.start(timeout) def hide_loading_ui(self): if not self.information_message_timer.isActive(): self.loading_widget.hide() if self.loading_animation.state() == QMovie.Running: self.loading_animation.stop() def hide_information_message(self): self.loading_ui.info_label_icon.hide() self.hide_loading_ui() self.manager_ui.thumb_container.setVisible(self.thumb_was_visible) def try_trusted_login(self): self.trusted_login_ui.label_error.setText("") email = self.trusted_login_ui.line_edit_email.text() password = self.trusted_login_ui.line_edit_password.text() error = None if email.isEmpty(): error = "Email can't be empty!" elif email.count("@") != 1: error = "Invalid email, check your @ signs!" elif email.contains(" "): error = "Invalid email, can't have spaces!" elif password.isEmpty(): error = "Password can't be empty!" if error == None: self.show_banner("Authenticating...", 3000) self.set_trusted_login_info("Authenticating, please wait...") self.truested_email = self.datahandler.to_unicode(str(email.toUtf8())) self.trusted_password = self.datahandler.to_unicode(str(password.toUtf8())) QTimer.singleShot(100, self.do_trusted_login_networking) else: self.set_trusted_login_error(error) def set_trusted_login_error(self, error): self.trusted_login_ui.label_error.setStyleSheet("color: #9d1414;") self.trusted_login_ui.label_error.setText(error) self.truested_email = None self.trusted_password = None def set_trusted_login_info(self, info): self.trusted_login_ui.label_error.setStyleSheet("color: #149d2b;") self.trusted_login_ui.label_error.setText(info) def do_trusted_login_networking(self): self.controller.end_trusted_auth(self.truested_email.encode("utf-8"), self.trusted_password.encode("utf-8")) self.truested_email = None self.trusted_password = None def reset_trusted_login(self): self.trusted_login_ui.line_edit_email.clear() self.trusted_login_ui.line_edit_password.clear() self.trusted_login_ui.label_error.clear() def switch_context(self, view = None): widget = None if view == "trustedlogin": widget = self.trusted_login_widget if view == "manager": widget = self.manager_widget if view == "console": self.console_widget.show() if view == None and self.last_view != None: widget = self.last_view if widget != None: self.last_view = self.stacked_layout.currentWidget() self.stacked_layout.setCurrentWidget(widget) def get_selected_data(self): return self.tree_controller.selected_data # Signal handlers def shut_down(self): self.main_widget.close() def show_console(self): if self.console_widget.isVisible() == False: self.switch_context("console") else: self.hide_console() def hide_console(self): self.console_widget.hide() def save_log_to_file(self): filename = self.datahandler.get_data_dir_path() + "dropn900.log" log_string = str(self.console_ui.text_area.toPlainText()) try: log_file = open(filename, "w") log_file.write(log_string) log_file.close() self.show_banner("Log saved to " + filename) except IOError: self.logger.error("Could not open " + filename + " to save log") def browser_control_clicked(self): if self.controller.connected: self.switch_context() else: self.controller.end_auth() def copy_item_link(self): url = self.tree_controller.current_public_link if url == None: return self.datahandler.copy_url_to_clipboard(url) def open_item_link(self): url = self.tree_controller.current_public_link if url == None: return QDesktopServices.openUrl(QtCore.QUrl(url)) def item_download(self): data = self.get_selected_data() if data == None: return if self.datahandler.dont_show_dl_dialog == False: # This dialog shows sometimes strange stuff on maemo5 # It's a PyQt4 bug and its the best we got, you can cope with this if self.last_dl_location == None: self.last_dl_location = self.datahandler.get_data_dir_path() local_folder_path = QFileDialog.getExistingDirectory(self.manager_widget, QString("Select Download Folder"), QString(self.last_dl_location), QFileDialog.ShowDirsOnly|QFileDialog.HideNameFilterDetails|QFileDialog.ReadOnly) if local_folder_path.isEmpty(): return py_unicode_path = self.datahandler.to_unicode(str(local_folder_path.toUtf8())) self.last_dl_location = py_unicode_path store_path = py_unicode_path + "/" + data.name else: dir_check = QDir(self.datahandler.get_data_dir_path()) if not dir_check.exists(): self.show_note("Cannot download, destination " + self.datahandler.get_data_dir_path() + " does not exist. Please set a new folder in settings.") return store_path = self.datahandler.get_data_dir_path() + data.name self.controller.connection.get_file(data.path, data.root, store_path, data.get_size(), data.mime_type) def item_upload(self): data = self.get_selected_data() if data == None or not data.is_folder(): return # This dialog shows sometimes strange stuff on maemo5 # It's a PyQt4 bug and its the best we got, you can cope with this if self.last_ul_location == None: self.last_ul_location = self.datahandler.get_data_dir_path() local_file_path = QFileDialog.getOpenFileName(self.manager_widget, QString("Select File for Upload"), QString(self.last_ul_location)) if local_file_path.isEmpty(): return py_unicode_path = self.datahandler.to_unicode(str(local_file_path.toUtf8())) self.last_ul_location = py_unicode_path[0:py_unicode_path.rfind("/")] self.controller.connection.upload_file(data.path, data.root, py_unicode_path) def item_rename(self): data = self.get_selected_data() if data == None: return # Get new name from user old_name = data.get_name() keyword = "file" if not data.is_folder() else "folder" new_name, ok = QInputDialog.getText(None, "Renaming " + keyword, "Give new name for " + keyword + " " + old_name, QtGui.QLineEdit.Normal, old_name) if not ok: return # Validate with QString if not self.is_name_valid(new_name, keyword): return # Make QString to python 'unicode' new_name = self.datahandler.to_unicode(str(new_name.toUtf8())) if old_name == new_name: return # Extension will be lost, ask user if he wants to leave it q_old_name = QtCore.QString(old_name) if q_old_name.contains("."): if not new_name.contains("."): format = old_name[q_old_name.lastIndexOf("."):] confirmation = QMessageBox.question(None, "Extension missing", "Do you want to append the original '" + format + "' extensions to the filename '" + new_name + "'?", QMessageBox.Yes, QMessageBox.No) if confirmation == QMessageBox.Yes: new_name.append(format) # Get final new path and rename if data.parent == "/": new_name = data.parent + new_name else: new_name = data.parent + "/" + new_name self.controller.connection.rename(data.root, data.path, new_name, data) def item_remove(self): data = self.get_selected_data() if data == None: return if data.is_folder(): confirmation = QMessageBox.question(None, "Remove folder verification", "Are you sure you want to remove the entire folder " + data.get_name() +"?", QMessageBox.Yes, QMessageBox.Cancel) else: confirmation = QMessageBox.question(None, "Remove file verification", "Are you sure you want to remove " + data.get_name() +"?", QMessageBox.Yes, QMessageBox.Cancel) if confirmation == QMessageBox.Yes: self.controller.connection.remove_file(data.root, data.path, data.parent, data.is_folder()) def item_new_folder(self): data = self.get_selected_data() if data == None: return if not data.is_folder(): return full_create_path = data.path + "/" new_folder_name, ok = QInputDialog.getText(None, "Give new folder name", "") if not ok: return # Validate QString if not self.is_name_valid(new_folder_name, "folder"): return # Make QString to python unicode new_folder_name = self.datahandler.to_unicode(str(new_folder_name.toUtf8())) full_create_path = data.path + "/" + new_folder_name self.controller.connection.create_folder(data.root, full_create_path, new_folder_name, data.path) def is_name_valid(self, name, item_type): if name.isEmpty() or name.isNull(): return False if name.contains("/"): self.show_information_ui("Cant use / in new " + item_type + " name", False) return False if name.contains("\\"): self.show_information_ui("Cant use \ in new " + item_type + " name", False) return False if name.startsWith(" "): self.show_information_ui("New " + item_type + " name cant start with a space", False) return False if name.endsWith(" "): self.show_information_ui("New " + item_type + " name cant end with a space", False) return False return True
class StatusBar(QStatusBar): def __init__(self): QStatusBar.__init__(self) self.editor = None self.widgetStatus = QWidget() vbox = QVBoxLayout(self.widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) #Search Layout hSearch = QHBoxLayout() self.line = TextLine(self) self.line.setMinimumWidth(250) self.checkBackward = QCheckBox('Find Backward') self.checkSensitive = QCheckBox('Respect Case Sensitive') self.checkWholeWord = QCheckBox('Find Whole Words') self.btnClose = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') self.btnFind = QPushButton(QIcon(resources.images['find']), '') self.btnPrevious = QPushButton( self.style().standardIcon(QStyle.SP_ArrowLeft), '') self.btnNext = QPushButton( self.style().standardIcon(QStyle.SP_ArrowRight), '') hSearch.addWidget(self.btnClose) hSearch.addWidget(self.line) hSearch.addWidget(self.btnFind) hSearch.addWidget(self.btnPrevious) hSearch.addWidget(self.btnNext) hSearch.addWidget(self.checkBackward) hSearch.addWidget(self.checkSensitive) hSearch.addWidget(self.checkWholeWord) vbox.addLayout(hSearch) #Replace Layout hReplace = QHBoxLayout() self.lineReplace = TextLine(self) self.lineReplace.setMinimumWidth(250) self.btnCloseReplace = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') self.btnReplace = QPushButton('Replace') self.btnReplaceAll = QPushButton('Replace All') hReplace.addWidget(self.btnCloseReplace) hReplace.addWidget(self.lineReplace) hReplace.addWidget(self.btnReplace) hReplace.addWidget(self.btnReplaceAll) vbox.addLayout(hReplace) self.replace_visibility(False) self.addWidget(self.widgetStatus) self.shortEsc = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(self.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self.btnFind, SIGNAL("clicked()"), self.find) self.connect(self.btnNext, SIGNAL("clicked()"), self.find_next) self.connect(self.btnPrevious, SIGNAL("clicked()"), self.find_previous) self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end) self.connect(self.btnCloseReplace, SIGNAL("clicked()"), lambda: self.replace_visibility(False)) self.connect(self.btnReplace, SIGNAL("clicked()"), self.replace) self.connect(self.btnReplaceAll, SIGNAL("clicked()"), self.replace_all) self.connect(self.shortEsc, SIGNAL("activated()"), self.hide_status) def focus_find(self, editor): self.line.setFocus() self.editor = editor self.line.selectAll() def replace_visibility(self, val): self.lineReplace.setVisible(val) self.btnCloseReplace.setVisible(val) self.btnReplace.setVisible(val) self.btnReplaceAll.setVisible(val) def hide_status(self): self.checkSensitive.setCheckState(Qt.Unchecked) self.checkWholeWord.setCheckState(Qt.Unchecked) self.checkBackward.setCheckState(Qt.Unchecked) self.hide() self.replace_visibility(False) if self.editor is not None: self.editor.setFocus() def replace(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.replace_match(str(self.line.text()), str(self.lineReplace.text()), s, w) def replace_all(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.replace_match(str(self.line.text()), str(self.lineReplace.text()), s, w, True) def find(self): b = False if self.checkBackward.checkState() == Qt.Unchecked else True s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), b, s, w) def find_next(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), False, s, w) def find_previous(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), True, s, w) def showMessage(self, message, timeout): self.widgetStatus.hide() self.replace_visibility(False) self.show() super(StatusBar, self).showMessage(message, timeout) def message_end(self, message): if message == '': self.hide() super(StatusBar, self).clearMessage() self.widgetStatus.show()
def hide(self): QWidget.hide(self)
class _StatusBar(QStatusBar): def __init__(self): super(_StatusBar, self).__init__() self._widgetStatus = QWidget() vbox = QVBoxLayout(self._widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) #Search Layout self._searchWidget = SearchWidget(self) vbox.addWidget(self._searchWidget) #Replace Layout self._replaceWidget = ReplaceWidget(self) vbox.addWidget(self._replaceWidget) self._replaceWidget.setVisible(False) #Code Locator self._codeLocator = locator.CodeLocatorWidget(self) vbox.addWidget(self._codeLocator) self._codeLocator.setVisible(False) #File system completer self._fileSystemOpener = FileSystemOpener() vbox.addWidget(self._fileSystemOpener) self._fileSystemOpener.setVisible(False) self.addWidget(self._widgetStatus) # Not Configurable Shortcuts shortEscStatus = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end) self.connect(self._replaceWidget._btnCloseReplace, SIGNAL("clicked()"), lambda: self._replaceWidget.setVisible(False)) self.connect(self._replaceWidget._btnReplace, SIGNAL("clicked()"), self.replace) self.connect(self._replaceWidget._btnReplaceAll, SIGNAL("clicked()"), self.replace_all) self.connect(self._replaceWidget._btnReplaceSelection, SIGNAL("clicked()"), self.replace_selected) self.connect(self._fileSystemOpener.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self._fileSystemOpener, SIGNAL("requestHide()"), self.hide_status) self.connect(shortEscStatus, SIGNAL("activated()"), self.hide_status) IDE.register_service('status_bar', self) #Register signals connections connections = ( { 'target': 'main_container', 'signal_name': 'currentEditorChanged(QString)', 'slot': self.handle_tab_changed }, { 'target': 'main_container', 'signal_name': 'updateLocator(QString)', 'slot': self.explore_file_code }, { 'target': 'explorer_container', 'signal_name': 'updateLocator()', 'slot': self.explore_code }, ) IDE.register_signals('status_bar', connections) def install(self): self.hide() ide = IDE.get_service('ide') ide.setStatusBar(self) ui_tools.install_shortcuts(self, actions.ACTIONS_STATUS, ide) def find_next_result(self): self._searchWidget.find_next() def find_previous_result(self): self._searchWidget.find_previous() def handle_tab_changed(self, new_tab): """ Re-run search if tab changed, we use the find of search widget because we want the widget to be updated. """ editor = main_container.MainContainer().get_actual_editor() if self._searchWidget.isVisible(): self._searchWidget.find_matches(editor) if editor: self.disconnect(editor, SIGNAL("textChanged()"), self._notify_editor_changed) self.connect(editor, SIGNAL("textChanged()"), self._notify_editor_changed) def _notify_editor_changed(self): """ Lets search widget know that the editor contents changed and find needs to be re-run """ if self._searchWidget.isVisible(): editor = main_container.MainContainer().get_actual_editor() self._searchWidget.contents_changed(editor) def explore_code(self): self._codeLocator.explore_code() def explore_file_code(self, path): self._codeLocator.explore_file_code(path) def show(self): self.clearMessage() QStatusBar.show(self) editor = main_container.MainContainer().get_actual_editor() if editor and editor.textCursor().hasSelection(): text = editor.textCursor().selectedText() self._searchWidget._line.setText(text) self._searchWidget.find_matches(editor, True) if self._widgetStatus.isVisible(): self._searchWidget._line.setFocus() self._searchWidget._line.selectAll() def show_replace(self): self.clearMessage() self.show() editor = main_container.MainContainer().get_actual_editor() if editor: if editor.textCursor().hasSelection(): word = editor.textCursor().selectedText() self._searchWidget._line.setText(word) self._replaceWidget.setVisible(True) def show_with_word(self): self.clearMessage() editor = main_container.MainContainer().get_actual_editor() if editor: word = editor._text_under_cursor() self._searchWidget._line.setText(word) editor = main_container.MainContainer().get_actual_editor() editor.moveCursor(QTextCursor.WordLeft) self._searchWidget.find_matches(editor) self.show() def show_locator(self): if not self._codeLocator.isVisible(): self.clearMessage() self._searchWidget.setVisible(False) self.show() self._codeLocator.setVisible(True) self._codeLocator._completer.setFocus() self._codeLocator.show_suggestions() def show_file_opener(self): self.clearMessage() self._searchWidget.setVisible(False) self._fileSystemOpener.setVisible(True) self.show() self._fileSystemOpener.pathLine.setFocus() def hide_status(self): self._searchWidget._checkSensitive.setCheckState(Qt.Unchecked) self._searchWidget._checkWholeWord.setCheckState(Qt.Unchecked) self.hide() self._searchWidget.setVisible(True) self._replaceWidget.setVisible(False) self._codeLocator.setVisible(False) self._fileSystemOpener.setVisible(False) widget = main_container.MainContainer().get_actual_widget() if widget: widget.setFocus() def replace(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match(self._searchWidget._line.text(), self._replaceWidget._lineReplace.text(), flags) if not editor.textCursor().hasSelection(): self.find() def replace_selected(self): self.replace_all(True) def replace_all(self, selected=False): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.replace_match(self._searchWidget._line.text(), self._replaceWidget._lineReplace.text(), flags, True, selected) def find(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags) def find_next(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 0 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags, True) def find_previous(self): s = 0 if not self._searchWidget._checkSensitive.isChecked() \ else QTextDocument.FindCaseSensitively w = 0 if not self._searchWidget._checkWholeWord.isChecked() \ else QTextDocument.FindWholeWords flags = 1 + s + w editor = main_container.MainContainer().get_actual_editor() if editor: editor.find_match(self._searchWidget._line.text(), flags, True) def showMessage(self, message, timeout): if settings.SHOW_STATUS_NOTIFICATIONS: self._widgetStatus.hide() self._replaceWidget.setVisible(False) self.show() QStatusBar.showMessage(self, message, timeout) def message_end(self, message): if message == '': self.hide() QStatusBar.clearMessage(self) self._widgetStatus.show()
class PythonConsoleWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QSettings() self.shell = ShellScintilla(self) self.setFocusProxy(self.shell) self.shellOut = ShellOutputScintilla(self) self.tabEditorWidget = EditorTabWidget(self) ##------------ UI ------------------------------- self.splitterEditor = QSplitter(self) self.splitterEditor.setOrientation(Qt.Horizontal) self.splitterEditor.setHandleWidth(6) self.splitterEditor.setChildrenCollapsible(True) self.shellOutWidget = QWidget(self) self.shellOutWidget.setLayout(QVBoxLayout()) self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0) self.shellOutWidget.layout().addWidget(self.shellOut) self.splitter = QSplitter(self.splitterEditor) self.splitter.setOrientation(Qt.Vertical) self.splitter.setHandleWidth(3) self.splitter.setChildrenCollapsible(False) self.splitter.addWidget(self.shellOutWidget) self.splitter.addWidget(self.shell) #self.splitterEditor.addWidget(self.tabEditorWidget) self.splitterObj = QSplitter(self.splitterEditor) self.splitterObj.setHandleWidth(3) self.splitterObj.setOrientation(Qt.Horizontal) #self.splitterObj.setSizes([0, 0]) #self.splitterObj.setStretchFactor(0, 1) self.widgetEditor = QWidget(self.splitterObj) self.widgetFind = QWidget(self) self.listClassMethod = QTreeWidget(self.splitterObj) self.listClassMethod.setColumnCount(2) objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector") self.listClassMethod.setHeaderLabels([objInspLabel, '']) self.listClassMethod.setColumnHidden(1, True) self.listClassMethod.setAlternatingRowColors(True) #self.splitterEditor.addWidget(self.widgetEditor) #self.splitterObj.addWidget(self.listClassMethod) #self.splitterObj.addWidget(self.widgetEditor) # Hide side editor on start up self.splitterObj.hide() self.listClassMethod.hide() # Hide search widget on start up self.widgetFind.hide() sizes = self.splitter.sizes() self.splitter.setSizes(sizes) ##----------------Restore Settings------------------------------------ self.restoreSettingsConsole() ##------------------Toolbar Editor------------------------------------- ## Action for Open File openFileBt = QCoreApplication.translate("PythonConsole", "Open file") self.openFileButton = QAction(self) self.openFileButton.setCheckable(False) self.openFileButton.setEnabled(True) self.openFileButton.setIcon(QgsApplication.getThemeIcon("console/iconOpenConsole.png")) self.openFileButton.setMenuRole(QAction.PreferencesRole) self.openFileButton.setIconVisibleInMenu(True) self.openFileButton.setToolTip(openFileBt) self.openFileButton.setText(openFileBt) openExtEditorBt = QCoreApplication.translate("PythonConsole", "Open in external editor") self.openInEditorButton = QAction(self) self.openInEditorButton.setCheckable(False) self.openInEditorButton.setEnabled(True) self.openInEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.openInEditorButton.setMenuRole(QAction.PreferencesRole) self.openInEditorButton.setIconVisibleInMenu(True) self.openInEditorButton.setToolTip(openExtEditorBt) self.openInEditorButton.setText(openExtEditorBt) ## Action for Save File saveFileBt = QCoreApplication.translate("PythonConsole", "Save") self.saveFileButton = QAction(self) self.saveFileButton.setCheckable(False) self.saveFileButton.setEnabled(False) self.saveFileButton.setIcon(QgsApplication.getThemeIcon("console/iconSaveConsole.png")) self.saveFileButton.setMenuRole(QAction.PreferencesRole) self.saveFileButton.setIconVisibleInMenu(True) self.saveFileButton.setToolTip(saveFileBt) self.saveFileButton.setText(saveFileBt) ## Action for Save File As saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...") self.saveAsFileButton = QAction(self) self.saveAsFileButton.setCheckable(False) self.saveAsFileButton.setEnabled(True) self.saveAsFileButton.setIcon(QgsApplication.getThemeIcon("console/iconSaveAsConsole.png")) self.saveAsFileButton.setMenuRole(QAction.PreferencesRole) self.saveAsFileButton.setIconVisibleInMenu(True) self.saveAsFileButton.setToolTip(saveAsFileBt) self.saveAsFileButton.setText(saveAsFileBt) ## Action Cut cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut") self.cutEditorButton = QAction(self) self.cutEditorButton.setCheckable(False) self.cutEditorButton.setEnabled(True) self.cutEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconCutEditorConsole.png")) self.cutEditorButton.setMenuRole(QAction.PreferencesRole) self.cutEditorButton.setIconVisibleInMenu(True) self.cutEditorButton.setToolTip(cutEditorBt) self.cutEditorButton.setText(cutEditorBt) ## Action Copy copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy") self.copyEditorButton = QAction(self) self.copyEditorButton.setCheckable(False) self.copyEditorButton.setEnabled(True) self.copyEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png")) self.copyEditorButton.setMenuRole(QAction.PreferencesRole) self.copyEditorButton.setIconVisibleInMenu(True) self.copyEditorButton.setToolTip(copyEditorBt) self.copyEditorButton.setText(copyEditorBt) ## Action Paste pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste") self.pasteEditorButton = QAction(self) self.pasteEditorButton.setCheckable(False) self.pasteEditorButton.setEnabled(True) self.pasteEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png")) self.pasteEditorButton.setMenuRole(QAction.PreferencesRole) self.pasteEditorButton.setIconVisibleInMenu(True) self.pasteEditorButton.setToolTip(pasteEditorBt) self.pasteEditorButton.setText(pasteEditorBt) ## Action Run Script (subprocess) runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script") self.runScriptEditorButton = QAction(self) self.runScriptEditorButton.setCheckable(False) self.runScriptEditorButton.setEnabled(True) self.runScriptEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconRunScriptConsole.png")) self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole) self.runScriptEditorButton.setIconVisibleInMenu(True) self.runScriptEditorButton.setToolTip(runScriptEditorBt) self.runScriptEditorButton.setText(runScriptEditorBt) ## Action Run Script (subprocess) commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment") self.commentEditorButton = QAction(self) self.commentEditorButton.setCheckable(False) self.commentEditorButton.setEnabled(True) self.commentEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconCommentEditorConsole.png")) self.commentEditorButton.setMenuRole(QAction.PreferencesRole) self.commentEditorButton.setIconVisibleInMenu(True) self.commentEditorButton.setToolTip(commentEditorBt) self.commentEditorButton.setText(commentEditorBt) ## Action Run Script (subprocess) uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment") self.uncommentEditorButton = QAction(self) self.uncommentEditorButton.setCheckable(False) self.uncommentEditorButton.setEnabled(True) self.uncommentEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconUncommentEditorConsole.png")) self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole) self.uncommentEditorButton.setIconVisibleInMenu(True) self.uncommentEditorButton.setToolTip(uncommentEditorBt) self.uncommentEditorButton.setText(uncommentEditorBt) ## Action for Object browser objList = QCoreApplication.translate("PythonConsole", "Object Inspector") self.objectListButton = QAction(self) self.objectListButton.setCheckable(True) self.objectListButton.setEnabled(self.settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.objectListButton.setIcon(QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png")) self.objectListButton.setMenuRole(QAction.PreferencesRole) self.objectListButton.setIconVisibleInMenu(True) self.objectListButton.setToolTip(objList) self.objectListButton.setText(objList) ## Action for Find text findText = QCoreApplication.translate("PythonConsole", "Find Text") self.findTextButton = QAction(self) self.findTextButton.setCheckable(True) self.findTextButton.setEnabled(True) self.findTextButton.setIcon(QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png")) self.findTextButton.setMenuRole(QAction.PreferencesRole) self.findTextButton.setIconVisibleInMenu(True) self.findTextButton.setToolTip(findText) self.findTextButton.setText(findText) ##----------------Toolbar Console------------------------------------- ## Action Show Editor showEditor = QCoreApplication.translate("PythonConsole", "Show editor") self.showEditorButton = QAction(self) self.showEditorButton.setEnabled(True) self.showEditorButton.setCheckable(True) self.showEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.showEditorButton.setMenuRole(QAction.PreferencesRole) self.showEditorButton.setIconVisibleInMenu(True) self.showEditorButton.setToolTip(showEditor) self.showEditorButton.setText(showEditor) ## Action for Clear button clearBt = QCoreApplication.translate("PythonConsole", "Clear console") self.clearButton = QAction(self) self.clearButton.setCheckable(False) self.clearButton.setEnabled(True) self.clearButton.setIcon(QgsApplication.getThemeIcon("console/iconClearConsole.png")) self.clearButton.setMenuRole(QAction.PreferencesRole) self.clearButton.setIconVisibleInMenu(True) self.clearButton.setToolTip(clearBt) self.clearButton.setText(clearBt) ## Action for settings optionsBt = QCoreApplication.translate("PythonConsole", "Settings") self.optionsButton = QAction(self) self.optionsButton.setCheckable(False) self.optionsButton.setEnabled(True) self.optionsButton.setIcon(QgsApplication.getThemeIcon("console/iconSettingsConsole.png")) self.optionsButton.setMenuRole(QAction.PreferencesRole) self.optionsButton.setIconVisibleInMenu(True) self.optionsButton.setToolTip(optionsBt) self.optionsButton.setText(optionsBt) ## Action menu for class actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class") self.actionClass = QAction(self) self.actionClass.setCheckable(False) self.actionClass.setEnabled(True) self.actionClass.setIcon(QgsApplication.getThemeIcon("console/iconClassConsole.png")) self.actionClass.setMenuRole(QAction.PreferencesRole) self.actionClass.setIconVisibleInMenu(True) self.actionClass.setToolTip(actionClassBt) self.actionClass.setText(actionClassBt) ## Import Processing class loadProcessingBt = QCoreApplication.translate("PythonConsole", "Import Processing class") self.loadProcessingButton = QAction(self) self.loadProcessingButton.setCheckable(False) self.loadProcessingButton.setEnabled(True) self.loadProcessingButton.setIcon(QgsApplication.getThemeIcon("console/iconProcessingConsole.png")) self.loadProcessingButton.setMenuRole(QAction.PreferencesRole) self.loadProcessingButton.setIconVisibleInMenu(True) self.loadProcessingButton.setToolTip(loadProcessingBt) self.loadProcessingButton.setText(loadProcessingBt) ## Import QtCore class loadQtCoreBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore class") self.loadQtCoreButton = QAction(self) self.loadQtCoreButton.setCheckable(False) self.loadQtCoreButton.setEnabled(True) self.loadQtCoreButton.setIcon(QgsApplication.getThemeIcon("console/iconQtCoreConsole.png")) self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole) self.loadQtCoreButton.setIconVisibleInMenu(True) self.loadQtCoreButton.setToolTip(loadQtCoreBt) self.loadQtCoreButton.setText(loadQtCoreBt) ## Import QtGui class loadQtGuiBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui class") self.loadQtGuiButton = QAction(self) self.loadQtGuiButton.setCheckable(False) self.loadQtGuiButton.setEnabled(True) self.loadQtGuiButton.setIcon(QgsApplication.getThemeIcon("console/iconQtGuiConsole.png")) self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole) self.loadQtGuiButton.setIconVisibleInMenu(True) self.loadQtGuiButton.setToolTip(loadQtGuiBt) self.loadQtGuiButton.setText(loadQtGuiBt) ## Action for Run script runBt = QCoreApplication.translate("PythonConsole", "Run command") self.runButton = QAction(self) self.runButton.setCheckable(False) self.runButton.setEnabled(True) self.runButton.setIcon(QgsApplication.getThemeIcon("console/iconRunConsole.png")) self.runButton.setMenuRole(QAction.PreferencesRole) self.runButton.setIconVisibleInMenu(True) self.runButton.setToolTip(runBt) self.runButton.setText(runBt) ## Help action helpBt = QCoreApplication.translate("PythonConsole", "Help") self.helpButton = QAction(self) self.helpButton.setCheckable(False) self.helpButton.setEnabled(True) self.helpButton.setIcon(QgsApplication.getThemeIcon("console/iconHelpConsole.png")) self.helpButton.setMenuRole(QAction.PreferencesRole) self.helpButton.setIconVisibleInMenu(True) self.helpButton.setToolTip(helpBt) self.helpButton.setText(helpBt) self.toolBar = QToolBar() self.toolBar.setEnabled(True) self.toolBar.setFocusPolicy(Qt.NoFocus) self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBar.setLayoutDirection(Qt.LeftToRight) self.toolBar.setIconSize(QSize(16, 16)) self.toolBar.setMovable(False) self.toolBar.setFloatable(False) self.toolBar.addAction(self.clearButton) self.toolBar.addAction(self.actionClass) self.toolBar.addAction(self.runButton) self.toolBar.addSeparator() self.toolBar.addAction(self.showEditorButton) self.toolBar.addSeparator() self.toolBar.addAction(self.optionsButton) self.toolBar.addAction(self.helpButton) self.toolBarEditor = QToolBar() self.toolBarEditor.setEnabled(False) self.toolBarEditor.setFocusPolicy(Qt.NoFocus) self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBarEditor.setLayoutDirection(Qt.LeftToRight) self.toolBarEditor.setIconSize(QSize(16, 16)) self.toolBarEditor.setMovable(False) self.toolBarEditor.setFloatable(False) self.toolBarEditor.addAction(self.openFileButton) self.toolBarEditor.addAction(self.openInEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.saveFileButton) self.toolBarEditor.addAction(self.saveAsFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.runScriptEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.findTextButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.cutEditorButton) self.toolBarEditor.addAction(self.copyEditorButton) self.toolBarEditor.addAction(self.pasteEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.commentEditorButton) self.toolBarEditor.addAction(self.uncommentEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.objectListButton) ## Menu Import Class self.classMenu = QMenu() self.classMenu.addAction(self.loadProcessingButton) self.classMenu.addAction(self.loadQtCoreButton) self.classMenu.addAction(self.loadQtGuiButton) cM = self.toolBar.widgetForAction(self.actionClass) cM.setMenu(self.classMenu) cM.setPopupMode(QToolButton.InstantPopup) self.widgetButton = QWidget() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.widgetButton.sizePolicy().hasHeightForWidth()) self.widgetButton.setSizePolicy(sizePolicy) self.widgetButtonEditor = QWidget(self.widgetEditor) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.widgetButtonEditor.sizePolicy().hasHeightForWidth()) self.widgetButtonEditor.setSizePolicy(sizePolicy) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.shellOut.sizePolicy().hasHeightForWidth()) self.shellOut.setSizePolicy(sizePolicy) self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) ##------------ Layout ------------------------------- self.mainLayout = QGridLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1) self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1) self.shellOutWidget.layout().insertWidget(0, self.toolBar) self.layoutEditor = QGridLayout(self.widgetEditor) self.layoutEditor.setMargin(0) self.layoutEditor.setSpacing(0) self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1) self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1) self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1) self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1) ## Layout for the find widget self.layoutFind = QGridLayout(self.widgetFind) self.layoutFind.setContentsMargins(0, 0, 0, 0) self.lineEditFind = QgsFilterLineEdit() placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find...") if pyqtconfig.Configuration().qt_version >= 0x40700: self.lineEditFind.setPlaceholderText(placeHolderTxt) else: self.lineEditFind.setToolTip(placeHolderTxt) self.findNextButton = QToolButton() self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon(QgsApplication.getThemeIcon("console/iconSearchNextEditorConsole.png")) self.findNextButton.setIconSize(QSize(24, 24)) self.findNextButton.setAutoRaise(True) self.findPrevButton = QToolButton() self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon(QgsApplication.getThemeIcon("console/iconSearchPrevEditorConsole.png")) self.findPrevButton.setIconSize(QSize(24, 24)) self.findPrevButton.setAutoRaise(True) self.caseSensitive = QCheckBox() caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive") self.caseSensitive.setText(caseSensTr) self.wholeWord = QCheckBox() wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word") self.wholeWord.setText(wholeWordTr) self.wrapAround = QCheckBox() self.wrapAround.setChecked(True) wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around") self.wrapAround.setText(wrapAroundTr) self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1) self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1) self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1) self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1) self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1) self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1) ##------------ Add first Tab in Editor ------------------------------- #self.tabEditorWidget.newTabEditor(tabName='first', filename=None) ##------------ Signal ------------------------------- self.findTextButton.toggled.connect(self.findTextEditor) self.objectListButton.toggled.connect(self.toggleObjectListWidget) self.commentEditorButton.triggered.connect(self.commentCode) self.uncommentEditorButton.triggered.connect(self.uncommentCode) self.runScriptEditorButton.triggered.connect(self.runScriptEditor) self.cutEditorButton.triggered.connect(self.cutEditor) self.copyEditorButton.triggered.connect(self.copyEditor) self.pasteEditorButton.triggered.connect(self.pasteEditor) self.showEditorButton.toggled.connect(self.toggleEditor) self.clearButton.triggered.connect(self.shellOut.clearConsole) self.optionsButton.triggered.connect(self.openSettings) self.loadProcessingButton.triggered.connect(self.processing) self.loadQtCoreButton.triggered.connect(self.qtCore) self.loadQtGuiButton.triggered.connect(self.qtGui) self.runButton.triggered.connect(self.shell.entered) self.openFileButton.triggered.connect(self.openScriptFile) self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor) self.saveFileButton.triggered.connect(self.saveScriptFile) self.saveAsFileButton.triggered.connect(self.saveAsScriptFile) self.helpButton.triggered.connect(self.openHelp) self.connect(self.listClassMethod, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.onClickGoToLine) self.lineEditFind.returnPressed.connect(self._findText) self.findNextButton.clicked.connect(self._findNext) self.findPrevButton.clicked.connect(self._findPrev) self.lineEditFind.textChanged.connect(self._textFindChanged) def _findText(self): self.tabEditorWidget.currentWidget().newEditor.findText(True) def _findNext(self): self.tabEditorWidget.currentWidget().newEditor.findText(True) def _findPrev(self): self.tabEditorWidget.currentWidget().newEditor.findText(False) def _textFindChanged(self): if self.lineEditFind.text(): self.findNextButton.setEnabled(True) self.findPrevButton.setEnabled(True) else: self.lineEditFind.setStyleSheet('') self.findNextButton.setEnabled(False) self.findPrevButton.setEnabled(False) def onClickGoToLine(self, item, column): tabEditor = self.tabEditorWidget.currentWidget().newEditor if item.text(1) == 'syntaxError': check = tabEditor.syntaxCheck(fromContextMenu=False) if check and not tabEditor.isReadOnly(): self.tabEditorWidget.currentWidget().save() return linenr = int(item.text(1)) itemName = str(item.text(0)) charPos = itemName.find(' ') if charPos != -1: objName = itemName[0:charPos] else: objName = itemName tabEditor.goToLine(objName, linenr) def processing(self): self.shell.commandConsole('processing') def qtCore(self): self.shell.commandConsole('qtCore') def qtGui(self): self.shell.commandConsole('qtGui') def toggleEditor(self, checked): self.splitterObj.show() if checked else self.splitterObj.hide() if not self.tabEditorWidget: self.tabEditorWidget.enableToolBarEditor(checked) self.tabEditorWidget.restoreTabsOrAddNew() def toggleObjectListWidget(self, checked): self.listClassMethod.show() if checked else self.listClassMethod.hide() def findTextEditor(self, checked): self.widgetFind.show() if checked else self.widgetFind.hide() def pasteEditor(self): self.tabEditorWidget.currentWidget().newEditor.paste() def cutEditor(self): self.tabEditorWidget.currentWidget().newEditor.cut() def copyEditor(self): self.tabEditorWidget.currentWidget().newEditor.copy() def runScriptEditor(self): self.tabEditorWidget.currentWidget().newEditor.runScriptCode() def commentCode(self): self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(True) def uncommentCode(self): self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(False) def openScriptFileExtEditor(self): tabWidget = self.tabEditorWidget.currentWidget() path = tabWidget.path import subprocess try: subprocess.Popen([os.environ['EDITOR'], path]) except KeyError: QDesktopServices.openUrl(QUrl.fromLocalFile(path)) def openScriptFile(self): lastDirPath = self.settings.value("pythonConsole/lastDirPath", QDir.homePath()) openFileTr = QCoreApplication.translate("PythonConsole", "Open File") fileList = QFileDialog.getOpenFileNames( self, openFileTr, lastDirPath, "Script file (*.py)") if fileList: for pyFile in fileList: for i in range(self.tabEditorWidget.count()): tabWidget = self.tabEditorWidget.widget(i) if tabWidget.path == pyFile: self.tabEditorWidget.setCurrentWidget(tabWidget) break else: tabName = QFileInfo(pyFile).fileName() self.tabEditorWidget.newTabEditor(tabName, pyFile) lastDirPath = QFileInfo(pyFile).path() self.settings.setValue("pythonConsole/lastDirPath", pyFile) self.updateTabListScript(pyFile, action='append') def saveScriptFile(self): tabWidget = self.tabEditorWidget.currentWidget() try: tabWidget.save() except (IOError, OSError) as error: msgText = QCoreApplication.translate('PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) def saveAsScriptFile(self, index=None): tabWidget = self.tabEditorWidget.currentWidget() if not index: index = self.tabEditorWidget.currentIndex() if not tabWidget.path: fileName = self.tabEditorWidget.tabText(index) + '.py' folder = self.settings.value("pythonConsole/lastDirPath", QDir.home()) pathFileName = os.path.join(folder, fileName) fileNone = True else: pathFileName = tabWidget.path fileNone = False saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As") filename = QFileDialog.getSaveFileName(self, saveAsFileTr, pathFileName, "Script file (*.py)") if filename: try: tabWidget.save(filename) except (IOError, OSError) as error: msgText = QCoreApplication.translate('PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) if fileNone: tabWidget.path = None else: tabWidget.path = pathFileName return if not fileNone: self.updateTabListScript(pathFileName, action='remove') def openHelp(self): QgsContextHelp.run("PythonConsole") def openSettings(self): if optionsDialog(self).exec_(): self.shell.refreshSettingsShell() self.shellOut.refreshSettingsOutput() self.tabEditorWidget.refreshSettingsEditor() def callWidgetMessageBar(self, text): self.shellOut.widgetMessageBar(iface, text) def callWidgetMessageBarEditor(self, text, level, timed): self.tabEditorWidget.widgetMessageBar(iface, text, level, timed) def updateTabListScript(self, script, action=None): if action == 'remove': self.tabListScript.remove(script) elif action == 'append': if not self.tabListScript: self.tabListScript = [] if script not in self.tabListScript: self.tabListScript.append(script) else: self.tabListScript = [] self.settings.setValue("pythonConsole/tabScripts", self.tabListScript) def saveSettingsConsole(self): self.settings.setValue("pythonConsole/splitterConsole", self.splitter.saveState()) self.settings.setValue("pythonConsole/splitterObj", self.splitterObj.saveState()) self.settings.setValue("pythonConsole/splitterEditor", self.splitterEditor.saveState()) self.shell.writeHistoryFile(True) def restoreSettingsConsole(self): storedTabScripts = self.settings.value("pythonConsole/tabScripts", []) self.tabListScript = storedTabScripts self.splitter.restoreState(self.settings.value("pythonConsole/splitterConsole", QByteArray())) self.splitterEditor.restoreState(self.settings.value("pythonConsole/splitterEditor", QByteArray())) self.splitterObj.restoreState(self.settings.value("pythonConsole/splitterObj", QByteArray()))
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.dirty = False self.isLoaded = False self.calibration_enabled = False self.aggregate_enabled = False self.setObjectName("MainWindow") self.resize(800, 600) self.setWindowTitle("OpenFisca") app_icon = get_icon('OpenFisca22.png') self.setWindowIcon(app_icon) self.setLocale(QLocale(QLocale.French, QLocale.France)) self.setDockOptions(QMainWindow.AllowNestedDocks | QMainWindow.AllowTabbedDocks | QMainWindow.AnimatedDocks) self.centralwidget = QWidget(self) self.gridLayout = QGridLayout(self.centralwidget) self.setCentralWidget(self.centralwidget) self.centralwidget.hide() self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) # Showing splash screen pixmap = QPixmap(':/images/splash.png', 'png') self.splash = QSplashScreen(pixmap) font = self.splash.font() font.setPixelSize(10) self.splash.setFont(font) self.splash.show() self.splash.showMessage( "Initialisation...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # if CONF.get('main', 'current_version', '') != __version__: # CONF.set('main', 'current_version', __version__) # Execute here the actions to be performed only once after # each update (there is nothing there for now, but it could # be useful some day... self.scenario = Scenario() # Preferences self.general_prefs = [SimConfigPage, PathConfigPage, CalConfigPage] self.oldXAXIS = 'sal' self.reforme = False self.apply_settings() # Dockwidgets creation self.splash.showMessage( "Creating widgets...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.create_dockwidgets() self.populate_mainwidow() ################################################################# ## Menu initialization ################################################################# self.splash.showMessage( "Creating menubar...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) # Menu Fichier self.file_menu = self.menuBar().addMenu("Fichier") action_export_png = create_action(self, 'Exporter le graphique', icon='document-save png.png', triggered=self._graph.save_figure) action_export_csv = create_action(self, 'Exporter la table', icon='document-save csv.png', triggered=self._table.saveCsv) action_pref = create_action(self, u'Préférences', QKeySequence.Preferences, icon='preferences-desktop.png', triggered=self.edit_preferences) action_quit = create_action(self, 'Quitter', QKeySequence.Quit, icon='process-stop.png', triggered=SLOT('close()')) file_actions = [ action_export_png, action_export_csv, None, action_pref, None, action_quit ] add_actions(self.file_menu, file_actions) # Menu Edit self.edit_menu = self.menuBar().addMenu(u"Édition") action_copy = create_action(self, 'Copier', QKeySequence.Copy, triggered=self.global_callback, data='copy') edit_actions = [None, action_copy] add_actions(self.edit_menu, edit_actions) # Menu Simulation self.simulation_menu = self.menuBar().addMenu(u"Simulation") self.action_refresh_bareme = create_action( self, u'Calculer barèmes', shortcut='F9', icon='calculator_green.png', triggered=self.refresh_bareme) self.action_refresh_aggregate = create_action( self, u'Calculer aggrégats', shortcut='F10', icon='calculator_blue.png', triggered=self.refresh_aggregate) self.action_calibrate = create_action(self, u'Caler les poids', shortcut='CTRL+K', icon='scale22.png', triggered=self.calibrate) action_bareme = create_action(self, u'Barème', icon='bareme22.png', toggled=self.modeBareme) action_cas_type = create_action(self, u'Cas type', icon='castype22.png', toggled=self.modeCasType) action_mode_reforme = create_action( self, u'Réforme', icon='comparison22.png', toggled=self.modeReforme, tip= u"Différence entre la situation simulée et la situation actuelle") mode_group = QActionGroup(self) mode_group.addAction(action_bareme) mode_group.addAction(action_cas_type) self.mode = 'bareme' action_bareme.trigger() simulation_actions = [ self.action_refresh_bareme, self.action_refresh_aggregate, None, self.action_calibrate, None, action_bareme, action_cas_type, None, action_mode_reforme ] add_actions(self.simulation_menu, simulation_actions) # Menu Help help_menu = self.menuBar().addMenu("&Aide") action_about = create_action(self, u"&About OpenFisca", triggered=self.helpAbout) action_help = create_action(self, "&Aide", QKeySequence.HelpContents, triggered=self.helpHelp) help_actions = [action_about, action_help] add_actions(help_menu, help_actions) # Display Menu view_menu = self.createPopupMenu() view_menu.setTitle("&Affichage") self.menuBar().insertMenu(help_menu.menuAction(), view_menu) # Toolbar self.main_toolbar = self.create_toolbar(u"Barre d'outil", 'main_toolbar') toolbar_actions = [ action_export_png, action_export_csv, None, self.action_refresh_bareme, self.action_refresh_aggregate, None, self.action_calibrate, None, action_bareme, action_cas_type, None, action_mode_reforme ] add_actions(self.main_toolbar, toolbar_actions) self.connect(self._menage, SIGNAL('changed()'), self.changed_bareme) self.connect(self._parametres, SIGNAL('changed()'), self.changed_param) self.connect(self._aggregate_output, SIGNAL('calculated()'), self.calculated) self.connect(self, SIGNAL('weights_changed()'), self.refresh_aggregate) self.connect(self, SIGNAL('bareme_only()'), self.switch_bareme_only) # Window settings self.splash.showMessage( "Restoring settings...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) settings = QSettings() size = settings.value('MainWindow/Size', QVariant(QSize(800, 600))).toSize() self.resize(size) position = settings.value('MainWindow/Position', QVariant(QPoint(0, 0))).toPoint() self.move(position) self.restoreState(settings.value("MainWindow/State").toByteArray()) self.splash.showMessage( "Loading survey data...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) self.enable_aggregate(True) self.refresh_bareme() self.isLoaded = True self.splash.hide() def create_toolbar(self, title, object_name, iconsize=24): toolbar = self.addToolBar(title) toolbar.setObjectName(object_name) toolbar.setIconSize(QSize(iconsize, iconsize)) return toolbar def create_dockwidgets(self): # Création des dockwidgets self._parametres = ParamWidget('data/param.xml', self) self._menage = ScenarioWidget(self.scenario, self) self._graph = Graph(self) self._table = OutTable(self) self._aggregate_output = AggregateOutputWidget(self) self._dataframe_widget = ExploreDataWidget(self) def populate_mainwidow(self): ''' Creates all dockwidgets ''' self.addDockWidget(Qt.RightDockWidgetArea, self._parametres) self.addDockWidget(Qt.RightDockWidgetArea, self._menage) self.addDockWidget(Qt.LeftDockWidgetArea, self._graph) self.addDockWidget(Qt.LeftDockWidgetArea, self._table) self.addDockWidget(Qt.LeftDockWidgetArea, self._aggregate_output) self.addDockWidget(Qt.LeftDockWidgetArea, self._dataframe_widget) self.tabifyDockWidget(self._dataframe_widget, self._aggregate_output) self.tabifyDockWidget(self._aggregate_output, self._table) self.tabifyDockWidget(self._table, self._graph) def global_callback(self): """Global callback""" widget = QApplication.focusWidget() action = self.sender() callback = unicode(action.data().toString()) if hasattr(widget, callback): getattr(widget, callback)() def load_survey_data(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: # liberate some memory before loading new data self.reset_aggregate() gc.collect() fname = CONF.get('paths', 'survey_data/file') self.survey = DataTable(InputTable, survey_data=fname) self._dataframe_widget.set_dataframe(self.survey.table) return True except Exception, e: self.aggregate_enabled = False QMessageBox.warning( self, u"Impossible de lire les données", u"OpenFisca n'a pas réussi à lire les données d'enquête et passe en mode barème. L'erreur suivante a été renvoyé:\n%s\n\nVous pouvez charger des nouvelles données d'enquête dans Fichier>Paramètres>Chemins>Données d'enquête" % e) self.emit(SIGNAL('baremeOnly()')) return False finally: