def onLanguageChange(self): languageName = self._langBox.currentText() if iep.config.settings.language == languageName: return # Save new language iep.config.settings.language = languageName setLanguage(iep.config.settings.language) # Notify user text = translate( 'wizard', """ The language has been changed for this wizard. IEP needs to restart for the change to take effect application-wide. """) m = QtGui.QMessageBox(self) m.setWindowTitle(translate("wizard", "Language changed")) m.setText(text) m.setIcon(m.Information) m.exec_() # Get props of current wizard geo = self.wizard().geometry() parent = self.wizard().parent() # Close ourself! self.wizard().close() # Start new one w = IEPWizard(parent) w.setGeometry(geo) w.show()
def onMenuTriggered(self, action): d = self.currentDict() if not d: return if action._id == 'remove': # Remove this project self.parent().removeStarredDir(d.path) elif action._id == 'name': # Open dialog to ask for name name = QtGui.QInputDialog.getText( self.parent(), translate('filebrowser', 'Project name'), translate('filebrowser', 'New project name:'), text=d['name'], ) if isinstance(name, tuple): name = name[0] if name[1] else '' if name: d['name'] = name self.updateProjectList() elif action._id == 'pythonpath': # Flip add-to-pythonpath flag d['addToPythonpath'] = not d['addToPythonpath']
def _duplicateOrRename(self, rename): # Get dirname and filename dirname, filename = os.path.split(self._item.path()) # Get title and label if rename: title = translate("filebrowser", "Rename") label = translate("filebrowser", "Give the new name for the file") else: title = translate("filebrowser", "Duplicate") label = translate("filebrowser", "Give the name for the new file") filename = 'Copy of ' + filename # Ask for new filename s = QtGui.QInputDialog.getText(self.parent(), title, label + ':\n%s' % self._item.path(), QtGui.QLineEdit.Normal, filename ) if isinstance(s, tuple): s = s[0] if s[1] else '' # Push rename task if s: newpath = os.path.join(dirname, s) task = tasks.RenameTask(newpath=newpath, removeold=rename) self._item._proxy.pushTask(task)
def onLanguageChange(self): languageName = self._langBox.currentText() if iep.config.settings.language == languageName: return # Save new language iep.config.settings.language = languageName setLanguage(iep.config.settings.language) # Notify user text = translate('wizard', """ The language has been changed for this wizard. IEP needs to restart for the change to take effect application-wide. """) m = QtGui.QMessageBox(self) m.setWindowTitle(translate("wizard", "Language changed")) m.setText(text) m.setIcon(m.Information) m.exec_() # Get props of current wizard geo = self.wizard().geometry() parent = self.wizard().parent() # Close ourself! self.wizard().close() # Start new one w = IEPWizard(parent) w.setGeometry(geo) w.show()
def buildMenu(self): menu = self._menu menu.clear() # Add action to remove bookmark action = menu.addAction(translate('filebrowser', 'Remove project')) action._id = 'remove' action.setCheckable(False) # Add action to change name action = menu.addAction(translate('filebrowser', 'Change project name')) action._id = 'name' action.setCheckable(False) menu.addSeparator() # Add check action for adding to Pythonpath action = menu.addAction( translate('filebrowser', 'Add path to Python path')) action._id = 'pythonpath' action.setCheckable(True) d = self.currentDict() if d: checked = bool(d and d['addToPythonpath']) action.setChecked(checked)
def buildMenu(self): menu = self._menu menu.clear() # Add action to remove bookmark action = menu.addAction(translate("filebrowser", "Remove project")) action._id = "remove" action.setCheckable(False) # Add action to change name action = menu.addAction(translate("filebrowser", "Change project name")) action._id = "name" action.setCheckable(False) menu.addSeparator() # Add check action for adding to Pythonpath action = menu.addAction(translate("filebrowser", "Add path to Python path")) action._id = "pythonpath" action.setCheckable(True) d = self.currentDict() if d: checked = bool(d and d["addToPythonpath"]) action.setChecked(checked) # Add action to cd to the project directory action = menu.addAction(translate("filebrowser", "Go to this directory in the current shell")) action._id = "cd" action.setCheckable(False)
def __init__(self): QtGui.QWizardPage.__init__(self) self.setTitle(translate('importwizard', 'Select file')) self.txtFilename = QtGui.QLineEdit() self.btnBrowse = QtGui.QPushButton(translate('importwizard', 'Browse...')) self.preview = QtGui.QPlainTextEdit() self.preview.setReadOnly(True) vlayout = QtGui.QVBoxLayout() hlayout = QtGui.QHBoxLayout() hlayout.addWidget(self.txtFilename) hlayout.addWidget(self.btnBrowse) vlayout.addLayout(hlayout) vlayout.addWidget(QtGui.QLabel(translate('importwizard', 'Preview:'))) vlayout.addWidget(self.preview) self.setLayout(vlayout) self.registerField('fname', self.txtFilename) self.btnBrowse.clicked.connect(self.onBrowseClicked) self.txtFilename.editingFinished.connect(self.updatePreview) self._isComplete = False
def __init__(self, parent): QtGui.QDialog.__init__(self, parent) self.setWindowTitle(iep.translate("menu dialog", "Manage IEP license keys")) self.resize(500,500) # Create button to add license key self._addbut = QtGui.QPushButton( iep.translate("menu dialog", "Add license key") ) self._addbut.clicked.connect(self.addLicenseKey) # Create label with link to website self._linkLabel = QtGui.QLabel(self) self._linkLabel.setTextFormat(QtCore.Qt.RichText) self._linkLabel.setOpenExternalLinks(True) self._linkLabel.setText("You can purchase a license at " + "<a href='http://iep-project.org/contributing.html'>http://iep-project.org</a>") self._linkLabel.setVisible(False) # Create label to show license info self._label = QtGui.QTextEdit(self) self._label.setLineWrapMode(self._label.WidgetWidth) self._label.setReadOnly(True) # Layout layout = QtGui.QVBoxLayout(self) self.setLayout(layout) layout.addWidget(self._addbut) layout.addWidget(self._linkLabel) layout.addWidget(self._label) # Init self.showLicenses()
def onMenuTriggered(self, action): d = self.currentDict() if not d: return if action._id == "remove": # Remove this project self.parent().removeStarredDir(d.path) elif action._id == "name": # Open dialog to ask for name name = QtGui.QInputDialog.getText( self.parent(), translate("filebrowser", "Project name"), translate("filebrowser", "New project name:"), text=d["name"], ) if isinstance(name, tuple): name = name[0] if name[1] else "" if name: d["name"] = name self.updateProjectList() elif action._id == "pythonpath": # Flip add-to-pythonpath flag d["addToPythonpath"] = not d["addToPythonpath"] elif action._id == "cd": # cd to the directory shell = iep.shells.getCurrentShell() if shell: shell.executeCommand("cd " + d.path + "\n")
def onMenuTriggered(self, action): d = self.currentDict() if not d: return if action._id == 'remove': # Remove this project self.parent().removeStarredDir(d.path) elif action._id == 'name': # Open dialog to ask for name name = QtGui.QInputDialog.getText(self.parent(), translate('filebrowser', 'Project name'), translate('filebrowser', 'New project name:'), text=d['name'], ) if isinstance(name, tuple): name = name[0] if name[1] else '' if name: d['name'] = name self.updateProjectList() elif action._id == 'pythonpath': # Flip add-to-pythonpath flag d['addToPythonpath'] = not d['addToPythonpath']
def onBtnExecuteClicked(self): shell = iep.shells.getCurrentShell() if shell is None: QtGui.QMessageBox.information(self, translate('importwizard', 'Import data wizard'), translate('importwizard', 'No current shell active')) return shell.executeCode(self.getCode(), 'importwizard')
class FinalPage(BaseIEPWizardPage): _title = translate('wizard', 'Get coding!') _image_filename = 'ieplogo128.png' _descriptions = [ translate( 'wizard', """This concludes the IEP wizard. Now, get coding and have fun!""" ), ]
class TwocomponentsWizardPage(BaseIEPWizardPage): _title = translate('wizard', 'IEP consists of two main components') _image_filename = 'iep_two_components.png' _descriptions = [ translate('wizard', "You can execute commands directly in the *shell*,"), translate('wizard', "or you can write code in the *editor* and execute that."), ]
def onDelete(self): # Ask for new filename b = QtGui.QMessageBox.question(self.parent(), translate("filebrowser", "Delete"), translate("filebrowser", "Are you sure that you want to delete") + ':\n%s' % self._item.path(), QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel, ) # Push delete task if b is QtGui.QMessageBox.Yes: self._item._proxy.pushTask(tasks.RemoveTask())
def open(self, filename): if self.isVisible(): QtGui.QMessageBox.information(self, translate('importwizard', 'Import data wizard'), translate('importwizard', 'The import data wizard is already open')) return self.restart() self.selectFilePage.txtFilename.setText(filename) self.selectFilePage.updatePreview() self.show()
def __init__(self, parent, config, path=None): QtGui.QWidget.__init__(self, parent) # Store config self.config = config # Create star button self._projects = Projects(self) # Create path input/display lineEdit self._pathEdit = PathInput(self) # Create file system proxy self._fsProxy = proxies.NativeFSProxy() self.destroyed.connect(self._fsProxy.stop) # Create tree widget self._tree = Tree(self) self._tree.setPath(Path(self.config.path)) # Create name filter self._nameFilter = NameFilter(self) #self._nameFilter.lineEdit().setToolTip('File filter pattern') self._nameFilter.setToolTip(translate('filebrowser', 'Filename filter')) self._nameFilter.setPlaceholderText(self._nameFilter.toolTip()) # Create search filter self._searchFilter = SearchFilter(self) self._searchFilter.setToolTip( translate('filebrowser', 'Search in files')) self._searchFilter.setPlaceholderText(self._searchFilter.toolTip()) # Signals to sync path. # Widgets that can change the path transmit signal to _tree self._pathEdit.dirUp.connect(self._tree.setFocus) self._pathEdit.dirUp.connect(self._tree.setPathUp) self._pathEdit.dirChanged.connect(self._tree.setPath) self._projects.dirChanged.connect(self._tree.setPath) # self._nameFilter.filterChanged.connect( self._tree.onChanged) # == update self._searchFilter.filterChanged.connect(self._tree.onChanged) # The tree transmits signals to widgets that need to know the path self._tree.dirChanged.connect(self._pathEdit.setPath) self._tree.dirChanged.connect(self._projects.setPath) self._layout() # Set and sync path ... if path is not None: self._tree.SetPath(path) self._tree.dirChanged.emit(self._tree.path())
def build(self): #TODO: implement 'open outside iep' on linux if sys.platform == 'darwin': self.addItem(translate("projectmanager", "Open outside iep"), None, self._openOutsideMac) self.addItem(translate("projectmanager", "Reveal in Finder"), None, self._showInFinder) if sys.platform.startswith('win'): self.addItem(translate("projectmanager", "Open outside iep"), None, self._openOutsideWin) self.addItem(translate("projectmanager", "Copy path"), None, self._copyPath)
def __init__(self, parent, config, path=None): QtGui.QWidget.__init__(self, parent) # Store config self.config = config # Create star button self._projects = Projects(self) # Create path input/display lineEdit self._pathEdit = PathInput(self) # Create file system proxy self._fsProxy = proxies.NativeFSProxy() self.destroyed.connect(self._fsProxy.stop) # Create tree widget self._tree = Tree(self) self._tree.setPath(Path(self.config.path)) # Create name filter self._nameFilter = NameFilter(self) #self._nameFilter.lineEdit().setToolTip('File filter pattern') self._nameFilter.setToolTip(translate('filebrowser', 'Filename filter')) self._nameFilter.setPlaceholderText(self._nameFilter.toolTip()) # Create search filter self._searchFilter = SearchFilter(self) self._searchFilter.setToolTip(translate('filebrowser', 'Search in files')) self._searchFilter.setPlaceholderText(self._searchFilter.toolTip()) # Signals to sync path. # Widgets that can change the path transmit signal to _tree self._pathEdit.dirUp.connect(self._tree.setFocus) self._pathEdit.dirUp.connect(self._tree.setPathUp) self._pathEdit.dirChanged.connect(self._tree.setPath) self._projects.dirChanged.connect(self._tree.setPath) # self._nameFilter.filterChanged.connect(self._tree.onChanged) # == update self._searchFilter.filterChanged.connect(self._tree.onChanged) # The tree transmits signals to widgets that need to know the path self._tree.dirChanged.connect(self._pathEdit.setPath) self._tree.dirChanged.connect(self._projects.setPath) self._layout() # Set and sync path ... if path is not None: self._tree.SetPath(path) self._tree.dirChanged.emit(self._tree.path())
def __init__(self, parent): # Do not pass parent, because is a sublayout QtGui.QVBoxLayout.__init__(self) # Create sub-widget self._edit1 = QtGui.QLineEdit(parent) self._edit1.textEdited.connect(self.onEditChanged) if sys.platform.startswith('win'): self._edit1.setPlaceholderText('C:\\path\\to\\script.py') else: self._edit1.setPlaceholderText('/path/to/script.py') # self._edit2 = QtGui.QTextEdit(parent) self._edit2.zoomOut(1) self._edit2.setMaximumHeight(80) self._edit2.setMinimumWidth(200) self._edit2.textChanged.connect(self.onEditChanged) # Layout self.setSpacing(1) self.addWidget(self._edit1) self.addWidget(self._edit2) # Create radio widget for system default t = translate('shell', 'Use system default') self._radio_system = QtGui.QRadioButton(t, parent) self._radio_system.toggled.connect(self.onCheckChanged) self.addWidget(self._radio_system) if self.DISABLE_SYSTEM_DEFAULT: self._radio_system.hide() # Create radio widget for file t = translate('shell', 'File to run at startup') self._radio_file = QtGui.QRadioButton(t, parent) self._radio_file.toggled.connect(self.onCheckChanged) self.addWidget(self._radio_file) # Create radio widget for code t = translate('shell', 'Code to run at startup') self._radio_code = QtGui.QRadioButton(t, parent) self._radio_code.toggled.connect(self.onCheckChanged) self.addWidget(self._radio_code) # The actual value of this shell config attribute self._value = '' # A buffered version, so that clicking the text box does not # remove the value at once self._valueFile = '' self._valueCode = '\n'
def updateProjectList(self): # Get sorted version of starredDirs starredDirs = self.parent().starredDirs starredDirs.sort(key=lambda p: p.lower()) # Refill the combo box self._combo.clear() for p in starredDirs: name = self.parent().dictForStarredDir(p).name self._combo.addItem(name, p) # Insert dummy item if starredDirs: self._combo.insertItem(0, translate("filebrowser", "Projects:"), "") # No-project item else: self._combo.addItem(translate("filebrowser", "Click star to bookmark current dir"), "")
class ShellWizardPage2(BaseIEPWizardPage): _title = translate('wizard', 'Configuring shells') _image_filename = 'iep_shell2.png' _descriptions = [ translate( 'wizard', """IEP can integrate the event loop of five different *GUI toolkits*, thus enabling interactive plotting with e.g. Visvis or Matplotlib."""), translate( 'wizard', """Via 'Shell > Edit shell configurations', you can edit and add *shell configurations*. This allows you to for example select the initial directory, or use a custom Pythonpath."""), ]
class EditorWizardPage(BaseIEPWizardPage): _title = translate('wizard', 'The editor is where you write your code') _image_filename = 'iep_editor.png' _descriptions = [ translate( 'wizard', """In the *editor*, each open file is represented as a tab. By right-clicking on a tab, files can be run, saved, closed, etc."""), translate( 'wizard', """The right mouse button also enables one to make a file the *main file* of a project. This file can be recognized by its star symbol, and it enables running the file more easily."""), ]
class ToolsWizardPage1(BaseIEPWizardPage): _title = translate('wizard', 'Tools for your convenience') _image_filename = 'iep_tools1.png' _descriptions = [ translate( 'wizard', """Via the *Tools menu*, one can select which tools to use. The tools can be positioned in any way you want, and can also be un-docked."""), translate( 'wizard', """Note that the tools system is designed such that it's easy to create your own tools. Look at the online wiki for more information, or use one of the existing tools as an example."""), ]
def retranslate(t): """ To allow retranslating after selecting the language. """ if hasattr(t, 'original'): return translate('wizard', t.original) else: return t
def __init__(self, parent): QtGui.QWizard.__init__(self, parent) # Set some appearance stuff self.setMinimumSize(600, 500) self.setWindowTitle(translate('wizard', 'Getting started with IEP')) self.setWizardStyle(self.ModernStyle) self.setButtonText(self.CancelButton, 'Stop') # Set logo pm = QtGui.QPixmap() pm.load( os.path.join(iep.iepDir, 'resources', 'appicons', 'ieplogo48.png')) self.setPixmap(self.LogoPixmap, pm) # Define pages klasses = [ IntroWizardPage, TwocomponentsWizardPage, EditorWizardPage, ShellWizardPage1, ShellWizardPage2, RuncodeWizardPage1, RuncodeWizardPage2, ToolsWizardPage1, ToolsWizardPage2, FinalPage ] # Create pages self._n = len(klasses) for i, klass in enumerate(klasses): self.addPage(klass(self, i))
class ToolsWizardPage2(BaseIEPWizardPage): _title = translate('wizard', 'Recommended tools') _image_filename = 'iep_tools2.png' _descriptions = [ translate('wizard', """We especially recommend the following tools:"""), translate( 'wizard', """The *Source structure tool* gives an outline of the source code.""" ), translate( 'wizard', """The *File browser tool* helps keep an overview of all files in a directory. To manage your projects, click the star icon."""), ]
def __init__(self, parent): QtGui.QWizard.__init__(self, parent) # Set some appearance stuff self.setMinimumSize(600, 500) self.setWindowTitle(translate('wizard', 'Getting started with IEP')) self.setWizardStyle(self.ModernStyle) self.setButtonText(self.CancelButton, 'Stop') # Set logo pm = QtGui.QPixmap() pm.load(os.path.join(iep.iepDir, 'resources', 'appicons', 'ieplogo48.png')) self.setPixmap(self.LogoPixmap, pm) # Define pages klasses = [ IntroWizardPage, TwocomponentsWizardPage, EditorWizardPage, ShellWizardPage1, ShellWizardPage2, RuncodeWizardPage1, RuncodeWizardPage2, ToolsWizardPage1, ToolsWizardPage2, FinalPage] # Create pages self._n = len(klasses) for i, klass in enumerate(klasses): self.addPage(klass(self, i))
class ShellWizardPage1(BaseIEPWizardPage): _title = translate('wizard', 'The shell is where your code gets executed') _image_filename = 'iep_shell1.png' _descriptions = [ translate( 'wizard', """When IEP starts, a default *shell* is created. You can add more shells that run simultaneously, and which may be of different Python versions."""), translate( 'wizard', """Shells run in a sub-process, such that when it is busy, IEP itself stays responsive, allowing you to keep coding and even run code in another shell."""), ]
def __init__(self, projectManager, *args, **kwds): QtGui.QDialog.__init__(self, *args, **kwds) # Set size and title size = 540, 300 self.setMinimumSize(*size) self.setWindowTitle(iep.translate('Projects', 'Manage projects')) # Create widgets and layout self._createWidgets() # Store project manager and attach model for the list of projects self._projectManager = projectManager self._projectsModel = projectManager.projectsModel self._activeProject = None self.lstProjects.setModel(self._projectsModel) # Workaround for PySide bug 1041 # - QAbstractItemModel has wrong ownership policy for selectionModel() # Instantiate a new selectionModel in Python so Python retains ownerships self.lstProjects.setSelectionModel( QtGui.QItemSelectionModel(self.lstProjects.model())) # Signals self.btnAdd.clicked.connect(self.addProject) self.btnRemove.clicked.connect(self.removeProject) self.btnDone.clicked.connect(self.close) self.txtDescription.editingFinished.connect(self.onDescriptionChanged) self.chkAddToPath.stateChanged.connect(self.onAddToPathChanged) self.lstProjects.selectionModel().currentChanged.connect( self.onProjectChanged) # Update description label when project name is changed self.lstProjects.model().dataChanged.connect( lambda i1, i2: self.txtDescription.setText(self._activeProject.name ))
def __init__(self, projectManager, *args, **kwds): QtGui.QDialog.__init__(self, *args, **kwds) # Set size and title size = 540, 300 self.setMinimumSize(*size) self.setWindowTitle(iep.translate('Projects', 'Manage projects')) # Create widgets and layout self._createWidgets() # Store project manager and attach model for the list of projects self._projectManager = projectManager self._projectsModel = projectManager.projectsModel self._activeProject = None self.lstProjects.setModel(self._projectsModel) # Workaround for PySide bug 1041 # - QAbstractItemModel has wrong ownership policy for selectionModel() # Instantiate a new selectionModel in Python so Python retains ownerships self.lstProjects.setSelectionModel( QtGui.QItemSelectionModel(self.lstProjects.model())) # Signals self.btnAdd.clicked.connect(self.addProject) self.btnRemove.clicked.connect(self.removeProject) self.btnDone.clicked.connect(self.close) self.txtDescription.editingFinished.connect(self.onDescriptionChanged) self.chkAddToPath.stateChanged.connect(self.onAddToPathChanged) self.lstProjects.selectionModel().currentChanged.connect(self.onProjectChanged) # Update description label when project name is changed self.lstProjects.model().dataChanged.connect( lambda i1,i2: self.txtDescription.setText(self._activeProject.name))
def updateProjectList(self): # Get sorted version of starredDirs starredDirs = self.parent().starredDirs starredDirs.sort(key=lambda p: p.lower()) # Refill the combo box self._combo.clear() for p in starredDirs: name = self.parent().dictForStarredDir(p).name self._combo.addItem(name, p) # Insert dummy item if starredDirs: self._combo.insertItem(0, translate('filebrowser', 'Projects:'), '') # No-project item else: self._combo.addItem( translate('filebrowser', 'Click star to bookmark current dir'), '')
def __init__(self, parent, i): BaseIEPWizardPage.__init__(self, parent, i) # Create label and checkbox t1 = translate('wizard', "This wizard can be opened using 'Help > IEP wizard'") t2 = translate('wizard', "Show this wizard on startup") self._label_info = QtGui.QLabel(t1, self) self._check_show = QtGui.QCheckBox(t2, self) self._check_show.stateChanged.connect(self._setNewUser) # Create language switcher self._langLabel = QtGui.QLabel(translate('wizard', "Select language"), self) # self._langBox = QtGui.QComboBox(self) self._langBox.setEditable(False) # Fill index, theIndex = -1, -1 cur = iep.config.settings.language for lang in sorted(LANGUAGES): index += 1 self._langBox.addItem(lang) if lang == LANGUAGE_SYNONYMS.get(cur, cur): theIndex = index # Set current index if theIndex >= 0: self._langBox.setCurrentIndex(theIndex) # Bind signal self._langBox.activated.connect(self.onLanguageChange) # Init check state if iep.config.state.newUser: self._check_show.setCheckState(QtCore.Qt.Checked) # Create sublayout layout = QtGui.QHBoxLayout() layout.addWidget(self._langLabel, 0) layout.addWidget(self._langBox, 0) layout.addStretch(2) self.layout().addLayout(layout) # Add to layout self.layout().addSpacing(10) self.layout().addWidget(self._label_info) self.layout().addWidget(self._check_show)
def __init__(self, parent = None): super().__init__(parent) # Drag/drop self.setSelectionMode(self.ExtendedSelection) self.setDragEnabled(True) # Double click self.doubleClicked.connect(self._onDoubleClicked) # Context menu self._menu = Menu(self, translate("menu", "History")) self._menu.addItem(translate("menu", "Copy ::: Copy selected lines"), iep.icons.page_white_copy, self.copy, "copy") self._menu.addItem(translate("menu", "Run ::: Run selected lines in current shell"), iep.icons.run_lines, self.runSelection, "run") self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.customContextMenuRequested.connect(self._onCustomContextMenuRequested)
def onBtnInsertClicked(self): editor = iep.editors.getCurrentEditor() if editor is None: QtGui.QMessageBox.information(self, translate('importwizard', 'Import data wizard'), translate('importwizard', 'No current file open')) return code = self.getCode() # Format tabs/spaces according to editor setting if editor.indentUsingSpaces(): code = code.replace('\t', ' ' * editor.indentWidth()) # insert code at start of line cursor = editor.textCursor() cursor.movePosition(cursor.StartOfBlock) cursor.insertText(code)
def __init__(self, parent): QtGui.QToolButton.__init__(self, parent) # Set text and tooltip self._baseText = translate('debug', 'Stack') self.setText('%s:' % self._baseText) self.setIcon(iep.icons.text_align_justify) self.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.setPopupMode(self.InstantPopup) # Bind to triggers self.triggered.connect(self.onTriggered)
def _runAsScript(self): filename = self._item.path() shell = iep.shells.getCurrentShell() if shell is not None: shell.restart(filename) else: msg = "No shell to run code in. " m = QtGui.QMessageBox(self) m.setWindowTitle(translate("menu dialog", "Could not run")) m.setText("Could not run " + filename + ":\n\n" + msg) m.setIcon(m.Warning) m.exec_()
class RuncodeWizardPage2(BaseIEPWizardPage): _title = translate('wizard', 'Interactive mode vs running as script') _image_filename = '' _descriptions = [ translate( 'wizard', """You can run the current file or the main file normally, or as a script. When run as script, the shell is restared to provide a clean environment. The shell is also initialized differently so that it closely resembles a normal script execution."""), translate( 'wizard', """In interactive mode, sys.path[0] is an empty string (i.e. the current dir), and sys.argv is set to ['']."""), translate( 'wizard', """In script mode, __file__ and sys.argv[0] are set to the scripts filename, sys.path[0] and the working dir are set to the directory containing the script.""" ), ]
class RuncodeWizardPage1(BaseIEPWizardPage): _title = translate('wizard', 'Running code') _image_filename = 'iep_run1.png' _descriptions = [ translate( 'wizard', "IEP supports several ways to run source code in the editor. (see the 'Run' menu)." ), translate( 'wizard', """*Run selection:* if there is no selected text, the current line is executed; if the selection is on a single line, the selection is evaluated; if the selection spans multiple lines, IEP will run the the (complete) selected lines."""), translate( 'wizard', "*Run cell:* a cell is everything between two lines starting with '##'." ), translate('wizard', "*Run file:* run all the code in the current file."), translate( 'wizard', "*Run project main file:* run the code in the current project's main file." ), ]
def __init__(self): QtGui.QWizardPage.__init__(self) self.setTitle("Execute import") self.setButtonText(QtGui.QWizard.FinishButton, translate('importwizard', 'Close')) self.rbAsArray = QtGui.QRadioButton(translate('importwizard', 'Import data as single array')) self.rbPerColumn = QtGui.QRadioButton(translate('importwizard', 'Import data into one variable per column')) self.rbAsArray.setChecked(True) self.chkInvalidRaise = QtGui.QCheckBox(translate('importwizard', 'Raise error upon invalid data')) self.chkInvalidRaise.setChecked(True) self.codeView = CodeView() self.codeView.setParser('python') self.codeView.setZoom(iep.config.view.zoom) self.codeView.setFont(iep.config.view.fontname) self.btnExecute = QtGui.QPushButton('Execute in current shell') self.btnInsert = QtGui.QPushButton('Paste into current file') layout = QtGui.QVBoxLayout() layout.addWidget(self.rbAsArray) layout.addWidget(self.rbPerColumn) layout.addWidget(self.chkInvalidRaise) layout.addWidget(QtGui.QLabel('Resulting import code:')) layout.addWidget(self.codeView) layout.addWidget(self.btnExecute) layout.addWidget(self.btnInsert) self.setLayout(layout) self.registerField('invalid_raise', self.chkInvalidRaise) self.btnExecute.clicked.connect(self.onBtnExecuteClicked) self.btnInsert.clicked.connect(self.onBtnInsertClicked) self.rbAsArray.clicked.connect(self.updateCode) self.rbPerColumn.clicked.connect(self.updateCode) self.chkInvalidRaise.stateChanged.connect(lambda state: self.updateCode())
def _createDirOrFile(self, file=True): # Get title and label if file: title = translate("filebrowser", "Create new file") label = translate("filebrowser", "Give the new name for the file") else: title = translate("filebrowser", "Create new directory") label = translate("filebrowser", "Give the name for the new directory") # Ask for new filename s = QtGui.QInputDialog.getText( self.parent(), title, label + ":\n%s" % self._item.path(), QtGui.QLineEdit.Normal, "new name" ) if isinstance(s, tuple): s = s[0] if s[1] else "" # Push rename task if s: newpath = os.path.join(self._item.path(), s) task = tasks.CreateTask(newpath=newpath, file=file) self._item._proxy.pushTask(task)
def __init__(self, parent): QtGui.QScrollArea.__init__(self, parent) # Init the scroll area self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.setWidgetResizable(True) self.setFrameShape(QtGui.QFrame.NoFrame); # Create widget and a layout self._content = QtGui.QWidget(parent) self._formLayout = QtGui.QFormLayout(self._content) # Collect classes of widgets to instantiate classes = [] for t in self.INFO_KEYS: className = 'ShellInfo_' + t.key cls = globals()[className] classes.append((t, cls)) # Instantiate all classes self._shellInfoWidgets = {} for t, cls in classes: # Instantiate and store instance = cls(self._content) self._shellInfoWidgets[t.key] = instance # Create label label = QtGui.QLabel(t, self._content) label.setToolTip(t.tt) # Add to layout self._formLayout.addRow(label, instance) # Add delete button t = translate('shell', 'Delete ::: Delete this shell configuration') label = QtGui.QLabel('', self._content) instance = QtGui.QPushButton(iep.icons.cancel, t, self._content) instance.setToolTip(t.tt) instance.setAutoDefault(False) instance.clicked.connect(self.parent().parent().onTabClose) deleteLayout = QtGui.QHBoxLayout() deleteLayout.addWidget(instance, 0) deleteLayout.addStretch(1) # Add to layout self._formLayout.addRow(label, deleteLayout) # Apply layout self._formLayout.setSpacing(15) self._content.setLayout(self._formLayout) self.setWidget(self._content)
def __init__(self): QtGui.QWizardPage.__init__(self) self.setTitle("Select parameters") self._columnNames = None def genComboBox(choices): cbx = QtGui.QComboBox() for choice in choices: cbx.addItem(choice) cbx.setEditable(True) return cbx self.cbxDelimiter = genComboBox(",;") self.cbxComments = genComboBox("#%'") self.sbSkipHeader = QtGui.QSpinBox() self.preview = QtGui.QTableWidget() self.preview.setSelectionModel(QtGui.QItemSelectionModel(self.preview.model())) # Work-around for reference tracking bug in PySide self.preview.setSelectionBehavior(self.preview.SelectColumns) self.preview.setSelectionMode(self.preview.MultiSelection) # Layout formlayout = QtGui.QFormLayout() formlayout.addRow('Delimiter', self.cbxDelimiter) formlayout.addRow('Comments', self.cbxComments) formlayout.addRow('Header rows to skip', self.sbSkipHeader) layout = QtGui.QVBoxLayout() layout.addLayout(formlayout) layout.addWidget(QtGui.QLabel( translate('importwizard', 'Select columns to import:'))) layout.addWidget(self.preview) self.setLayout(layout) # Wizard fields self.registerField('delimiter', self.cbxDelimiter, "currentText") self.registerField('comments', self.cbxComments, "currentText") self.registerField('skip_header', self.sbSkipHeader) # Signals self.cbxComments.editTextChanged.connect(self.updatePreview) self.cbxDelimiter.editTextChanged.connect(self.updatePreview) self.sbSkipHeader.valueChanged.connect(self.updatePreview) self.preview.verticalHeader().sectionClicked.connect(self.onRowHeaderClicked)
def buildMenu(self): config = self.parent().config menu = self._menu menu.clear() map = [ ('searchMatchCase', False, translate("filebrowser", "Match case")), ('searchRegExp', False, translate("filebrowser", "RegExp")), ('searchSubDirs', True, translate("filebrowser", "Search in subdirs")) ] # Fill menu for option, default, description in map: if option is None: menu.addSeparator() else: # Make sure the option exists if option not in config: config[option] = default # Make action in menu action = menu.addAction(description) action._option = option action.setCheckable(True) action.setChecked( bool(config[option]) )
def buildMenu(self): menu = self._menu menu.clear() # Add action to remove bookmark action = menu.addAction(translate('filebrowser', 'Remove project')) action._id = 'remove' action.setCheckable(False) # Add action to change name action = menu.addAction(translate('filebrowser', 'Change project name')) action._id = 'name' action.setCheckable(False) menu.addSeparator() # Add check action for adding to Pythonpath action = menu.addAction(translate('filebrowser', 'Add path to Python path')) action._id = 'pythonpath' action.setCheckable(True) d = self.currentDict() if d: checked = bool( d and d['addToPythonpath'] ) action.setChecked(checked)
def buildMenu(self): config = self.parent().config menu = self._menu menu.clear() map = [('searchMatchCase', False, translate("filebrowser", "Match case")), ('searchRegExp', False, translate("filebrowser", "RegExp")), ('searchSubDirs', True, translate("filebrowser", "Search in subdirs"))] # Fill menu for option, default, description in map: if option is None: menu.addSeparator() else: # Make sure the option exists if option not in config: config[option] = default # Make action in menu action = menu.addAction(description) action._option = option action.setCheckable(True) action.setChecked(bool(config[option]))
def __init__(self, parent): QtGui.QToolButton.__init__(self, parent) # Set text and tooltip self.setText('Debug') self.setIcon(iep.icons.bug) self.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.setToolTip(translate("debug", "Start/Stop post mortem debugging.")) # Set mode self.setPopupMode(self.InstantPopup) # Bind to triggers self.pressed.connect(self.onPressed) self.triggered.connect(self.onTriggered)
def _createDirOrFile(self, file=True): # Get title and label if file: title = translate("filebrowser", "Create new file") label = translate("filebrowser", "Give the new name for the file") else: title = translate("filebrowser", "Create new directory") label = translate("filebrowser", "Give the name for the new directory") # Ask for new filename s = QtGui.QInputDialog.getText(self.parent(), title, label + ':\n%s' % self._item.path(), QtGui.QLineEdit.Normal, 'new name' ) if isinstance(s, tuple): s = s[0] if s[1] else '' # Push rename task if s: newpath = os.path.join(self._item.path(), s) task = tasks.CreateTask(newpath=newpath, file=file) self._item._proxy.pushTask(task)
def __init__(self): QtGui.QWizard.__init__(self) self.setMinimumSize(500,400) self.resize(700,500) self.setPreviewData(None) self.selectFilePage = SelectFilePage() self.setParametersPage = SetParametersPage() self.resultPage = ResultPage() self.addPage(self.selectFilePage) self.addPage(self.setParametersPage) self.addPage(self.resultPage) self.setWindowTitle(translate('importwizard', 'Import data')) self.currentIdChanged.connect(self.onCurrentIdChanged)
def __init__(self, parent): QtGui.QWidget.__init__(self, parent) # Create layout self._formLayout = QtGui.QFormLayout(self) # Collect classes of widgets to instantiate classes = [] for t in self.INFO_KEYS: className = 'ShellInfo_' + t.key cls = globals()[className] classes.append((t, cls)) # Instantiate all classes self._shellInfoWidgets = {} for t, cls in classes: # Instantiate and store instance = cls(self) self._shellInfoWidgets[t.key] = instance # Create label label = QtGui.QLabel(t, self) label.setToolTip(t.tt) # Add to layout self._formLayout.addRow(label, instance) # Add delete button t = translate('shell', 'Delete ::: Delete this shell configuration') label = QtGui.QLabel('', self) instance = QtGui.QPushButton(iep.icons.cancel, t, self) instance.setToolTip(t.tt) instance.setAutoDefault(False) instance.clicked.connect(self.parent().parent().onTabClose) deleteLayout = QtGui.QHBoxLayout() deleteLayout.addWidget(instance, 0) deleteLayout.addStretch(1) # Add to layout self._formLayout.addRow(label, deleteLayout) # Apply layout self._formLayout.setSpacing(15) self.setLayout(self._formLayout)
def __init__(self, parent, widget, systemValue): # Do not pass parent, because is a sublayout QtGui.QVBoxLayout.__init__(self) # Layout self.setSpacing(1) self.addWidget(widget) # Create checkbox widget if not self.DISABLE_SYSTEM_DEFAULT: t = translate('shell', 'Use system default') self._check = QtGui.QCheckBox(t, parent) self._check.stateChanged.connect(self.onCheckChanged) self.addWidget(self._check) # The actual value of this shell config attribute self._value = '' # The value of self._value if the system default is selected self._systemValue = systemValue # A buffered version, so that clicking the text box does not # remove the value at once self._bufferedValue = ''
def build(self): isplat = sys.platform.startswith # The star object if isinstance(self._item, DirItem): if self._item._starred: self.addItem(translate("filebrowser", "Unstar this dir"), None, self._star) else: self.addItem(translate("filebrowser", "Star this dir"), None, self._star) self.addSeparator() # The normal "open" function if isinstance(self._item, FileItem): self.addItem(translate("filebrowser", "Open"), None, self._item.onActivated) # Create items for open and copy path if isinstance(self._item, (FileItem, DirItem)): if isplat('win') or isplat('darwin') or isplat('linux'): self.addItem(translate("filebrowser", "Open outside iep"), None, self._openOutsideIep) if isplat('darwin'): self.addItem(translate("filebrowser", "Reveal in Finder"), None, self._showInFinder) if True: self.addItem(translate("filebrowser", "Copy path"), None, self._copyPath) self.addSeparator() # Create items for file management if isinstance(self._item, FileItem): self.addItem(translate("filebrowser", "Rename"), None, self.onRename) self.addItem(translate("filebrowser", "Delete"), None, self.onDelete) #self.addItem(translate("filebrowser", "Duplicate"), None, self.onDuplicate) if isinstance(self._item, (Tree, DirItem)): self.addItem(translate("filebrowser", "Create new file"), None, self.onCreateFile) self.addItem(translate("filebrowser", "Create new directory"), None, self.onCreateDir) if isinstance(self._item, DirItem): self.addSeparator() self.addItem(translate("filebrowser", "Delete"), None, self.onDelete)
def __init__(self, *args): QtGui.QDialog.__init__(self, *args) self.setModal(True) # Set title self.setWindowTitle(iep.translate('shell', 'Shell configurations')) # Create tab widget self._tabs = QtGui.QTabWidget(self) #self._tabs = CompactTabWidget(self, padding=(4,4,5,5)) #self._tabs.setDocumentMode(False) self._tabs.setMovable(True) # Get known interpreters (sorted them by version) # Do this here so we only need to do it once ... from pyzolib.interpreters import get_interpreters self.interpreters = list(reversed(get_interpreters('2.4'))) # Introduce an entry if there's none if not iep.config.shellConfigs2: w = ShellInfoTab(self._tabs) self._tabs.addTab(w, '---') w.setInfo() # Fill tabs for item in iep.config.shellConfigs2: w = ShellInfoTab(self._tabs) self._tabs.addTab(w, '---') w.setInfo(item) # Enable making new tabs and closing tabs self._add = QtGui.QToolButton(self) self._tabs.setCornerWidget(self._add) self._add.clicked.connect(self.onAdd) self._add.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self._add.setIcon(iep.icons.add) self._add.setText(translate('shell', 'Add config')) # #self._tabs.setTabsClosable(True) self._tabs.tabCloseRequested.connect(self.onTabClose) # Create buttons cancelBut = QtGui.QPushButton("Cancel", self) okBut = QtGui.QPushButton("Done", self) cancelBut.clicked.connect(self.close) okBut.clicked.connect(self.applyAndClose) # Layout for buttons buttonLayout = QtGui.QHBoxLayout() buttonLayout.addStretch(1) buttonLayout.addWidget(cancelBut) buttonLayout.addSpacing(10) buttonLayout.addWidget(okBut) # Layout the widgets mainLayout = QtGui.QVBoxLayout(self) mainLayout.addSpacing(8) mainLayout.addWidget(self._tabs,0) mainLayout.addLayout(buttonLayout,0) self.setLayout(mainLayout) # Prevent resizing self.show() size = self.size() self.setMinimumSize(size) self.setMaximumHeight(size.height())
class ShellInfoTab(QtGui.QWidget): INFO_KEYS = [ translate('shell', 'name ::: The name of this configuration.'), translate('shell', 'exe ::: The Python executable.'), translate('shell', 'gui ::: The GUI toolkit to integrate (for interactive plotting, etc.).'), translate('shell', 'pythonPath ::: A list of directories to search for modules and packages. Write each path on a new line, or separate with the default seperator for this OS.'), translate('shell', 'startupScript ::: The script to run at startup (not in script mode).'), translate('shell', 'startDir ::: The start directory (not in script mode).') ] def __init__(self, parent): QtGui.QWidget.__init__(self, parent) # Create layout self._formLayout = QtGui.QFormLayout(self) # Collect classes of widgets to instantiate classes = [] for t in self.INFO_KEYS: className = 'ShellInfo_' + t.key cls = globals()[className] classes.append((t, cls)) # Instantiate all classes self._shellInfoWidgets = {} for t, cls in classes: # Instantiate and store instance = cls(self) self._shellInfoWidgets[t.key] = instance # Create label label = QtGui.QLabel(t, self) label.setToolTip(t.tt) # Add to layout self._formLayout.addRow(label, instance) # Add delete button t = translate('shell', 'Delete ::: Delete this shell configuration') label = QtGui.QLabel('', self) instance = QtGui.QPushButton(iep.icons.cancel, t, self) instance.setToolTip(t.tt) instance.setAutoDefault(False) instance.clicked.connect(self.parent().parent().onTabClose) deleteLayout = QtGui.QHBoxLayout() deleteLayout.addWidget(instance, 0) deleteLayout.addStretch(1) # Add to layout self._formLayout.addRow(label, deleteLayout) # Apply layout self._formLayout.setSpacing(15) self.setLayout(self._formLayout) def setTabTitle(self, name): tabWidget = self.parent().parent() tabWidget.setTabText(tabWidget.indexOf(self), name) def setInfo(self, info=None): """ Set the shell info struct, and use it to update the widgets. Not via init, because this function also sets the tab name. """ # If info not given, use default as specified by the KernelInfo struct if info is None: info = KernelInfo() # Name n = self.parent().parent().count() if n > 1: info.name = "Shell config %i" % n # Store info self._info = info # Set widget values according to info try: for key in info: widget = self._shellInfoWidgets.get(key, None) if widget is not None: widget.setTheText(info[key]) except Exception as why: print("Error setting info in shell config:", why) print(info) def getInfo(self): info = self._info # Set struct values according to widgets try: for key in info: widget = self._shellInfoWidgets.get(key, None) if widget is not None: info[key] = widget.getTheText() except Exception as why: print("Error getting info in shell config:", why) print(info) # Return the original (but modified) ssdf struct object return info
def __init__(self, *args): QtGui.QFrame.__init__(self, *args) self.setFocusPolicy(QtCore.Qt.ClickFocus) # init layout layout = QtGui.QHBoxLayout(self) layout.setSpacing(0) self.setLayout(layout) # Create some widgets first to realize a correct tab order self._hidebut = QtGui.QToolButton(self) self._findText = QtGui.QLineEdit(self) self._replaceText = QtGui.QLineEdit(self) if True: # Create sub layouts vsubLayout = QtGui.QVBoxLayout() vsubLayout.setSpacing(0) layout.addLayout(vsubLayout, 0) # Add button self._hidebut.setFont( QtGui.QFont('helvetica',7) ) self._hidebut.setToolTip(translate('search', 'Hide search widget (Escape)')) self._hidebut.setIcon( iep.icons.cancel ) self._hidebut.setIconSize(QtCore.QSize(16,16)) vsubLayout.addWidget(self._hidebut, 0) vsubLayout.addStretch(1) layout.addSpacing(10) if True: # Create sub layouts vsubLayout = QtGui.QVBoxLayout() hsubLayout = QtGui.QHBoxLayout() vsubLayout.setSpacing(0) hsubLayout.setSpacing(0) layout.addLayout(vsubLayout, 0) # Add find text self._findText.setToolTip(translate('search', 'Find pattern')) vsubLayout.addWidget(self._findText, 0) vsubLayout.addLayout(hsubLayout) # Add previous button self._findPrev = QtGui.QToolButton(self) t = translate('search', 'Previous ::: Find previous occurance of the pattern.') self._findPrev.setText(t); self._findPrev.setToolTip(t.tt) hsubLayout.addWidget(self._findPrev, 0) hsubLayout.addStretch(1) # Add next button self._findNext = QtGui.QToolButton(self) t = translate('search', 'Next ::: Find next occurance of the pattern.') self._findNext.setText(t); self._findNext.setToolTip(t.tt) #self._findNext.setDefault(True) # Not possible with tool buttons hsubLayout.addWidget(self._findNext, 0) layout.addSpacing(10) if True: # Create sub layouts vsubLayout = QtGui.QVBoxLayout() hsubLayout = QtGui.QHBoxLayout() vsubLayout.setSpacing(0) hsubLayout.setSpacing(0) layout.addLayout(vsubLayout, 0) # Add replace text self._replaceText.setToolTip(translate('search', 'Replace pattern')) vsubLayout.addWidget(self._replaceText, 0) vsubLayout.addLayout(hsubLayout) # Add replace-all button self._replaceAll = QtGui.QToolButton(self) t = translate('search', 'Repl. all ::: Replace all matches in current document.') self._replaceAll.setText(t); self._replaceAll.setToolTip(t.tt) hsubLayout.addWidget(self._replaceAll, 0) hsubLayout.addStretch(1) # Add replace button self._replace = QtGui.QToolButton(self) t = translate('search', 'Replace ::: Replace this match.') self._replace.setText(t); self._replace.setToolTip(t.tt) hsubLayout.addWidget(self._replace, 0) layout.addSpacing(10) if True: # Create sub layouts vsubLayout = QtGui.QVBoxLayout() vsubLayout.setSpacing(0) layout.addLayout(vsubLayout, 0) # Add match-case checkbox t = translate('search', 'Match case ::: Find words that match case.') self._caseCheck = QtGui.QCheckBox(t, self) self._caseCheck.setToolTip(t.tt) vsubLayout.addWidget(self._caseCheck, 0) # Add regexp checkbox t = translate('search', 'RegExp ::: Find using regular expressions.') self._regExp = QtGui.QCheckBox(t, self) self._regExp.setToolTip(t.tt) vsubLayout.addWidget(self._regExp, 0) if True: # Create sub layouts vsubLayout = QtGui.QVBoxLayout() vsubLayout.setSpacing(0) layout.addLayout(vsubLayout, 0) # Add whole-word checkbox t = translate('search', 'Whole words ::: Find only whole words.') self._wholeWord = QtGui.QCheckBox(t, self) self._wholeWord.setToolTip(t.tt) self._wholeWord.resize(60, 16) vsubLayout.addWidget(self._wholeWord, 0) # Add autohide dropbox t = translate('search', 'Auto hide ::: Hide search/replace when unused for 10 s.') self._autoHide = QtGui.QCheckBox(t, self) self._autoHide.setToolTip(t.tt) self._autoHide.resize(60, 16) vsubLayout.addWidget(self._autoHide, 0) layout.addStretch(1) # Set placeholder texts for lineEdit in [self._findText, self._replaceText]: if hasattr(lineEdit, 'setPlaceholderText'): lineEdit.setPlaceholderText(lineEdit.toolTip()) lineEdit.textChanged.connect(self.autoHideTimerReset) # Set focus policy for but in [self._findPrev, self._findNext, self._replaceAll, self._replace, self._caseCheck, self._wholeWord, self._regExp]: #but.setFocusPolicy(QtCore.Qt.ClickFocus) but.clicked.connect(self.autoHideTimerReset) # create timer objects self._timerBeginEnd = QtCore.QTimer(self) self._timerBeginEnd.setSingleShot(True) self._timerBeginEnd.timeout.connect( self.resetAppearance ) # self._timerAutoHide = QtCore.QTimer(self) self._timerAutoHide.setSingleShot(False) self._timerAutoHide.setInterval(500) # ms self._timerAutoHide.timeout.connect( self.autoHideTimerCallback ) self._timerAutoHide_t0 = time.time() self._timerAutoHide.start() # create callbacks self._findText.returnPressed.connect(self.findNext) self._hidebut.clicked.connect(self.hideMe) self._findNext.clicked.connect(self.findNext) self._findPrev.clicked.connect(self.findPrevious) self._replace.clicked.connect(self.replaceOne) self._replaceAll.clicked.connect(self.replaceAll) # self._regExp.stateChanged.connect(self.handleReplacePossible) # init case and regexp self._caseCheck.setChecked( bool(iep.config.state.find_matchCase) ) self._regExp.setChecked( bool(iep.config.state.find_regExp) ) self._wholeWord.setChecked( bool(iep.config.state.find_wholeWord) ) self._autoHide.setChecked( bool(iep.config.state.find_autoHide) ) # show or hide? if bool(iep.config.state.find_show): self.show() else: self.hide()