def update_actions(self): """ Updates the list of actions. """ self.clear() self.recent_files_actions[:] = [] for file in self.manager.get_recent_files(): action = QtWidgets.QAction(self) action.setText(os.path.split(file)[1]) action.setToolTip(file) action.setStatusTip(file) action.setData(file) action.setIcon(self.icon_provider.icon(QtCore.QFileInfo(file))) action.triggered.connect(self._on_action_triggered) self.addAction(action) self.recent_files_actions.append(action) self.addSeparator() action_clear = QtWidgets.QAction('Clear list', self) action_clear.triggered.connect(self.clear_recent_files) if isinstance(self.clear_icon, QtGui.QIcon): action_clear.setIcon(self.clear_icon) elif self.clear_icon: theme = '' if len(self.clear_icon) == 2: theme, path = self.clear_icon else: path = self.clear_icon icons.icon(theme, path, 'fa.times-circle') self.addAction(action_clear)
def save_current(self, path=None): """ Save current editor content. Leave file to None to erase the previous file content. If the current editor's file_path is None and path is None, the function will call ``QtWidgets.QFileDialog.getSaveFileName`` to get a valid save filename. :param path: path of the file to save, leave it None to overwrite existing file. """ try: if not path and not self._current.file.path: path, filter = QtWidgets.QFileDialog.getSaveFileName( self, _('Choose destination path')) if not path: return False old_path = self._current.file.path code_edit = self._current self._save_editor(code_edit, path) path = code_edit.file.path # path (and icon) may have changed if path and old_path != path: self._ensure_unique_name(code_edit, code_edit.file.name) self.setTabText(self.currentIndex(), code_edit._tab_name) ext = os.path.splitext(path)[1] old_ext = os.path.splitext(old_path)[1] if ext != old_ext or not old_path: icon = QtWidgets.QFileIconProvider().icon( QtCore.QFileInfo(code_edit.file.path)) self.setTabIcon(self.currentIndex(), icon) return True except AttributeError: # not an editor widget pass return False
def _update_recents(self): """ Updates the recent files list. """ self.ui.listWidgetRecents.clear() for file in self.app.file.recent_files_manager.get_recent_files(): item = QtWidgets.QListWidgetItem() if ('.' + QtCore.QFileInfo(file).suffix().upper() in CobolCodeEdit.extensions): icon = QtGui.QIcon(icons.ICON_MIMETYPE) else: icon = QtWidgets.QFileIconProvider().icon( QtCore.QFileInfo(file)) item.setText(QtCore.QFileInfo(file).fileName()) item.setToolTip(file) item.setIcon(icon) item.setData(QtCore.Qt.UserRole, file) self.ui.listWidgetRecents.addItem(item)
def set_filenames(self, filenames): def clean(filenames): ret_val = [] new_count = 0 for filename in filenames: if not filename: filename = 'New document %d.txt' % (new_count + 1) new_count += 1 ret_val.append(filename) return ret_val self._filenames = filenames filenames = clean(filenames) if self.sort_enabled: filenames = sorted(filenames, key=lambda x: QtCore.QFileInfo(x).fileName().lower()) self.ui.tableWidget.clearContents() icon_provider = SplittableCodeEditTabWidget.icon_provider_klass() self.ui.tableWidget.setRowCount(len(filenames)) self.ui.tableWidget.horizontalHeader().setSectionResizeMode( QtWidgets.QHeaderView.ResizeToContents) for row, path in enumerate(filenames): finfo = QtCore.QFileInfo(path) filename = finfo.fileName() if finfo.exists(): icon = icon_provider.icon(finfo) else: icon = icon_provider.icon(icon_provider.File) # file name item = QtWidgets.QTableWidgetItem() item.setText(filename) item.setIcon(icon) item.setToolTip(path) item.setData(QtCore.Qt.UserRole, bytes(path, 'utf-8')) self.ui.tableWidget.setItem(row, 0, item) # path item = QtWidgets.QTableWidgetItem() item.setText(path) item.setToolTip(path) item.setData(QtCore.Qt.UserRole, bytes(path, 'utf-8')) self.ui.tableWidget.setItem(row, 1, item)
def _update_recents(self): """ Updates the recent files list. """ self.ui.listWidgetRecents.clear() for file in self.app.file.recent_files_manager.get_recent_files(): item = QtWidgets.QListWidgetItem() fi = QtCore.QFileInfo(file) icon = FileIconProvider().icon(fi) item.setText(fi.fileName()) item.setToolTip(file) item.setIcon(icon) item.setData(QtCore.Qt.UserRole, file) self.ui.listWidgetRecents.addItem(item)
def add_message(self, msg): """ Adds a checker message to the table. :param msg: The message to append :type msg: pyqode.core.modes.CheckerMessage """ row = self.rowCount() self.insertRow(row) # type item = QtWidgets.QTableWidgetItem(self._make_icon(msg.status), msg.status_string) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_TYPE, item) # filename item = QtWidgets.QTableWidgetItem( QtCore.QFileInfo(msg.path).fileName()) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_FILE_NAME, item) # line if msg.line <= 0: item = QtWidgets.QTableWidgetItem("-") else: item = QtWidgets.QTableWidgetItem(str(msg.line + 1)) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_LINE_NBR, item) # desc item = QtWidgets.QTableWidgetItem(msg.description) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_MSG, item)
def update_actions(self): """ Updates the list of actions. """ self.clear() self.recent_files_actions[:] = [] for file in self.manager.get_recent_files(): action = QtWidgets.QAction(self) action.setText(os.path.split(file)[1]) action.setToolTip(file) action.setStatusTip(file) action.setData(file) action.setIcon(self.icon_provider.icon(QtCore.QFileInfo(file))) action.triggered.connect(self._on_action_triggered) self.addAction(action) self.recent_files_actions.append(action) self.addSeparator() action_clear = QtWidgets.QAction('Clear list', self) action_clear.triggered.connect(self.clear_recent_files) if self.clear_icon and len(self.clear_icon) == 2: action_clear.setIcon( QtGui.QIcon.fromTheme(self.clear_icon[0], QtGui.QIcon(self.clear_icon[1]))) self.addAction(action_clear)
def _run_in_external_terminal(self, program, wd, file_type): """ Runs a program in an external terminal. :param program: program to run :param wd: working directory """ self.ui.consoleOutput.append("Launched in external terminal") pyqode_console = system.which('pyqode-console') if file_type == FileType.MODULE: program = QtCore.QFileInfo(program).baseName() if system.windows: cmd = [pyqode_console, program] if file_type == FileType.MODULE: cmd.insert(1, system.which('cobcrun')) subprocess.Popen(cmd, cwd=wd, creationflags=subprocess.CREATE_NEW_CONSOLE) elif system.darwin: cmd = ['open', program] if file_type == FileType.MODULE: cmd.insert(1, system.which('cobcrun')) subprocess.Popen(cmd, cwd=wd) else: if file_type == FileType.EXECUTABLE: cmd = ['"%s %s"' % (pyqode_console, program)] else: cmd = [ '"%s %s %s"' % (pyqode_console, system.which('cobcrun'), program) ] cmd = (Settings().external_terminal_command.strip().split(' ') + cmd) subprocess.Popen(' '.join(cmd), cwd=wd, shell=True) _logger().info('running program in external terminal: %s', ' '.join(cmd))
def _icon(self, path): provider = self.icon_provider_klass() if not os.path.exists(path): return provider.icon(provider.File) return provider.icon(QtCore.QFileInfo(path))
def open_document(self, path, encoding=None, replace_tabs_by_spaces=True, clean_trailing_whitespaces=True, safe_save=True, restore_cursor_position=True, preferred_eol=0, autodetect_eol=True, show_whitespaces=False, **kwargs): """ Opens a document. :param path: Path of the document to open :param encoding: The encoding to use to open the file. Default is locale.getpreferredencoding(). :param replace_tabs_by_spaces: Enable/Disable replace tabs by spaces. Default is true. :param clean_trailing_whitespaces: Enable/Disable clean trailing whitespaces (on save). Default is True. :param safe_save: If True, the file is saved to a temporary file first. If the save went fine, the temporary file is renamed to the final filename. :param restore_cursor_position: If true, last cursor position will be restored. Default is True. :param preferred_eol: Preferred EOL convention. This setting will be used for saving the document unless autodetect_eol is True. :param autodetect_eol: If true, automatically detects file EOL and use it instead of the preferred EOL when saving files. :param show_whitespaces: True to show white spaces. :param kwargs: addtional keyword args to pass to the widget constructor. :return: The created code editor """ path = os.path.normpath(path) paths = [] widgets = [] for w in self.widgets(include_clones=False): if os.path.exists(w.file.path): # skip new docs widgets.append(w) paths.append(w.file.path) if path in paths: i = paths.index(path) w = widgets[i] tw = w.parent_tab_widget tw.setCurrentIndex(tw.indexOf(w)) return w else: assert os.path.exists(path) name = os.path.split(path)[1] use_parent_dir = False for tab in self.widgets(): title = QtCore.QFileInfo(tab.file.path).fileName() if title == name: tw = tab.parent_tab_widget new_name = os.path.join(os.path.split(os.path.dirname( tab.file.path))[1], title) tw.setTabText(tw.indexOf(tab), new_name) use_parent_dir = True if use_parent_dir: name = os.path.join( os.path.split(os.path.dirname(path))[1], name) use_parent_dir = False tab = self._create_code_edit(self.guess_mimetype(path), **kwargs) tab.file.clean_trailing_whitespaces = clean_trailing_whitespaces tab.file.safe_save = safe_save tab.file.restore_cursor = restore_cursor_position tab.file.replace_tabs_by_spaces = replace_tabs_by_spaces tab.file.autodetect_eol = autodetect_eol tab.file.preferred_eol = preferred_eol tab.show_whitespaces = show_whitespaces tab.file.open(path, encoding=encoding) tab.setDocumentTitle(name) icon = self._icon(path) self.add_tab(tab, title=name, icon=icon) return tab
def _run_in_external_terminal(self, program, wd, file_type): """ Runs a program in an external terminal. :param program: program to run :param wd: working directory """ pyqode_console = system.which('pyqode-console') cobc_run_insert_pos = 1 if pyqode_console is None: from pyqode.core.tools import console pyqode_console = [sys.executable, console.__file__] cobc_run_insert_pos = 2 else: pyqode_console = [pyqode_console] env = os.environ.copy() for k, v in list(Settings().run_environemnt.items()): env[k] = v if 'PATH' not in list(Settings().run_environemnt.keys()): env['PATH'] = GnuCobolCompiler.setup_process_environment().value( 'PATH') if file_type == FileType.MODULE: program = QtCore.QFileInfo(program).baseName() if system.windows: cmd = pyqode_console + [program] if file_type == FileType.MODULE: cmd.insert(cobc_run_insert_pos, system.which('cobcrun')) try: _logger().debug( "running program in external terminal: %r, %r, %r" % (cmd, wd, env)) subprocess.Popen(cmd, cwd=wd, creationflags=subprocess.CREATE_NEW_CONSOLE, env=env) except (OSError, subprocess.CalledProcessError): msg = "Failed to launch program in external terminal (cmd=%s) " % ' '.join( cmd) _logger().exception(msg) self.ui.consoleOutput.appendPlainText(msg) return elif system.darwin: if file_type == FileType.MODULE: create_script(PATH_RUN_MODULE_SCRIPT, RUN_MODULE_SCRIPT, (wd, system.which('cobcrun'), program)) cmd = [ 'open', '-n', '-a', 'Terminal', '--args', PATH_RUN_MODULE_SCRIPT ] else: create_script(PATH_RUN_PROGRAM_SCRIPT, RUN_PROGRAM_SCRIPT, (wd, program)) cmd = [ 'open', '-n', '-a', 'Terminal', '--args', PATH_RUN_PROGRAM_SCRIPT ] try: subprocess.Popen(cmd, cwd=wd, env=env) except (OSError, subprocess.CalledProcessError): msg = "Failed to launch program in external terminal (cmd=%s) " % ' '.join( cmd) _logger().exception(msg) self.ui.consoleOutput.appendPlainText(msg) return else: if file_type == FileType.EXECUTABLE: cmd = ['"%s %s"' % (' '.join(pyqode_console), program)] else: cmd = [ '"%s %s %s"' % (' '.join(pyqode_console), system.which('cobcrun'), program) ] cmd = system.shell_split( Settings().external_terminal_command.strip()) + cmd try: subprocess.Popen(' '.join(cmd), cwd=wd, shell=True, env=env) except (OSError, subprocess.CalledProcessError): msg = "Failed to launch program in external terminal (cmd=%s) " % ' '.join( cmd) _logger().exception(msg) self.ui.consoleOutput.appendPlainText(msg) return _logger().info('running program in external terminal: %s', ' '.join(cmd)) self.ui.consoleOutput.appendPlainText( "Launched in external terminal: %s" % ' '.join(cmd))
def _get_icon(self): return QtWidgets.QFileIconProvider().icon(QtCore.QFileInfo(self.path))
def _add_file(self, path): icon = QtWidgets.QFileIconProvider().icon(QtCore.QFileInfo(path)) item = QtWidgets.QListWidgetItem(icon, path) self.listWidget.addItem(item)