def resize_to_contents(self): """Resize cells to contents""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor()
def test(): from spyderlib.qt.QtGui import QApplication app = QApplication([]) widget = create_widget() widget.show() # Start the application main loop. app.exec_()
def _post_message(self, message, timeout=60000): """ Post a message to the main window status bar with a timeout in ms """ if self.editor_widget: statusbar = self.editor_widget.window().statusBar() statusbar.showMessage(message, timeout) QApplication.processEvents()
def starting_long_process(self, message): """ Showing message in main window's status bar and changing mouse cursor to Qt.WaitCursor """ self.show_message(message) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents()
def ending_long_process(self, message=""): """ Clearing main window's status bar and restoring mouse cursor """ QApplication.restoreOverrideCursor() self.show_message(message, timeout=2000) QApplication.processEvents()
def copy_without_prompts(self): """Copy text to clipboard without prompts""" text = self.get_selected_text() lines = text.split(os.linesep) for index, line in enumerate(lines): if line.startswith('>>> ') or line.startswith('... '): lines[index] = line[4:] text = os.linesep.join(lines) QApplication.clipboard().setText(text)
def write_error(self): if os.name == 'nt': #---This is apparently necessary only on Windows (not sure though): # emptying standard output buffer before writing error output self.process.setReadChannel(QProcess.StandardOutput) if self.process.waitForReadyRead(1): self.write_output() self.shell.write_error(self.get_stderr()) QApplication.processEvents()
def mouseMoveEvent(self, event): """Show Pointing Hand Cursor on error messages""" text = self.get_line_at(event.pos()) if get_error_match(text): if not self.__cursor_changed: QApplication.setOverrideCursor(QCursor(Qt.PointingHandCursor)) self.__cursor_changed = True event.accept() return if self.__cursor_changed: QApplication.restoreOverrideCursor() self.__cursor_changed = False self.QT_CLASS.mouseMoveEvent(self, event)
def save_data(self, filename=None): """Save data""" if filename is None: filename = self.filename if filename is None: filename = getcwd() filename, _selfilter = getsavefilename(self, _("Save data"), filename, iofunctions.save_filters) if filename: self.filename = filename else: return False QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() if self.is_internal_shell: wsfilter = self.get_internal_shell_filter('picklable', check_all=True) namespace = wsfilter(self.shellwidget.interpreter.namespace).copy() error_message = iofunctions.save(namespace, filename) else: settings = self.get_view_settings() error_message = monitor_save_globals(self._get_sock(), settings, filename) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical(self, _("Save data"), _("<b>Unable to save current workspace</b>" "<br><br>Error message:<br>%s") % error_message) self.save_button.setEnabled(self.filename is not None)
def paintEvent(self, event): """Qt Override. Include a validation icon to the left of the line edit. """ super(IconLineEdit, self).paintEvent(event) painter = QPainter(self) rect = self.geometry() space = int((rect.height())/6) h = rect.height() - space w = rect.width() - h if self._icon_visible: if self._status and self._status_set: pixmap = self._set_icon.pixmap(h, h) elif self._status: pixmap = self._valid_icon.pixmap(h, h) else: pixmap = self._invalid_icon.pixmap(h, h) painter.drawPixmap(w, space, pixmap) application_style = QApplication.style().objectName() if self._application_style != application_style: self._application_style = application_style self._refresh() # Small hack to gurantee correct padding on Spyder start if self._paint_count < 5: self._paint_count += 1 self._refresh()
def mouseMoveEvent(self, event): """Override Qt method""" if event.buttons() == Qt.MouseButtons(Qt.LeftButton) and \ (event.pos() - self.__drag_start_pos).manhattanLength() > \ QApplication.startDragDistance(): drag = QDrag(self) mimeData = QMimeData() # Converting id's to long to avoid an OverflowError with PySide if PY2: ancestor_id = long(id(self.ancestor)) parent_widget_id = long(id(self.parentWidget())) self_id = long(id(self)) else: ancestor_id = id(self.ancestor) parent_widget_id = id(self.parentWidget()) self_id = id(self) mimeData.setData("parent-id", QByteArray.number(ancestor_id)) mimeData.setData("tabwidget-id", QByteArray.number(parent_widget_id)) mimeData.setData("tabbar-id", QByteArray.number(self_id)) mimeData.setData("source-index", QByteArray.number(self.tabAt(self.__drag_start_pos))) drag.setMimeData(mimeData) drag.exec_() QTabBar.mouseMoveEvent(self, event)
def data(self, index, role=Qt.DisplayRole): """Qt Override""" if not index.isValid() or \ not (0 <= index.row() < len(self.shortcuts)): return to_qvariant() shortcut = self.shortcuts[index.row()] key = shortcut.key column = index.column() if role == Qt.DisplayRole: if column == CONTEXT: return to_qvariant(shortcut.context) elif column == NAME: color = self.text_color if self._parent == QApplication.focusWidget(): if self.current_index().row() == index.row(): color = self.text_color_highlight else: color = self.text_color return to_qvariant(self._enrich_text(shortcut.name, color)) elif column == SEQUENCE: text = QKeySequence(key).toString(QKeySequence.NativeText) return to_qvariant(text) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter)) return to_qvariant()
def data(self, index, role=Qt.DisplayRole): """Qt Override.""" row = index.row() if not index.isValid() or not (0 <= row < len(self.shortcuts)): return to_qvariant() shortcut = self.shortcuts[row] key = shortcut.key column = index.column() if role == Qt.DisplayRole: if column == CONTEXT: return to_qvariant(shortcut.context) elif column == NAME: color = self.text_color if self._parent == QApplication.focusWidget(): if self.current_index().row() == row: color = self.text_color_highlight else: color = self.text_color text = self.rich_text[row] text = '<p style="color:{0}">{1}</p>'.format(color, text) return to_qvariant(text) elif column == SEQUENCE: text = QKeySequence(key).toString(QKeySequence.NativeText) return to_qvariant(text) elif column == SEARCH_SCORE: # Treating search scores as a table column simplifies the # sorting once a score for a specific string in the finder # has been defined. This column however should always remain # hidden. return to_qvariant(self.scores[row]) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter)) return to_qvariant()
def copy(self): """Copy text to clipboard""" if not self.selectedIndexes(): return (row_min, row_max, col_min, col_max) = get_idx_rect(self.selectedIndexes()) index = header = False if col_min == 0: col_min = 1 index = True df = self.model().df if col_max == 0: # To copy indices contents = '\n'.join(map(str, df.index.tolist()[slice(row_min, row_max+1)])) else: # To copy DataFrame if (col_min == 0 or col_min == 1) and (df.shape[1] == col_max): header = True obj = df.iloc[slice(row_min, row_max+1), slice(col_min-1, col_max)] output = io.StringIO() obj.to_csv(output, sep='\t', index=index, header=header) if not PY2: contents = output.getvalue() else: contents = output.getvalue().decode('utf-8') output.close() clipboard = QApplication.clipboard() clipboard.setText(contents)
def paint(self, painter, option, index): options = QStyleOptionViewItem(option) self.initStyleOption(options, index) style = (QApplication.style() if options.widget is None else options.widget.style()) doc = QTextDocument() doc.setDocumentMargin(self._margin) doc.setHtml(options.text) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() if style.objectName() == 'oxygen': painter.translate(textRect.topLeft() + QPoint(5, -9)) else: painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def __init__(self, target, executable=None, name=None, extra_args=None, libs=None, cwd=None, env=None): super(AsyncClient, self).__init__() self.executable = executable or sys.executable self.extra_args = extra_args self.target = target self.name = name or self self.libs = libs self.cwd = cwd self.env = env self.is_initialized = False self.closing = False self.context = zmq.Context() QApplication.instance().aboutToQuit.connect(self.close) # Set up the heartbeat timer. self.timer = QTimer(self) self.timer.timeout.connect(self._heartbeat) self.timer.start(HEARTBEAT)
def show_data(self, justanalyzed=False): if not justanalyzed: self.output = None self.log_button.setEnabled(self.output is not None \ and len(self.output) > 0) self.kill_if_running() filename = to_text_string(self.filecombo.currentText()) if not filename: return self.datatree.load_data(self.DATAPATH) self.datelabel.setText(_('Sorting data, please wait...')) QApplication.processEvents() self.datatree.show_tree() text_style = "<span style=\'color: #444444\'><b>%s </b></span>" date_text = text_style % time.strftime("%d %b %Y %H:%M", time.localtime()) self.datelabel.setText(date_text)
def qapplication(translate=True): """Return QApplication instance Creates it if it doesn't already exist""" app = QApplication.instance() if not app: # Set Application name for Gnome 3 # https://groups.google.com/forum/#!topic/pyside/24qxvwfrRDs app = QApplication(['Spyder']) if translate: install_translator(app) return app
def tab_moved(self, event): """Method called when a tab from a QTabBar has been moved.""" # If the left button isn't pressed anymore then return if not event.buttons() & Qt.LeftButton: self.to_index = None return self.to_index = self.dock_tabbar.tabAt(event.pos()) if not self.moving and self.from_index != -1 and self.to_index != -1: QApplication.setOverrideCursor(Qt.ClosedHandCursor) self.moving = True if self.to_index == -1: self.to_index = self.from_index from_index, to_index = self.from_index, self.to_index if from_index != to_index and from_index != -1 and to_index != -1: self.move_tab(from_index, to_index) self._fix_cursor(from_index, to_index) self.from_index = to_index
def __init__(self, *args, **kwargs): super(IconLineEdit, self).__init__(*args, **kwargs) self._status = True self._status_set = True self._valid_icon = ima.icon('todo') self._invalid_icon = ima.icon('warning') self._set_icon = ima.icon('todo_list') self._application_style = QApplication.style().objectName() self._refresh() self._paint_count = 0 self._icon_visible = False
def mousePressEvent(self, event): """Reimplement Qt method""" if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() if self.has_selected_text(): self.remove_selected_text() self.setFocus() event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier) QPlainTextEdit.mousePressEvent(self, event) QPlainTextEdit.mouseReleaseEvent(self, event) # Send selection text to clipboard to be able to use # the paste method and avoid the strange Issue 1445 # # Note: This issue seems a focusing problem but it # seems really hard to track mode_clip = QClipboard.Clipboard mode_sel = QClipboard.Selection text_clip = QApplication.clipboard().text(mode=mode_clip) text_sel = QApplication.clipboard().text(mode=mode_sel) QApplication.clipboard().setText(text_sel, mode=mode_clip) self.paste() QApplication.clipboard().setText(text_clip, mode=mode_clip) else: self.calltip_widget.hide() QPlainTextEdit.mousePressEvent(self, event)
def findinfiles_callback(self): """Find in files callback""" widget = QApplication.focusWidget() if not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.raise_() text = '' from spyderlib.widgets.editor import TextEditBaseWidget if isinstance(widget, TextEditBaseWidget): if widget.has_selected_text(): text = widget.get_selected_text() self.set_search_text(text) if text: self.find()
def start(self): """Start a new connection with the plugin. """ self._initialized = False plugin_name = self.plugin_name self.sock, server_port = connect_to_port() self.sock.listen(2) QApplication.instance().aboutToQuit.connect(self.close) self.process = QProcess(self) self.process.setWorkingDirectory(os.path.dirname(__file__)) processEnvironment = QProcessEnvironment() env = self.process.systemEnvironment() python_path = imp.find_module('spyderlib')[1] # Use the current version of the plugin provider if possible. try: provider_path = imp.find_module(self.plugin_name)[1] python_path = os.sep.join([python_path, provider_path]) except ImportError: pass env.append("PYTHONPATH=%s" % python_path) for envItem in env: envName, separator, envValue = envItem.partition('=') processEnvironment.insert(envName, envValue) self.process.setProcessEnvironment(processEnvironment) p_args = ['-u', 'plugin_server.py', str(server_port), plugin_name] self.listener = PluginListener(self.sock) self.listener.request_handled.connect(self.request_handled.emit) self.listener.initialized.connect(self._on_initialized) self.listener.start() self.process.start(self.executable, p_args) self.process.finished.connect(self._on_finished) running = self.process.waitForStarted() if not running: raise IOError('Could not start plugin %s' % plugin_name)
def findinfiles_callback(self): """Find in files callback""" widget = QApplication.focusWidget() if not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.raise_() text = '' try: if widget.has_selected_text(): text = widget.get_selected_text() except AttributeError: # This is not a text widget deriving from TextEditBaseWidget pass self.set_search_text(text) if text: self.find()
def paste(self): """Reimplemented slot to handle multiline paste action""" text = to_text_string(QApplication.clipboard().text()) if len(text.splitlines()) > 1: # Multiline paste if self.new_input_line: self.on_new_line() self.remove_selected_text() # Remove selection, eventually end = self.get_current_line_from_cursor() lines = self.get_current_line_to_cursor() + text + end self.clear_line() self.execute_lines(lines) self.move_cursor(-len(end)) else: # Standard paste ShellBaseWidget.paste(self)
def mouseMoveEvent(self, event): """Override Qt method""" if event.buttons() == Qt.MouseButtons(Qt.LeftButton) and \ (event.pos() - self.__drag_start_pos).manhattanLength() > \ QApplication.startDragDistance(): drag = QDrag(self) mimeData = QMimeData() mimeData.setData("parent-id", QByteArray.number(id(self.ancestor))) mimeData.setData("tabwidget-id", QByteArray.number(id(self.parentWidget()))) mimeData.setData("tabbar-id", QByteArray.number(id(self))) mimeData.setData("source-index", QByteArray.number(self.tabAt(self.__drag_start_pos))) drag.setMimeData(mimeData) drag.exec_() QTabBar.mouseMoveEvent(self, event)
def pypi_fedit(data, title="", comment="", icon=None, parent=None, apply=None): import webbrowser if QApplication.startingUp(): _app = QApplication([]) dialog = FormDialog(data, title, comment, icon, parent, apply) url = 'https://pypi.python.org/pypi?:action=browse&show=all' params = {':action':'browse', 'show':'all'} if dialog.exec_(): raw_selections = dialog.get() stripped_selections = ' '.join(raw_selections).split() if len(stripped_selections) != 0: _selections = '&'.join(stripped_selections) selections = '&' + _selections else: selections = '' prepared_url = url + selections webbrowser.open_new(prepared_url)
def copy(self, index=False, header=False): """Copy text to clipboard""" (row_min, row_max, col_min, col_max) = get_idx_rect(self.selectedIndexes()) if col_min == 0: col_min = 1 index = True df = self.model().df if col_max == 0: # To copy indices contents = '\n'.join(map(str, df.index.tolist()[slice(row_min, row_max+1)])) else: # To copy DataFrame if df.shape[0] == row_max+1 and row_min == 0: header = True obj = df.iloc[slice(row_min, row_max+1), slice(col_min-1, col_max)] output = io.StringIO() obj.to_csv(output, sep='\t', index=index, header=header) contents = output.getvalue() output.close() clipboard = QApplication.clipboard() clipboard.setText(contents)
def fedit(data, title="", comment="", icon=None, parent=None, apply=None): """ Create form dialog and return result (if Cancel button is pressed, return None) data: datalist, datagroup title: string comment: string icon: QIcon instance parent: parent QWidget apply: apply callback (function) datalist: list/tuple of (field_name, field_value) datagroup: list/tuple of (datalist *or* datagroup, title, comment) -> one field for each member of a datalist -> one tab for each member of a top-level datagroup -> one page (of a multipage widget, each page can be selected with a combo box) for each member of a datagroup inside a datagroup Supported types for field_value: - int, float, str, unicode, bool - colors: in Qt-compatible text form, i.e. in hex format or name (red,...) (automatically detected from a string) - list/tuple: * the first element will be the selected index (or value) * the other elements can be couples (key, value) or only values """ # Create a QApplication instance if no instance currently exists # (e.g. if the module is used directly from the interpreter) test_travis = os.environ.get('TEST_TRAVIS_WIDGETS', None) if test_travis is not None: from spyderlib.utils.qthelpers import qapplication _app = qapplication(test_time=1) elif QApplication.startingUp(): _app = QApplication([]) dialog = FormDialog(data, title, comment, icon, parent, apply) if dialog.exec_(): return dialog.get()
def tab_released(self, event): """Method called when a tab from a QTabBar has been released.""" QApplication.restoreOverrideCursor() self.moving = False
def run_c2p(self): """Prompt the user to load a combine archive, translate to Python, and display in a new window""" editorwindow = None #Used in editor.load processevents=True #Used in editor.load editor = self.main.editor basedir = getcwd() if CONF.get('workingdir', 'editor/open/browse_scriptdir'): c_fname = editor.get_current_filename() if c_fname is not None and c_fname != editor.TEMPFILE_PATH: basedir = os.path.dirname(c_fname) editor.emit(SIGNAL('redirect_stdio(bool)'), False) parent_widget = editor.get_current_editorstack() selectedfilter = '' filters = 'Combine archives (*.zip *.omex);;All files (*.*)' filenames, _selfilter = getopenfilenames(parent_widget, _("Open combine archive"), basedir, filters, selectedfilter=selectedfilter) editor.emit(SIGNAL('redirect_stdio(bool)'), True) if filenames: filenames = [os.path.normpath(fname) for fname in filenames] if CONF.get('workingdir', 'editor/open/auto_set_to_basedir'): directory = os.path.dirname(filenames[0]) editor.emit(SIGNAL("open_dir(QString)"), directory) else: #The file dialog box was closed without selecting a file. return focus_widget = QApplication.focusWidget() if editor.dockwidget and not editor.ismaximized and\ (not editor.dockwidget.isAncestorOf(focus_widget)\ and not isinstance(focus_widget, CodeEditor)): editor.dockwidget.setVisible(True) editor.dockwidget.setFocus() editor.dockwidget.raise_() def _convert(fname): fname = os.path.abspath(encoding.to_unicode_from_fs(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper()+fname[1:] return fname if hasattr(filenames, 'replaceInStrings'): # This is a QStringList instance (PyQt API #1), converting to list: filenames = list(filenames) if not isinstance(filenames, list): filenames = [_convert(filenames)] else: filenames = [_convert(fname) for fname in list(filenames)] for index, filename in enumerate(filenames): p = re.compile( '(.zip$|.omex$)') pythonfile = p.sub( '.py', filename) if (pythonfile == filename): pythonfile = filename + ".py" current_editor = editor.set_current_filename(pythonfile, editorwindow) if current_editor is not None: # -- TODO: Do not open an already opened file pass else: # -- Not an existing opened file: if not os.path.isfile(filename): continue # -- current_es = editor.get_current_editorstack(editorwindow) # Creating the editor widget in the first editorstack (the one # that can't be destroyed), then cloning this editor widget in # all other editorstacks: finfo, newname = self.load_and_translate(filename, pythonfile, editor) finfo.path = editor.main.get_spyder_pythonpath() editor._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(newname) #if (current_editor is not None): # editor.register_widget_shortcuts("Editor", current_editor) current_es.analyze_script() if (current_editor is not None): current_editor.clearFocus() current_editor.setFocus() current_editor.window().raise_() if processevents: QApplication.processEvents()
def copy_to_clipboard(self): from spyderlib.dependencies import status QApplication.clipboard().setText(status())
# silently ignored here. eintr = errno.WSAEINTR if os.name == 'nt' else errno.EINTR if e.args[0] == eintr: continue raise if not self._initialized: server_port = read_packet(conn) if isinstance(server_port, int): self._initialized = True self.initialized.emit(server_port) else: self.request_handled.emit(read_packet(conn)) if __name__ == '__main__': app = QApplication(sys.argv) plugin = PluginClient('jedi') def handle_return(value): print(value) if value['method'] == 'foo': app.quit() else: plugin.send(dict(method='foo')) def handle_errored(): print('errored') sys.exit(1) def start(): print('start')
def test(): """ """ app = QApplication([]) win = TestWindow() win.show() app.exec_()
def resize_to_contents(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.dataTable.resizeColumnsToContents() self.dataModel.fetch_more(columns=True) self.dataTable.resizeColumnsToContents() QApplication.restoreOverrideCursor()
def copy(self): """Copy text to clipboard""" cliptxt = self._sel_to_text( self.selectedIndexes() ) clipboard = QApplication.clipboard() clipboard.setText(cliptxt)
def main(): # Splash screen # ------------------------------------------------------------------------- # Start Qt Splash to inform the user of the current status app = qapplication() restarter = Restarter() resample = not IS_WINDOWS # Resampling SVG icon only on non-Windows platforms (see Issue 1314): icon = ima.icon('spyder', resample=resample) app.setWindowIcon(icon) restarter.set_splash_message(_('Closing Spyder')) # Get variables # Note: Variables defined in spyderlib\spyder.py 'restart()' method spyder_args = os.environ.pop('SPYDER_ARGS', None) pid = os.environ.pop('SPYDER_PID', None) is_bootstrap = os.environ.pop('SPYDER_IS_BOOTSTRAP', None) reset = os.environ.pop('SPYDER_RESET', None) # Get the spyder base folder based on this file spyder_folder = osp.split(osp.dirname(osp.abspath(__file__)))[0] if not any([spyder_args, pid, is_bootstrap, reset]): error = "This script can only be called from within a Spyder instance" raise RuntimeError(error) # Variables were stored as string literals in the environment, so to use # them we need to parse them in a safe manner. is_bootstrap = ast.literal_eval(is_bootstrap) pid = ast.literal_eval(pid) args = ast.literal_eval(spyder_args) reset = ast.literal_eval(reset) # Enforce the --new-instance flag when running spyder if '--new-instance' not in args: if is_bootstrap and '--' not in args: args = args + ['--', '--new-instance'] else: args.append('--new-instance') # Create the arguments needed for reseting if '--' in args: args_reset = ['--', '--reset'] else: args_reset = ['--reset'] # Arrange arguments to be passed to the restarter and reset subprocess args = ' '.join(args) args_reset = ' '.join(args_reset) # Get python excutable running this script python = sys.executable # Build the command if is_bootstrap: spyder = osp.join(spyder_folder, 'bootstrap.py') else: spyderlib = osp.join(spyder_folder, 'spyderlib') spyder = osp.join(spyderlib, 'start_app.py') command = '"{0}" "{1}" {2}'.format(python, spyder, args) # Adjust the command and/or arguments to subprocess depending on the OS shell = not IS_WINDOWS # Before launching a new Spyder instance we need to make sure that the # previous one has closed. We wait for a fixed and "reasonable" amount of # time and check, otherwise an error is launched wait_time = 90 if IS_WINDOWS else 30 # Seconds for counter in range(int(wait_time / SLEEP_TIME)): if not is_pid_running(pid): break time.sleep(SLEEP_TIME) # Throttling control QApplication.processEvents() # Needed to refresh the splash else: # The old spyder instance took too long to close and restart aborts restarter.launch_error_message(error_type=CLOSE_ERROR) env = os.environ.copy() # Reset Spyder (if required) # ------------------------------------------------------------------------- if reset: restarter.set_splash_message(_('Resetting Spyder to defaults')) command_reset = '"{0}" "{1}" {2}'.format(python, spyder, args_reset) try: p = subprocess.Popen(command_reset, shell=shell, env=env) except Exception as error: restarter.launch_error_message(error_type=RESET_ERROR, error=error) else: p.communicate() pid_reset = p.pid # Before launching a new Spyder instance we need to make sure that the # reset subprocess has closed. We wait for a fixed and "reasonable" # amount of time and check, otherwise an error is launched. wait_time = 20 # Seconds for counter in range(int(wait_time / SLEEP_TIME)): if not is_pid_running(pid_reset): break time.sleep(SLEEP_TIME) # Throttling control QApplication.processEvents() # Needed to refresh the splash else: # The reset subprocess took too long and it is killed try: p.kill() except OSError as error: restarter.launch_error_message(error_type=RESET_ERROR, error=error) else: restarter.launch_error_message(error_type=RESET_ERROR) # Restart # ------------------------------------------------------------------------- restarter.set_splash_message(_('Restarting')) try: subprocess.Popen(command, shell=shell, env=env) except Exception as error: restarter.launch_error_message(error_type=RESTART_ERROR, error=error)
def event(self, event): if event.type() == QEvent.FileOpen: fname = str(event.file()) self.open_external_file.emit(fname) return QApplication.event(self, event)
def event(self, event): if event.type() == QEvent.FileOpen: fname = str(event.file()) self.emit(SIGNAL('open_external_file(QString)'), fname) return QApplication.event(self, event)
def copy(self): """ Reimplement Qt method Copy text to clipboard with correct EOL chars """ QApplication.clipboard().setText(self.get_selected_text())
def write_output(self): self.shell.write(self.get_stdout(), flush=True) QApplication.processEvents()
def show_list(self, completion_list, automatic=True): if len(completion_list) == 1 and not automatic: self.textedit.insert_completion(completion_list[0]) return self.completion_list = completion_list self.clear() self.addItems(completion_list) self.setCurrentRow(0) QApplication.processEvents(QEventLoop.ExcludeUserInputEvents) self.show() self.setFocus() self.raise_() # Retrieving current screen height desktop = QApplication.desktop() srect = desktop.availableGeometry(desktop.screenNumber(self)) screen_right = srect.right() screen_bottom = srect.bottom() point = self.textedit.cursorRect().bottomRight() point.setX(point.x() + self.textedit.get_linenumberarea_width()) point = self.textedit.mapToGlobal(point) # Computing completion widget and its parent right positions comp_right = point.x() + self.width() ancestor = self.parent() if ancestor is None: anc_right = screen_right else: anc_right = min([ancestor.x() + ancestor.width(), screen_right]) # Moving completion widget to the left # if there is not enough space to the right if comp_right > anc_right: point.setX(point.x() - self.width()) # Computing completion widget and its parent bottom positions comp_bottom = point.y() + self.height() ancestor = self.parent() if ancestor is None: anc_bottom = screen_bottom else: anc_bottom = min([ancestor.y() + ancestor.height(), screen_bottom]) # Moving completion widget above if there is not enough space below x_position = point.x() if comp_bottom > anc_bottom: point = self.textedit.cursorRect().topRight() point = self.textedit.mapToGlobal(point) point.setX(x_position) point.setY(point.y() - self.height()) if ancestor is not None: # Useful only if we set parent to 'ancestor' in __init__ point = ancestor.mapFromGlobal(point) self.move(point) if to_text_string(self.textedit.completion_text): # When initialized, if completion text is not empty, we need # to update the displayed list: self.update_current()
def initialize_continued(self): """Load home page""" self.go_home() QApplication.restoreOverrideCursor()
def paste(self): """Reimplement Qt method""" if self.has_selected_text(): self.remove_selected_text() self.insert_text(QApplication.clipboard().text())
def initialize(self): """Start pydoc server""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() self.start_server()
def leaveEvent(self, event): """If cursor has not been restored yet, do it now""" if self.__cursor_changed: QApplication.restoreOverrideCursor() self.__cursor_changed = False self.QT_CLASS.leaveEvent(self, event)
def __init__(self, *args): QApplication.__init__(self, *args)
def import_data(self, filenames=None): """Import data from text file""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question( self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?") % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) if self.is_internal_shell: self.editor.import_from_string(text) else: base_name = osp.basename(self.filename) editor = ImportWizard( self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() monitor_set_global(self._get_sock(), var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() if self.is_internal_shell: namespace, error_message = load_func(self.filename) interpreter = self.shellwidget.interpreter for key in list(namespace.keys()): new_key = fix_reference_name( key, blacklist=list(interpreter.namespace.keys())) if new_key != key: namespace[new_key] = namespace.pop(key) if error_message is None: interpreter.namespace.update(namespace) else: error_message = monitor_load_globals( self._get_sock(), self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical( self, title, _("<b>Unable to load '%s'</b>" "<br><br>Error message:<br>%s") % (self.filename, error_message)) self.refresh_table()