def test_builtin_shift_del_and_ins(editor_bot): """ Test that the builtin key sequences Ctrl+Ins, Shit+Del and Shift+Ins result in copy, cut and paste actions in Windows and Linux. Regression test for issue #5035, #4947, and #5973. """ editorstack, qtbot = editor_bot editor = editorstack.get_current_editor() QApplication.clipboard().clear() # Select the first line of the editor. qtbot.keyClick(editor, Qt.Key_End, modifier=Qt.ShiftModifier) assert editor.get_selected_text() == 'Line1' # Copy the selection with Ctrl+Ins. qtbot.keyClick(editor, Qt.Key_Insert, modifier=Qt.ControlModifier) assert QApplication.clipboard().text() == 'Line1' # Paste the copied text at the end of the line with Shift+Ins. qtbot.keyClick(editor, Qt.Key_End) qtbot.keyClick(editor, Qt.Key_Insert, modifier=Qt.ShiftModifier) assert editor.toPlainText() == 'Line1Line1\nLine2\nLine3\nLine4\n' # Select the second line in the editor again. qtbot.keyClick(editor, Qt.Key_Home, modifier=Qt.ShiftModifier) assert editor.get_selected_text() == 'Line1Line1' # Cut the selection with Shift+Del. qtbot.keyClick(editor, Qt.Key_Delete, modifier=Qt.ShiftModifier) assert QApplication.clipboard().text() == 'Line1Line1' assert editor.toPlainText() == '\nLine2\nLine3\nLine4\n'
def copy(self): """ Reimplement Qt method Copy text to clipboard with correct EOL chars """ if self.get_selected_text(): QApplication.clipboard().setText(self.get_selected_text())
def test_copy_cut_paste_shortcuts(editor_bot): """ Test that the copy, cut, and paste keyboard shortcuts are working as expected with the default Spyder keybindings. """ editorstack, qtbot = editor_bot editor = editorstack.get_current_editor() QApplication.clipboard().clear() # Select and Copy the first line in the editor. qtbot.keyClick(editor, Qt.Key_End, modifier=Qt.ShiftModifier) assert editor.get_selected_text() == 'Line1' qtbot.keyClick(editor, Qt.Key_C, modifier=Qt.ControlModifier) assert QApplication.clipboard().text() == 'Line1' # Paste the selected text. qtbot.keyClick(editor, Qt.Key_Home) qtbot.keyClick(editor, Qt.Key_V, modifier=Qt.ControlModifier) assert editor.toPlainText() == 'Line1Line1\nLine2\nLine3\nLine4\n' # Select and Cut the first line in the editor. qtbot.keyClick(editor, Qt.Key_Home) qtbot.keyClick(editor, Qt.Key_End, modifier=Qt.ShiftModifier) assert editor.get_selected_text() == 'Line1Line1' qtbot.keyClick(editor, Qt.Key_X, modifier=Qt.ControlModifier) assert QApplication.clipboard().text() == 'Line1Line1' assert editor.toPlainText() == '\nLine2\nLine3\nLine4\n'
def yDOLLAR(self, repeat): editor = self._widget.editor() cursor = editor.textCursor() cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor, repeat) text = cursor.selectedText() QApplication.clipboard().setText(text)
def yw(self, repeat): editor = self._widget.editor() cursor = editor.textCursor() cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor, repeat - 1) cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) text = cursor.selectedText() QApplication.clipboard().setText(text)
def test_copy_to_clipboard(self): self.widget.loadFunction('name=LinearBackground,A0=0,A1=0') yield self.start_setup_menu() yield self.start_manage_setup() QApplication.clipboard().clear() self.trigger_action('action_CopyToClipboard') yield self.wait_for_true(lambda: QApplication.clipboard().text() != '') self.assertEqual(QApplication.clipboard().text(), 'name=LinearBackground,A0=0,A1=0')
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 _submit_to_github(self): """Action to take when pressing the submit button.""" # Get reference to the main window if self.parent() is not None: if getattr(self.parent(), 'main', False): # This covers the case when the dialog is attached # to the internal console main = self.parent().main else: # Else the dialog is attached to the main window # directly main = self.parent() else: main = None # Getting description and traceback title = self.title.text() description = self.input_description.toPlainText() traceback = self.error_traceback[:-1] # Remove last EOL # Render issue if main is not None: issue_text = main.render_issue(description=description, traceback=traceback) else: issue_text = description try: if main is None: org = 'ccordoba12' else: org = 'spyder-ide' github_backend = GithubBackend(org, 'spyder', parent_widget=main) github_report = github_backend.send_report(title, issue_text) if github_report: self.close() except Exception: ret = QMessageBox.question( self, _('Error'), _("An error occurred while trying to send the issue to " "Github automatically. Would you like to open it " "manually?<br><br>" "If so, please make sure to paste your clipboard " "into the issue report box that will appear in a new " "browser tab before clicking <i>Submit</i> on that " "page.")) if ret in [QMessageBox.Yes, QMessageBox.Ok]: QApplication.clipboard().setText(issue_text) issue_body = ( " \n<!--- *** BEFORE SUBMITTING: PASTE CLIPBOARD HERE " "TO COMPLETE YOUR REPORT *** ---!>\n") if main is not None: main.report_issue(body=issue_body, title=title, open_webpage=True) else: pass
def copy_figure(self): """Copy figure to clipboard.""" if self.fmt in ['image/png', 'image/jpeg']: qpixmap = QPixmap() qpixmap.loadFromData(self.fig, self.fmt.upper()) QApplication.clipboard().setImage(qpixmap.toImage()) elif self.fmt == 'image/svg+xml': svg_to_clipboard(self.fig) else: return self.blink_figure()
def test_paste_from_clipboard(self): assert (isinstance(self, TestFunctionBrowser)) browser = self.widget browser.setFunction('name=FlatBackground;name=FlatBackground,A0=1') view = browser.view() user = BrowserUser(browser) QApplication.clipboard().setText('name=LinearBackground,A0=5,A1=10') pos = view.getVisualRectFunctionProperty('').center() tree = view.treeWidget().viewport() yield self.show_context_menu(tree, pos, pause=0) yield self.mouse_trigger_action('paste_from_clipboard', pause=0) fun = self.get_fit_function() self.assertEqual(fun.name, 'LinearBackground') self.assertEqual(user.structure_changed.call_count, 1)
def y(self, repeat): """Copy selected line.""" editor = self._widget.editor() selection = editor.get_extra_selections('vim_visual')[0] cursor = selection.cursor text = cursor.selectedText() QApplication.clipboard().setText(text) if self.visual_mode == 'char': self._update_selection_type('char') elif self.visual_mode == 'line': self._update_selection_type('line') else: self._update_selection_type('block') editor.setTextCursor(self._prev_cursor) self._move_cursor(QTextCursor.StartOfLine) self.exit_visual_mode()
def P(self, repeat): """Paste line above current line, paste characters before cursor.""" editor = self._widget.editor() cursor = editor.textCursor() text = QApplication.clipboard().text() lines = text.splitlines() if self._widget.selection_type[1] == 'line': text *= repeat startBlockPosition = cursor.block().position() cursor.movePosition(QTextCursor.StartOfLine) cursor.insertText(text) cursor.setPosition(startBlockPosition) if lines[0].strip(): cursor.movePosition(QTextCursor.NextWord) editor.setTextCursor(cursor) elif self._widget.selection_type[1] == 'char': startPosition = cursor.position() for i in range(repeat): editor.paste() if len(lines) > 1: cursor.setPosition(startPosition) editor.setTextCursor(cursor) else: # TODO: implement pasting block text after implementing visual mode pass self._widget.update_vim_cursor()
def closeEvent(self, *args, **kwargs): self.save_settings() # Enable paste of clipboard after termination clipboard = QApplication.clipboard() event = QEvent(QEvent.Clipboard) QApplication.sendEvent(clipboard, event) return QMainWindow.closeEvent(self, *args, **kwargs)
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 copy_files_clipboard(create_folders_files): """Fixture to copy files/folders into the clipboard""" file_paths = create_folders_files[0] file_content = QMimeData() file_content.setUrls([QUrl.fromLocalFile(fname) for fname in file_paths]) cb = QApplication.clipboard() cb.setMimeData(file_content, mode=cb.Clipboard) return file_paths
def explorer_with_files(qtbot, create_folders_files, request): """Setup Project/File Explorer widget.""" cb = QApplication.clipboard() paths, project_dir, destination_dir, top_folder = create_folders_files explorer_orig = request.param(directory=project_dir) explorer_dest = request.param(directory=destination_dir) qtbot.addWidget(explorer_orig) qtbot.addWidget(explorer_dest) return explorer_orig, explorer_dest, paths, top_folder, cb
def test_paste_text(code_editor_bot, text, line_ending_char): """Test pasting text into the editor.""" editor = code_editor_bot[0] text = text.replace(osp.os.linesep, line_ending_char) cb = QApplication.clipboard() cb.setText(text, mode=cb.Clipboard) cursor = editor.textCursor() cursor.movePosition(QTextCursor.Start) editor.setTextCursor(cursor) editor.paste() for line_no, txt in enumerate(text.splitlines()): assert editor.get_text_line(line_no) == txt
def __init__(self, editor_widget): self.editor_widget = editor_widget QLineEdit.__init__(self, editor_widget) # Build widget self.commandline = VimLineEdit(self) self.commandline.textChanged.connect(self.on_text_changed) self.commandline.returnPressed.connect(self.on_return) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) hlayout = QHBoxLayout() hlayout.addWidget(QLabel("Vim:")) hlayout.addWidget(self.commandline) hlayout.setContentsMargins(1, 1, 1, 1) self.setLayout(hlayout) self.selection_type = (int(time()), "char") QApplication.clipboard().dataChanged.connect(self.on_copy) # Initialize available commands self.vim_keys = VimKeys(self) self.vim_commands = VimCommands(self)
def mousePressEvent(self, event): """Reimplement Qt method""" # mouse buttons for forward and backward navigation if event.button() == Qt.XButton1: self.sig_prev_cursor.emit() elif event.button() == Qt.XButton2: self.sig_next_cursor.emit() if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() 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 spyder-ide/spyder#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 _submit_to_github(self): """Action to take when pressing the submit button.""" # Getting description and traceback title = self.title.text() description = self.input_description.toPlainText() traceback = self.error_traceback[:-1] # Remove last EOL # Render issue issue_text = self.render_issue( description=description, traceback=traceback, include_env=self.include_env.isChecked()) try: org = self._github_org if not self._testing else 'ccordoba12' repo = self._github_repo github_backend = GithubBackend(org, repo, parent_widget=self) github_report = github_backend.send_report(title, issue_text) if github_report: self.close() except Exception: ret = QMessageBox.question( self, _('Error'), _("An error occurred while trying to send the issue to " "Github automatically. Would you like to open it " "manually?<br><br>" "If so, please make sure to paste your clipboard " "into the issue report box that will appear in a new " "browser tab before clicking <i>Submit</i> on that " "page."), ) if ret in [QMessageBox.Yes, QMessageBox.Ok]: QApplication.clipboard().setText(issue_text) issue_body = ( " \n<!--- *** BEFORE SUBMITTING: PASTE CLIPBOARD HERE " "TO COMPLETE YOUR REPORT *** ---!>\n") self.open_web_report(body=issue_body, title=title)
def test_terminal_paste(setup_terminal, qtbot_module): """Test the paste action in the terminal.""" terminal = setup_terminal qtbot_module.waitUntil(lambda: terminal.get_widget().server_is_ready(), timeout=TERM_UP) qtbot_module.wait(1000) term = terminal.get_widget().get_current_term() port = terminal.get_widget().port status_code = requests.get('http://127.0.0.1:{}'.format(port)).status_code assert status_code == 200 separator = os.linesep expected = ['prueba'] QApplication.clipboard().clear() QApplication.clipboard().setText(separator.join(expected)) term.view.paste() qtbot_module.waitUntil(lambda: check_paste(term, expected), timeout=TERM_UP) expected = ['this', 'a', 'test'] QApplication.clipboard().setText(separator.join(expected)) term.view.paste() qtbot_module.waitUntil(lambda: check_paste(term, expected), timeout=TERM_UP)
def test_yw_command(vim_bot): """Copy word.""" main, editor_stack, editor, vim, qtbot = vim_bot editor.stdkey_backspace() editor.go_to_line(3) editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) cmd_line = vim.get_focus_widget() # qtbot.keyClicks(cmd_line, 'v') qtbot.keyClicks(cmd_line, 'yw') clipboard = QApplication.clipboard().text() # editor.moveCursor(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) # new_line, new_col = editor.get_cursor_line_column() assert clipboard == 'line'
def copyCells(self): indices = self._content.data_set_table.selectedIndexes() if len(indices) == 0: return col_count = self._content.data_set_table.columnCount() rows = [] for r in indices: if r.row() not in rows: rows.append(r.row()) selected_text = "" for row in rows: for i in range(col_count): data = self._content.data_set_table.item(row, i) if data is not None: selected_text += str(data.text()) if i < col_count - 1: selected_text += '\t' selected_text += '\n' QApplication.clipboard().setText(selected_text)
def _submit_to_github(self): """Action to take when pressing the submit button.""" main = self.parent().main # Getting description and traceback description = self.input_description.toPlainText() traceback = self.error_traceback[:-1] # Remove last eol # Render issue issue_text = main.render_issue(description=description, traceback=traceback) # Copy issue to clipboard QApplication.clipboard().setText(issue_text) # Submit issue to Github issue_body=("<!--- " "Please paste the contents of your clipboard " "below to complete reporting your problem. " "--->\n\n") main.report_issue(body=issue_body, title="Automatic error report")
def test_yw_command(vim_bot): """Copy word.""" main, editor_stack, editor, vim, qtbot = vim_bot editor.stdkey_backspace() editor.go_to_line(3) editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) cmd_line = vim.get_focus_widget() # qtbot.keyClicks(cmd_line, 'v') qtbot.keyClicks(cmd_line, 'yw') clipboard = QApplication.clipboard().text() # editor.moveCursor(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) # new_line, new_col = editor.get_cursor_line_column() assert clipboard == 'line'
def _copy(self): ''' Copies all of the selected items to the clipboard. ''' # Copy the urls of the selected files to the clipboard. filePath = self._model.filePath urls = [QUrl.fromLocalFile(filePath(index)) for index in self._view.selectedIndexes()] mime_data = QMimeData() mime_data.setUrls(urls) clipboard = QApplication.clipboard() clipboard.setMimeData(mime_data)
def on_copy(self): """ copy file or dir , save path in pasteAction data. :return: """ path = self.get_current_file_path() self.pasteAction.setEnabled(True) self.pasteAction.setData(path) data = QMimeData() data.setUrls([QUrl.fromLocalFile(path)]) # 复制到系统剪贴板 clip = QApplication.clipboard() clip.setMimeData(data)
def __init__(self, editor_widget, main): """Main widget constructor.""" self.editor_widget = editor_widget self.main = main QLineEdit.__init__(self, editor_widget) # Build widget self.commandline = VimLineEdit(self) self.commandline.textChanged.connect(self.on_text_changed) self.commandline.returnPressed.connect(self.on_return) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) hlayout = QHBoxLayout() hlayout.addWidget(QLabel("Vim:")) hlayout.addWidget(self.commandline) hlayout.setContentsMargins(5, 0, 0, 5) self.setLayout(hlayout) self.selection_type = (int(time()), "char") QApplication.clipboard().dataChanged.connect(self.on_copy) # Initialize available commands self.vim_keys = VimKeys(self) self.vim_commands = VimCommands(self)
def test_ydollar_command(vim_bot): """Copy until end of line.""" main, editor_stack, editor, vim, qtbot = vim_bot editor.stdkey_backspace() editor.go_to_line(3) editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) qtbot.keyPress(editor, Qt.Key_Right) qtbot.keyPress(editor, Qt.Key_Right) cmd_line = vim.get_focus_widget() # qtbot.keyClicks(cmd_line, 'v') qtbot.keyClicks(cmd_line, 'y$') clipboard = QApplication.clipboard().text() # editor.moveCursor(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) # new_line, new_col = editor.get_cursor_line_column() assert clipboard == 'ne 2'
def test_ydollar_command(vim_bot): """Copy until end of line.""" main, editor_stack, editor, vim, qtbot = vim_bot editor.stdkey_backspace() editor.go_to_line(3) editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) qtbot.keyPress(editor, Qt.Key_Right) qtbot.keyPress(editor, Qt.Key_Right) cmd_line = vim.get_focus_widget() # qtbot.keyClicks(cmd_line, 'v') qtbot.keyClicks(cmd_line, 'y$') clipboard = QApplication.clipboard().text() # editor.moveCursor(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) # new_line, new_col = editor.get_cursor_line_column() assert clipboard == 'ne 2'
def test_copy_png_to_clipboard(figbrowser, tmpdir): """ Test copying png figures to the clipboard. """ figs = add_figures_to_browser(figbrowser, 3, tmpdir, 'image/png') clipboard = QApplication.clipboard() # Copy the current figure (last thumbnail) to the clipboard. figbrowser.copy_figure() assert clipboard.image() == png_to_qimage(figs[-1]) # Copy the first thumbnail to the clipboard. figbrowser.go_next_thumbnail() figbrowser.copy_figure() assert clipboard.image() == png_to_qimage(figs[0])
def test_copy_svg_to_clipboard(figbrowser, tmpdir): """ Test copying svg figures to the clipboard. """ figs = add_figures_to_browser(figbrowser, 3, tmpdir, 'image/svg+xml') clipboard = QApplication.clipboard() # Copy the current figure (last thumbnail) to the clipboard. figbrowser.copy_figure() assert clipboard.mimeData().data('image/svg+xml') == figs[-1] # Copy the first thumbnail to the clipboard. figbrowser.go_next_thumbnail() figbrowser.copy_figure() assert clipboard.mimeData().data('image/svg+xml') == figs[0]
def test_copy_svg_to_clipboard(figbrowser, tmpdir): """ Test copying svg figures to the clipboard. """ figs = add_figures_to_browser(figbrowser, 3, tmpdir, 'image/svg+xml') clipboard = QApplication.clipboard() # Copy the current figure (last thumbnail) to the clipboard. figbrowser.copy_figure() assert clipboard.mimeData().data('image/svg+xml') == figs[-1] # Copy the first thumbnail to the clipboard. figbrowser.go_next_thumbnail() figbrowser.copy_figure() assert clipboard.mimeData().data('image/svg+xml') == figs[0]
def test_copy_png_to_clipboard(figbrowser, tmpdir): """ Test copying png figures to the clipboard. """ figs = add_figures_to_browser(figbrowser, 3, tmpdir, 'image/png') clipboard = QApplication.clipboard() # Copy the current figure (last thumbnail) to the clipboard. figbrowser.copy_figure() assert clipboard.image() == png_to_qimage(figs[-1]) # Copy the first thumbnail to the clipboard. figbrowser.go_next_thumbnail() figbrowser.copy_figure() assert clipboard.image() == png_to_qimage(figs[0])
def test_gg_command_char_mode(vim_bot): """Select from first line character.""" main, editor_stack, editor, vim, qtbot = vim_bot editor.stdkey_backspace() editor.go_to_line(3) editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) qtbot.keyPress(editor, Qt.Key_Right) qtbot.keyPress(editor, Qt.Key_Right) cmd_line = vim.get_focus_widget() qtbot.keyClicks(cmd_line, 'v') qtbot.keyClicks(cmd_line, 'gg') qtbot.keyClicks(cmd_line, 'y') clipboard = QApplication.clipboard().text() # editor.moveCursor(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) # new_line, new_col = editor.get_cursor_line_column() assert clipboard == u' 123\u2029line 1\u2029li'
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 test_gg_command_char_mode(vim_bot): """Select from first line character.""" main, editor_stack, editor, vim, qtbot = vim_bot editor.stdkey_backspace() editor.go_to_line(3) editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) qtbot.keyPress(editor, Qt.Key_Right) qtbot.keyPress(editor, Qt.Key_Right) cmd_line = vim.get_focus_widget() qtbot.keyClicks(cmd_line, 'v') qtbot.keyClicks(cmd_line, 'gg') qtbot.keyClicks(cmd_line, 'y') clipboard = QApplication.clipboard().text() # editor.moveCursor(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) # new_line, new_col = editor.get_cursor_line_column() assert clipboard == u' 123\u2029line 1\u2029li'
def keyPressEvent(self, event): """Override Qt method.""" key = event.key() # Display a copy menu in case the widget is disabled. if event.matches(QKeySequence.Paste): clipboard = QApplication.clipboard() text = clipboard.text() if self.VALID_RE.exactMatch(text): self.setText(text) return else: if key in [Qt.Key_Return, Qt.Key_Enter]: self.sig_return_pressed.emit() elif key in [Qt.Key_Escape]: self.sig_escape_pressed.emit() super(LineEditEnvironment, self).keyPressEvent(event)
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 copy_coordinates_to_clipboard(session): """ Copy coordinates to clipboard so user can paste them elsewhere :param session: :return: """ coords_status = False lay = session.application.current_tab for w in lay.cube_views: civ = w._widget if civ.is_mouse_over: coords_status = civ.get_coords() break if coords_status: cb = QApplication.clipboard() cb.clear(mode=cb.Clipboard) cb.setText(coords_status, mode=cb.Clipboard)
def copy_coordinates_to_clipboard(session): """ Copy coordinates to clipboard so user can paste them elsewhere :param session: :return: """ coords_status = False lay = session.application.current_tab for w in lay.all_views: civ = w._widget if civ.is_mouse_over: coords_status = civ.get_coords() break if coords_status: cb = QApplication.clipboard() cb.clear(mode=cb.Clipboard) cb.setText(coords_status, mode=cb.Clipboard)
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 df = self.model().df obj = df.iloc[slice(row_min, row_max + 1), slice(col_min, col_max + 1)] 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 __init__(self, parent=None): super(FileSystemTable, self).__init__(parent) self._table_type = TableType.Local self._hidden_columns = '' self._name_columns_width = 0 self._fixed_name_column = False # This prevents doing unneeded initialization # when QtDesginer loads the plugin. if parent is None: return self.parent = parent self.path_data = dict() self.selected_row = None self.clipboard = QApplication.clipboard() self.model = QtpyVCPQFileSystemModel() self.model.setReadOnly(True) self.model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot | QDir.AllEntries) self.setModel(self.model) self.verticalHeader().hide() self.horizontalHeader().setStretchLastSection(True) self.setAlternatingRowColors(True) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.selection_model = self.selectionModel() self.selection_model.selectionChanged.connect(self.onSelectionChanged) # open selected item on double click or enter pressed self.activated.connect(self.openSelectedItem) self.info = Info() self.nc_file_editor = self.info.getEditor() self.nc_file_dir = self.info.getProgramPrefix() self.nc_file_exts = self.info.getProgramExtentions() self.setRootPath(self.nc_file_dir) self.model.rootPathChanged.connect(self.onRootPathChanged)
def copy(self): """Copy selection as text to clipboard""" raw_data, axes_names, vlabels, hlabels = self._selection_data() data = self.data_adapter.selection_to_chain(raw_data, axes_names, vlabels, hlabels) if data is None: return # np.savetxt make things more complicated, especially on py3 # XXX: why don't we use repr for everything? def vrepr(v): if isinstance(v, float): return repr(v) else: return str(v) text = '\n'.join('\t'.join(vrepr(v) for v in line) for line in data) clipboard = QApplication.clipboard() clipboard.setText(text)
def keyPressEvent(self, event): ctrl = event.modifiers() & Qt.ControlModifier != 0 if not self.is_running or self.textCursor().hasSelection(): if event.key() == Qt.Key_C and ctrl: self.copy() return propagate_to_parent = True delete = event.key() in [Qt.Key_Backspace, Qt.Key_Delete] if delete and not self._usr_buffer: return if event.key() == Qt.Key_V and ctrl: # Paste to usr buffer text = QApplication.clipboard().text() self._usr_buffer += text self.setTextColor(self._stdin_col) if self._mask_user_input: text = len(text) * '*' self.insertPlainText(text) return if event.key() in [Qt.Key_Return, Qt.Key_Enter]: # send the user input to the child process if sys.platform == 'win32': self._usr_buffer += "\r" self._usr_buffer += "\n" self.process.write(self.get_user_buffer_as_bytes()) self._usr_buffer = "" else: if not delete and len(event.text()): txt = event.text() self._usr_buffer += txt if self._mask_user_input: txt = '*' self.setTextColor(self._stdin_col) self.insertPlainText(txt) propagate_to_parent = False elif delete: self._usr_buffer = self._usr_buffer[:len(self._usr_buffer) - 1] # text is inserted here, the text color must be defined before this # line if propagate_to_parent: super(InteractiveConsole, self).keyPressEvent(event) self.setTextColor(self._stdout_col)
def on_paste(self): """ Paste file or dir in pasteAction data :return: """ from pmgwidgets import copy_paste path = self.get_current_file_path() target_dir_name = path if os.path.isdir(path) else os.path.dirname( path) url: QUrl = None mimedata = QApplication.clipboard().mimeData(mode=QClipboard.Clipboard) print(mimedata) urls: List[QUrl] = mimedata.urls() for url in urls: source_path = url.toLocalFile() # self.pasteAction.data() # File if os.path.isfile(source_path): source_file_name = os.path.basename(source_path) # if exist ,rename to copy_xxx if os.path.isfile( os.path.join(target_dir_name, source_file_name)): target_file_name = "copy_{0}".format(source_file_name) else: target_file_name = source_file_name target_path = os.path.join(target_dir_name, target_file_name) # Directory else: last_dir_name = os.path.split(source_path)[-1] # if exist , rename dir copy_xxxx if os.path.isdir(os.path.join(target_dir_name, last_dir_name)): target_name = "copy_{0}".format(last_dir_name) else: target_name = last_dir_name target_path = os.path.join(target_dir_name, target_name) copy_succ = copy_paste(source_path, target_path) if not copy_succ: QMessageBox.critical(self, self.tr('Error'), self.tr('Copy File or Directory Error.')) else: self.set_item_focus(target_path)
def show_address_tooltip(self, event): """ Show the PyDMTooltip and copy address to clipboard This is intended to replicate the behavior of the "middle click" from EDM. If the QWidget does not have a valid PyDMChannel nothing will be displayed """ channels_method = getattr(self, 'channels', None) if channels_method is None: return channels = channels_method() if not channels: logger.debug('Widget has no channels to display tooltip') return addrs = [] no_proto_addrs = [] for ch in channels: addr = ch.address if not addr: continue addrs.append(addr) no_proto_addrs.append(remove_protocol(addr)) tooltip = os.linesep.join(addrs) clipboard_text = " ".join(no_proto_addrs) QToolTip.showText(event.globalPos(), tooltip) # If the address has a protocol, strip it out before putting it on the # clipboard. clipboard = QApplication.clipboard() mode = clipboard.Clipboard if platform.system() == 'Linux': # Mode Selection is only valid for X11. mode = clipboard.Selection clipboard.setText(clipboard_text, mode=mode) event = QEvent(QEvent.Clipboard) self.app.sendEvent(clipboard, event)
def show_address_tooltip(self, event): """ Show the PyDMTooltip and copy address to clipboard This is intended to replicate the behavior of the "middle click" from EDM. If the QWidget does not have a valid PyDMChannel nothing will be displayed """ if not len(self._channels): logger.warning("Object %r has no PyDM Channels", self) return addr = self.channels()[0].address QToolTip.showText(event.globalPos(), addr) # If the address has a protocol, strip it out before putting it on the # clipboard. copy_text = remove_protocol(addr) clipboard = QApplication.clipboard() clipboard.setText(copy_text) event = QEvent(QEvent.Clipboard) self.app.sendEvent(clipboard, event)
def show_address_tooltip(self, event): """ Show the PyDMTooltip and copy address to clipboard This is intended to replicate the behavior of the "middle click" from EDM. If the QWidget does not have a valid PyDMChannel nothing will be displayed """ if not len(self._channels): logger.warning("Object %r has no PyDM Channels", self) return addr = self.channels()[0].address QToolTip.showText(event.globalPos(), addr) # If the address has a protocol, strip it out before putting it on the # clipboard. copy_text = remove_protocol(addr) clipboard = QApplication.clipboard() clipboard.setText(copy_text) event = QEvent(QEvent.Clipboard) self.app.sendEvent(clipboard, event)
def __init__(self, path): super().__init__() self.path_set = settings.path(self, path) uic.loadUi(str(self.path['main']/'UI'/'main_window.ui'), self) self.splitter.moveSplitter(0, 1) # moves splitter 0 as close to 1 as possible self.setWindowIcon(QtGui.QIcon(str(self.path['main']/'UI'/'graphics'/'main_icon.png'))) # Start threadpools self.threadpool = QtCore.QThreadPool() self.threadpool.setMaxThreadCount(2) # Sets thread count to 1 (1 for gui - this is implicit, 1 for calc) # Set selected tabs for tab_widget in [self.option_tab_widget, self.plot_tab_widget]: tab_widget.setCurrentIndex(0) # Set Clipboard self.clipboard = QApplication.clipboard() self.var = {'reactor': {'t_unit_conv': 1}} self.SIM = mech_fcns.Simulation_Result() self.mech_loaded = False self.convert_units = convert_units.Convert_Units(self) self.series = settings.series(self) self.sim_explorer = sim_explorer_widget.SIM_Explorer_Widgets(self) self.plot = plot(self) options_panel_widgets.Initialize(self) self.mech = mech_fcns.Chemical_Mechanism() # Setup save sim self.save_sim = save_widget.Save_Dialog(self) self.save_sim_button.clicked.connect(self.save_sim.execute) self.action_Save.triggered.connect(self.save_sim.execute) # Initialize Settings self.initialize_settings() self.show()
def qt_clipboard_monitor(func=None, info=1): """ qt实现的剪切板监控器 感觉这个组件还有很多可以扩展的,比如设置可以退出的快捷键 """ import pyperclip last_str = '' if func is None: func = lambda s: s def on_clipboard_change(): # 1 数据内容一样则跳过不处理,表示很可能是该函数调用pyperclip.copy(s)产生的重复响应 nonlocal last_str s0 = pyperclip.paste() s0 = s0.replace('\r\n', '\n') if s0 == last_str: return else: last_str = s0 # 2 处理函数 s1 = func(s0) if s1 != s0: if info: print('【处理前】', time.strftime('%H:%M:%S')) print(s0) print('【处理后】') print(s1) print() pyperclip.copy(s1) app = QApplication([]) clipboard = app.clipboard() clipboard.dataChanged.connect(on_clipboard_change) app.exec_()
def __structure_list_context_menu(self, point) -> None: """Context menu for the type synthesis results.""" index = self.structure_list.currentIndex().row() self.to_collection.setEnabled(index > -1) self.copy_edges.setEnabled(index > -1) self.copy_image.setEnabled(index > -1) action = self.pop_menu_topo.exec_(self.structure_list.mapToGlobal(point)) if not action: return clipboard = QApplication.clipboard() if action == self.to_collection: self.add_collection(self.answer[index].edges) elif action == self.copy_edges: clipboard.setText(str(self.answer[index].edges)) elif action == self.copy_image: # Turn the transparent background to white image1 = self.__atlas_image() image2 = QImage(image1.size(), image1.format()) image2.fill(Qt.white) painter = QPainter(image2) painter.drawImage(QPointF(0, 0), image1) painter.end() clipboard.setPixmap(QPixmap.fromImage(image2))
def paste(self): bounds = self.view_data._selection_bounds() if bounds is None: return row_min, row_max, col_min, col_max = bounds clipboard = QApplication.clipboard() text = str(clipboard.text()) list_data = [line.split('\t') for line in text.splitlines()] try: # take the first cell which contains '\' pos_last = next(i for i, v in enumerate(list_data[0]) if '\\' in v) except StopIteration: # if there isn't any, assume 1d array pos_last = 0 if pos_last or '\\' in list_data[0][0]: # ndim > 1 list_data = [line[pos_last + 1:] for line in list_data[1:]] elif len(list_data) == 2 and list_data[1][0] == '': # ndim == 1 list_data = [list_data[1][1:]] new_data = np.array(list_data) if new_data.shape[0] > 1: row_max = row_min + new_data.shape[0] if new_data.shape[1] > 1: col_max = col_min + new_data.shape[1] result = self.model_data.set_values(row_min, col_min, row_max, col_max, new_data) if result is None: return # TODO: when pasting near bottom/right boundaries and size of # new_data exceeds destination size, we should either have an error # or clip new_data self.view_data.selectionModel().select( QItemSelection(*result), QItemSelectionModel.ClearAndSelect)
def show_init_args(self): text = ('WaitingSpinner(\n' ' parent,\n' ' roundness={}, opacity={},\n' ' fade={}, radius={}, lines={},\n' ' line_length={}, line_width={},\n' ' speed={}, color={}\n' ')\n').format(self.sb_roundness.value(), self.sb_opacity.value(), self.sb_fadeperc.value(), self.sb_inner_radius.value(), self.sb_lines.value(), self.sb_line_length.value(), self.sb_line_width.value(), self.sb_rev_s.value(), self.spinner.color.getRgb()[:3]) msg_box = QMessageBox(text=text) msg_box.setWindowTitle('Text was copied to clipboard') cb = QApplication.clipboard() cb.clear(mode=cb.Clipboard) cb.setText(text, mode=cb.Clipboard) print(text) msg_box.exec_()
def mousePressEvent(self, event): """Reimplement Qt method""" if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() 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 __copy_expr(self) -> None: """Copy the expression.""" string = self.edges_text.text() if string: QApplication.clipboard().setText(string) self.edges_text.selectAll()
def __copy_expr(self) -> None: """Copy profile expression.""" text = self.expression_string.text() if text: QApplication.clipboard().setText(text)
def __copy_result_text(self) -> None: """Copy pretty print result as text.""" QApplication.clipboard().setText( pprint.pformat(self.mechanism_data[self.result_list.currentRow()]) )
def paste(self): """Reimplement Qt method""" if self.has_selected_text(): self.remove_selected_text() self.insert_text(QApplication.clipboard().text())
def copy_to_clipboard(self): from spyder.dependencies import status QApplication.clipboard().setText(status())