id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
11,500
errors_tree.py
ninja-ide_ninja-ide/ninja_ide/gui/tools_dock/errors_tree.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QTreeWidget, QTreeWidgetItem, QWidget, QVBoxLayout ) from ninja_ide.gui.ide import IDE # FIXME: se ejecuta 2 veces refresh, proviene de _set_current combo editor # FIXME: analizar todo el proyecto class ErrorsTree(QWidget): def __init__(self, parent=None): super().__init__(parent) IDE.register_service("errors_tree", self) box = QVBoxLayout(self) box.setContentsMargins(0, 0, 0, 0) self._tree = QTreeWidget() self._tree.header().setHidden(True) self._tree.setAnimated(True) box.addWidget(self._tree) def refresh(self, errors, path): self._tree.clear() parent = QTreeWidgetItem(self._tree, [path]) for lineno, msg in errors.items(): item = QTreeWidgetItem(parent, [msg]) self._tree.addTopLevelItem(item) def display_name(self): return 'Errors' # FIXME: if stm ErrorsTree()
1,652
Python
.py
45
32.222222
74
0.698373
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,501
tools_dock.py
ninja-ide_ninja-ide/ninja_ide/gui/tools_dock/tools_dock.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import collections from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QToolButton from PyQt5.QtWidgets import QMenu from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QStackedWidget from PyQt5.QtWidgets import QSpacerItem from PyQt5.QtWidgets import QSizePolicy from PyQt5.QtWidgets import QStyleOption from PyQt5.QtWidgets import QStyle from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QShortcut from PyQt5.QtGui import QPainter from PyQt5.QtGui import QKeySequence from PyQt5.QtGui import QCursor from PyQt5.QtCore import pyqtSignal from PyQt5.QtCore import QRect from PyQt5.QtCore import Qt from PyQt5.QtCore import QSize from ninja_ide.core import settings from ninja_ide.tools import ui_tools from ninja_ide.tools.logger import NinjaLogger from ninja_ide.gui.ide import IDE from ninja_ide.gui.tools_dock import actions from ninja_ide.gui.tools_dock import python_selector logger = NinjaLogger(__name__) DEBUG = logger.debug class _ToolsDock(QWidget): __WIDGETS = {} __created = False __index = 0 # Signals executeFile = pyqtSignal() executeProject = pyqtSignal() executeSelection = pyqtSignal() stopApplication = pyqtSignal() def __init__(self, parent=None): super().__init__(parent) # Register signals connections layout = QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) self.__buttons = [] self.__action_number = 1 self.__buttons_visibility = {} self.__current_widget = None self.__last_index = -1 self._stack_widgets = QStackedWidget() layout.addWidget(self._stack_widgets) # Buttons Widget self.buttons_widget = QWidget() self.buttons_widget.setObjectName("tools_dock") self.buttons_widget.setFixedHeight(26) self.buttons_widget.setLayout(QHBoxLayout()) self.buttons_widget.layout().setContentsMargins(2, 2, 5, 2) self.buttons_widget.layout().setSpacing(10) IDE.register_service("tools_dock", self) _ToolsDock.__created = True @classmethod def register_widget(cls, display_name, obj): """Register a widget providing the service name and the instance""" cls.__WIDGETS[cls.__index] = (obj, display_name) cls.__index += 1 def install(self): self._load_ui() ninjaide = IDE.get_service("ide") ninjaide.place_me_on("tools_dock", self, "central") ui_tools.install_shortcuts(self, actions.ACTIONS, ninjaide) ninjaide.goingDown.connect(self._save_settings) ninja_settings = IDE.ninja_settings() index = int(ninja_settings.value("tools_dock/widgetVisible", -1)) if index == -1: self.hide() else: self._show(index) def _load_ui(self): ninjaide = IDE.get_service("ide") shortcut_number = 1 for index, (obj, name) in _ToolsDock.__WIDGETS.items(): button = ToolButton(name, index + 1) button.setCheckable(True) button.clicked.connect(self.on_button_triggered) self.__buttons.append(button) self.buttons_widget.layout().addWidget(button) self.add_widget(name, obj) self.__buttons_visibility[button] = True # Shortcut action ksequence = self._get_shortcut(shortcut_number) short = QShortcut(ksequence, ninjaide) button.setToolTip( ui_tools.tooltip_with_shortcut(button._text, ksequence)) short.activated.connect(self._shortcut_triggered) shortcut_number += 1 self.buttons_widget.layout().addItem( QSpacerItem(0, 0, QSizePolicy.Expanding)) # Python Selector btn_selector = ui_tools.FancyButton("Loading...") btn_selector.setIcon(ui_tools.get_icon("python")) btn_selector.setCheckable(True) btn_selector.setEnabled(False) self.buttons_widget.layout().addWidget(btn_selector) # QML Interface self._python_selector = python_selector.PythonSelector(btn_selector) interpreter_srv = IDE.get_service("interpreter") interpreter_srv.foundInterpreters.connect( self._python_selector.add_model) btn_selector.toggled[bool].connect( lambda v: self._python_selector.setVisible(v)) # Popup for show/hide tools widget button_toggle_widgets = ToggleButton() self.buttons_widget.layout().addWidget(button_toggle_widgets) button_toggle_widgets.clicked.connect(self._show_menu) def _get_shortcut(self, short_number: int): """Return shortcut as ALT + number""" if short_number < 1 or short_number > 9: return QKeySequence() modifier = Qt.ALT if not settings.IS_MAC_OS else Qt.CTRL return QKeySequence(modifier + (Qt.Key_0 + short_number)) def _shortcut_triggered(self): short = self.sender() widget_index = int(short.key().toString()[-1]) - 1 widget = self.widget(widget_index) if widget.isVisible(): self._hide() else: self._show(widget_index) def _show_menu(self): menu = QMenu() for n, (obj, display_name) in _ToolsDock.__WIDGETS.items(): action = menu.addAction(display_name) action.setCheckable(True) action.setData(n) button = self.__buttons[n] visible = self.__buttons_visibility.get(button) action.setChecked(visible) result = menu.exec_(QCursor.pos()) if not result: return index = result.data() btn = self.__buttons[index] visible = self.__buttons_visibility.get(btn, False) self.__buttons_visibility[btn] = not visible if visible: btn.hide() else: btn.show() def get_widget_index_by_instance(self, instance): index = -1 for i, (obj, _) in self.__WIDGETS.items(): if instance == obj: index = i break return index def execute_file(self): run_widget = IDE.get_service("run_widget") index = self.get_widget_index_by_instance(run_widget) self._show(index) self.executeFile.emit() def execute_project(self): run_widget = IDE.get_service("run_widget") index = self.get_widget_index_by_instance(run_widget) self._show(index) self.executeProject.emit() def execute_selection(self): run_widget = IDE.get_service("run_widget") index = self.get_widget_index_by_instance(run_widget) self._show(index) self.executeSelection.emit() def kill_application(self): self.stopApplication.emit() def add_widget(self, display_name, obj): self._stack_widgets.addWidget(obj) func = getattr(obj, "install_widget", None) if isinstance(func, collections.Callable): func() def on_button_triggered(self): # Get button index button = self.sender() index = self.__buttons.index(button) if index == self.current_index() and self._is_current_visible(): self._hide() else: self._show(index) def widget(self, index): return self.__WIDGETS[index][0] def _hide(self): self.__current_widget.setVisible(False) index = self.current_index() self.__buttons[index].setChecked(False) self.widget(index).setVisible(False) self.hide() def hide_widget(self, obj): index = self.get_widget_index_by_instance(obj) self.set_current_index(index) self._hide() def _show(self, index): widget = self.widget(index) self.__current_widget = widget widget.setVisible(True) widget.setFocus() self.set_current_index(index) self.show() def set_current_index(self, index): if self.__last_index != -1: self.__buttons[self.__last_index].setChecked(False) self.__buttons[index].setChecked(True) if index != -1: self._stack_widgets.setCurrentIndex(index) widget = self.widget(index) widget.setVisible(True) self.__last_index = index def current_index(self): return self._stack_widgets.currentIndex() def _is_current_visible(self): return self.__current_widget and self.__current_widget.isVisible() def _save_settings(self): ninja_settings = IDE.ninja_settings() visible_widget = self.current_index() if not self.isVisible(): visible_widget = -1 ninja_settings.setValue("tools_dock/widgetVisible", visible_widget) class ToggleButton(QToolButton): def __init__(self, parent=None): super().__init__(parent) self.setObjectName("toggle_button") self.setFocusPolicy(Qt.NoFocus) self.setAutoRaise(True) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) def sizeHint(self): self.ensurePolished() return QSize(20, 20) def paintEvent(self, event): QToolButton.paintEvent(self, event) painter = QPainter(self) opt = QStyleOption() opt.initFrom(self) opt.rect = QRect(6, self.rect().center().y() - 3, 8, 8) opt.rect.translate(0, -3) style = self.style() style.drawPrimitive(QStyle.PE_IndicatorArrowUp, opt, painter, self) opt.rect.translate(0, 6) style.drawPrimitive(QStyle.PE_IndicatorArrowDown, opt, painter, self) class StackedWidget(QStackedWidget): """Handle the different widgets in the stack of tools dock.""" def setCurrentIndex(self, index): """Change the current widget being displayed with an animation.""" old_widget = self.currentWidget() new_widget = self.widget(index) if old_widget != new_widget: self.fader_widget = ui_tools.FaderWidget(self.currentWidget(), self.widget(index)) QStackedWidget.setCurrentIndex(self, index) class ToolButton(QPushButton): def __init__(self, text, number=None, parent=None): super().__init__(parent) self.setObjectName("button_tooldock") self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.setFlat(True) if number is None: self._number = None else: self._number = str(number) self._text = text def setText(self, text): super().setText(text) self._text = text def paintEvent(self, event): super().paintEvent(event) if self._number is None: painter = QPainter(self) fm = self.fontMetrics() base_line = (self.height() - fm.height()) / 2 + fm.ascent() painter.drawText(event.rect(), Qt.AlignCenter, self._text) else: fm = self.fontMetrics() base_line = (self.height() - fm.height()) / 2 + fm.ascent() number_width = fm.width(self._number) painter = QPainter(self) # Draw shortcut number painter.drawText( (15 - number_width) / 2, base_line, self._number ) # Draw display name of tool button painter.drawText( 18, base_line, fm.elidedText(self._text, Qt.ElideRight, self.width())) def sizeHint(self): self.ensurePolished() s = self.fontMetrics().size(Qt.TextSingleLine, self._text) s.setWidth(s.width() + 25) return s.expandedTo(QApplication.globalStrut()) tools_dock = _ToolsDock() '''from PyQt5.QtWidgets import ( QWidget, QToolBar, QPushButton, QToolButton, QStyle, QStackedWidget, QHBoxLayout, QVBoxLayout, QSpacerItem, QShortcut, QSizePolicy ) from PyQt5.QtGui import ( QIcon, QKeySequence ) from PyQt5.QtCore import ( QSize, pyqtSignal, Qt ) # from PyQt4.QtWebKit import QWebPage from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.gui.ide import IDE from ninja_ide.gui.tools_dock import actions from ninja_ide.gui.tools_dock import console_widget from ninja_ide.gui.tools_dock import run_widget # from ninja_ide.gui.tools_dock import web_render # from ninja_ide.gui.tools_dock import find_in_files # from ninja_ide.gui.tools_dock import results from ninja_ide.tools import ui_tools from ninja_ide import translations # from ninja_ide.gui.theme import COLORS from ninja_ide.gui.theme import NTheme # TODO: add terminal widget class _ToolsDock(ui_tools.StyledBar): """Former Miscellaneous, contains all the widgets in the bottom area.""" projectExecuted = pyqtSignal('QString') def __init__(self, parent=None): super(_ToolsDock, self).__init__(parent) # Register signals connections connections = ( {'target': 'main_container', 'signal_name': "findOcurrences(QString)", 'slot': self.show_find_occurrences}, {'target': 'main_container', 'signal_name': "runFile(QString)", 'slot': self.execute_file}, ) IDE.register_signals('tools_dock', connections) IDE.register_service("tools_dock", self) def setup_ui(self): """Load all the components of the ui during the install process.""" vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) # self.__toolbar = QToolBar() # self.__toolbar.setContentsMargins(0, 0, 0, 0) # self.__toolbar.setObjectName('custom') self.hbox = QHBoxLayout() vbox.addLayout(self.hbox) self.stack = QStackedWidget() vbox.addWidget(self.stack) self._console = console_widget.ConsoleWidget() self._runWidget = run_widget.RunWidget() # self._web = web_render.WebRender() # self._findInFilesWidget = find_in_files.FindInFilesWidget( # self.parent()) # Not Configurable Shortcuts shortEscMisc = QShortcut(QKeySequence(Qt.Key_Escape), self) shortEscMisc.activated.connect(self.hide) # Toolbar # hbox.addWidget(self.__toolbar) self.add_to_stack( self._console, ui_tools.colored_icon( ":img/console", NTheme.get_color('IconBaseColor')), translations.TR_CONSOLE) self.add_to_stack( self._runWidget, ui_tools.colored_icon( ":img/run", NTheme.get_color('IconBaseColor')), translations.TR_OUTPUT) # self.add_to_stack(self._web, ":img/web", # translations.TR_WEB_PREVIEW) # self.add_to_stack(self._findInFilesWidget, ":img/find", # translations.TR_FIND_IN_FILES) # Last Element in the Stacked widget # self._results = results.Results(self) # self.stack.addWidget(self._results) # self.__toolbar.addSeparator() self.hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) # btn_close = QPushButton( # self.style().standardIcon(QStyle.SP_DialogCloseButton), '') # btn_close.setIconSize(QSize(24, 24)) # btn_close.setObjectName('navigation_button') btn_close = QToolButton() btn_close.setIcon( QIcon( ui_tools.colored_icon( ":img/close", NTheme.get_color('IconBaseColor')))) btn_close.setToolTip('F4: ' + translations.TR_ALL_VISIBILITY) self.hbox.addWidget(btn_close) btn_close.clicked.connect(self.hide) def install(self): """ Install triggered by the ide """ self.setup_ui() ninjaide = IDE.get_service('ide') ninjaide.place_me_on("tools_dock", self, "central") ui_tools.install_shortcuts(self, actions.ACTIONS, ninjaide) ninjaide.goingDown.connect(self.save_configuration) qsettings = IDE.ninja_settings() visible = qsettings.value("tools_dock/visible", True, type=bool) self.setVisible(visible) def save_configuration(self): qsettings = IDE.ninja_settings() qsettings.setValue("tools_dock/visible", self.isVisible()) def change_visibility(self): """Change tools dock visibility.""" # FIXME: set focus on console when is visible but not focus if self.isVisible(): self.hide() else: self.show() def add_project_to_console(self, projectFolder): """Add the namespace of the project received into the ninja-console.""" self._console.load_project_into_console(projectFolder) def remove_project_from_console(self, projectFolder): """Remove the namespace of the project received from the console.""" self._console.unload_project_from_console(projectFolder) def _item_changed(self, val): """Change the current item.""" if not self.isVisible(): self.show() # self.stack.show_display(val) self.stack.setCurrentIndex(val) def show_find_in_files_widget(self): """Show the Find In Files widget.""" index_of = self.stack.indexOf(self._findInFilesWidget) self._item_changed(index_of) self._findInFilesWidget.open() self._findInFilesWidget.setFocus() def show_find_occurrences(self, word): """Show Find In Files widget in find occurrences mode.""" index_of = self.stack.indexOf(self._findInFilesWidget) self._item_changed(index_of) self._findInFilesWidget.find_occurrences(word) self._findInFilesWidget.setFocus() def execute_file(self): """Execute the current file.""" main_container = IDE.get_service('main_container') if not main_container: return editorWidget = main_container.get_current_editor() if editorWidget is not None: if editorWidget.is_modified: main_container.save_file(editorWidget) # emit a signal for plugin! # self.emit(SIGNAL("fileExecuted(QString)"), # editorWidget.file_path) ext = file_manager.get_file_extension(editorWidget.file_path) # TODO: Remove the IF statment and use Handlers if ext == 'py': self._run_application(editorWidget.file_path) elif ext == 'html': self.render_web_page(editorWidget.file_path) def execute_project(self): """Execute the project marked as Main Project.""" projects_explorer = IDE.get_service('projects_explorer') if projects_explorer is None: return nproject = projects_explorer.current_project if nproject: main_file = nproject.main_file if not main_file and projects_explorer.current_tree: projects_explorer.current_tree.open_project_properties() elif main_file: projects_explorer.save_project() # emit a signal for plugin! self.projectExecuted.emit(nproject.path) main_file = file_manager.create_path(nproject.path, nproject.main_file) self._run_application( main_file, pythonExec=nproject.python_exec_command, PYTHONPATH=nproject.python_path, programParams=nproject.program_params, preExec=nproject.pre_exec_script, postExec=nproject.post_exec_script ) def _run_application(self, fileName, pythonExec=False, PYTHONPATH=None, programParams='', preExec='', postExec=''): """Execute the process to run the application.""" self._item_changed(1) self.show() self._runWidget.start_process(fileName, pythonExec, PYTHONPATH, programParams, preExec, postExec) self._runWidget.input.setFocus() def show_results(self, items): """Show Results of Navigate to for several occurrences.""" index_of = self.stack.indexOf(self._results) self._item_changed(index_of) self.show() self._results.update_result(items) self._results._tree.setFocus() self._results.setFocus() def kill_application(self): """Kill the process of the application being executed.""" self._runWidget.kill_process() def render_web_page(self, url): """Render a webpage from the url path.""" index_of = self.stack.indexOf(self._web) self._item_changed(index_of) self.show() self._web.render_page(url) if settings.SHOW_WEB_INSPECTOR: web_inspector = IDE.get_service('web_inspector') if web_inspector: web_inspector.set_inspection_page(self._web.webFrame.page()) self._web.webFrame.triggerPageAction( QWebPage.InspectElement, True) web_inspector.refresh_inspector() self._web.setFocus() def add_to_stack(self, widget, icon_path, description): """ Add a widget to the container and an button(with icon))to the toolbar to show the widget """ # add the widget self.stack.addWidget(widget) # create a button in the toolbar to show the widget # button = QPushButton(QIcon(icon_path), '') button = QToolButton(self) # button.setIconSize(QSize(18, 18)) # button.setIcon(QIcon(icon_path)) button.setText(description) button.setToolTip(description) index = self.stack.count() - 1 button.clicked.connect(lambda: self._item_changed(index)) self.hbox.addWidget(button) # self.__toolbar.addWidget(button) def showEvent(self, event): super(_ToolsDock, self).showEvent(event) widget = self.stack.currentWidget() if widget: widget.setFocus() class StackedWidget(QStackedWidget): """Handle the different widgets in the stack of tools dock.""" def setCurrentIndex(self, index): """Change the current widget being displayed with an animation.""" self.fader_widget = ui_tools.FaderWidget(self.currentWidget(), self.widget(index)) QStackedWidget.setCurrentIndex(self, index) def show_display(self, index): """Change the current widget and trigger the animation.""" self.setCurrentIndex(index) ToolsDock = _ToolsDock() '''
23,743
Python
.py
573
32.364747
79
0.631207
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,502
actions.py
ninja-ide_ninja-ide/ninja_ide/gui/tools_dock/actions.py
# -*- coding: utf-8 -*- from ninja_ide import translations # "connect": "function_name" ACTIONS = ( # "weight": 240 # "connect": "show_find_in_files_widget" { "shortcut": "run-file", "action": { "text": translations.TR_RUN_FILE, "image": "run-file", "section": (translations.TR_MENU_PROJECT, None), "weight": 110 }, "connect": "execute_file" }, { "shortcut": "run-selection", "action": { "text": translations.TR_RUN_SELECTION, "section": (translations.TR_MENU_PROJECT, None), "weight": 110 }, "connect": "execute_selection" }, { "shortcut": "run-project", "action": { "text": translations.TR_RUN_PROJECT, "image": "run-project", "section": (translations.TR_MENU_PROJECT, None), "weight": 100 }, "connect": "execute_project" }, { "shortcut": "stop-execution", "action": { 'text': translations.TR_STOP, 'image': "stop", 'section': (translations.TR_MENU_PROJECT, None), 'weight': 120 }, "connect": "kill_application" }, # "weight": 100 # "connect": "change_visibility" )
1,351
Python
.py
48
19.666667
60
0.490769
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,503
scrollbar.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/scrollbar.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from collections import namedtuple from collections import defaultdict from PyQt5.QtWidgets import ( QScrollBar, QToolTip, QStyleOptionSlider, QWidget, QStyle ) from PyQt5.QtGui import ( QPainter, QColor ) from PyQt5.QtCore import QPoint from PyQt5.QtCore import QTimer from PyQt5.QtCore import Qt Marker = namedtuple('Marker', 'position color priority') class ScrollBarOverlay(QWidget): class Position: LEFT = 0 CENTER = 1 RIGHT = 2 def __init__(self, nscrollbar): super().__init__(nscrollbar) self._nscrollbar = nscrollbar self.__schedule_updated = False self.markers = defaultdict(list) # {'id': list of markers} self.cache = {} # {'position': marker} self.range_offset = 0.0 self.visible_range = 0.0 def paintEvent(self, event): QWidget.paintEvent(self, event) self.update_cache() if not self.cache: return rect = self._nscrollbar.overlay_rect() sb_range = self._nscrollbar.get_scrollbar_range() sb_range = max(self.visible_range, sb_range) result_width = rect.width() / 3 result_height = min(rect.height() / sb_range + 1, 4) x = rect.center().x() - 1 offset = rect.height() / sb_range * self.range_offset vertical_margin = ((rect.height() / sb_range) - result_height) / 2 painter = QPainter(self) for lineno in self.cache.keys(): marker = self.cache[lineno] top = rect.top() + offset + vertical_margin + \ marker.position / sb_range * rect.height() painter.fillRect( x, top, result_width, 4, QColor(marker.color)) def update_cache(self): if not self.__schedule_updated: return self.cache.clear() categories = self.markers.keys() for category in categories: markers = self.markers[category] for marker in markers: old = self.cache.get(marker.position) if old is not None and old.position == marker.position: if old.priority > marker.priority: self.cache[old.position] = old continue self.cache[marker.position] = marker self.__schedule_updated = False def schedule_update(self): if self.__schedule_updated: return self.__schedule_updated = True QTimer.singleShot(0, self.update) class NScrollBar(QScrollBar): """Custom QScrollBar with markers""" def __init__(self, neditor): super().__init__(neditor) self._neditor = neditor self._overlay = ScrollBarOverlay(self) def line_number_to_position(self, lineno): """ Converts line number to y position """ return (lineno - self.minimum()) * self.__scale_factor() def __scale_factor(self): val = self.maximum() + self.pageStep() return self.height() / val def get_scrollbar_range(self): return self.maximum() + self.pageStep() def overlay_rect(self): opt = QStyleOptionSlider() self.initStyleOption(opt) return self.style().subControlRect(QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self) def set_visible_range(self, visible_range): self._overlay.visible_range = visible_range def set_range_offset(self, offset): self._overlay.range_offset = offset def resizeEvent(self, event): if self._overlay is None: return QScrollBar.resizeEvent(self, event) self._overlay.resize(self.size()) def mousePressEvent(self, event): super().mousePressEvent(event) if event.button() == Qt.LeftButton: self._tooltip_pos = event.globalPos() - QPoint(event.pos().x(), 0) from_line = self._neditor.first_visible_block().blockNumber() + 1 to_line = self._neditor.last_visible_block().blockNumber() text = "<center>%d<br/>&#x2014;<br/>%d</center>" QToolTip.showText(self._tooltip_pos, text % (from_line, to_line)) def mouseMoveEvent(self, event): super().mouseMoveEvent(event) from_line = self._neditor.first_visible_block().blockNumber() + 1 to_line = self._neditor.last_visible_block().blockNumber() text = "<center>%d<br/>&#x2014;<br/>%d</center>" QToolTip.showText(self._tooltip_pos, text % (from_line, to_line)) def remove_marker(self, category): if category in self._overlay.markers: del self._overlay.markers[category] self._overlay.schedule_update() def add_marker(self, category, lineno, color, priority=0): marker = Marker(lineno, color, priority) self._overlay.markers[category].append(marker) self._overlay.schedule_update() def link(self, scrollbar): self._overlay.markers.update(scrollbar.markers().copy()) def markers(self): return self._overlay.markers
5,947
Python
.py
146
31.842466
78
0.617158
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,504
syntax_highlighter.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/syntax_highlighter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. # Based on: https://bitbucket.org/henning/syntaxhighlighter """ Partition-based syntax highlighter """ from __future__ import absolute_import from __future__ import unicode_literals import re from PyQt4.QtGui import ( QSyntaxHighlighter, QColor, QTextCharFormat, QTextBlockUserData, QFont, QBrush, QTextFormat) from PyQt4.QtCore import SIGNAL from ninja_ide import resources from ninja_ide.core import settings try: unicode except NameError: # Python 3 basestring = unicode = str # lint:ok def get_user_data(block): user_data = block.userData() if user_data is None or not isinstance(user_data, SyntaxUserData): user_data = SyntaxUserData() return user_data class SyntaxUserData(QTextBlockUserData): """Store the information of the errors, str and comments for each block.""" def __init__(self, error=False): super(SyntaxUserData, self).__init__() self.error = error self.str_groups = [] self.comment_start = -1 def clear_data(self): """Clear the data stored for the current block.""" self.error = False self.str_groups = [] self.comment_start = -1 def add_str_group(self, start, end): """Add a pair of values setting the beggining and end of a string.""" self.str_groups.append((start, end + 1)) def comment_start_at(self, pos): """Set the position in the line where the comment starts.""" self.comment_start = pos class TextCharFormat(QTextCharFormat): NAME = QTextFormat.UserProperty + 1 class Format(object): __slots__ = ("name", "tcf") def __init__(self, name, color=None, bold=None, italic=None, base_format=None, background=None): self.name = name tcf = TextCharFormat() if base_format is not None: if isinstance(base_format, Format): base_format = base_format.tcf tcf.merge(base_format) tcf.setFont(base_format.font()) if color is not None: if not isinstance(color, QColor): color = QColor(color) tcf.setForeground(QBrush(color)) if bold is not None: if bold: tcf.setFontWeight(QFont.Bold) else: tcf.setFontWeight(QFont.Normal) if italic is not None: tcf.setFontItalic(italic) if background is not None: color = QColor(background) tcf.setBackground(color) tcf.setProperty(TextCharFormat.NAME, name) self.tcf = tcf class HighlighterError(Exception): pass class Partition(object): # every partition maps to a specific state in QSyntaxHighlighter __slots__ = ("name", "start", "end", "is_multiline", "search_end") def __init__(self, name, start, end, is_multiline=False): self.name = name self.start = start self.end = end self.is_multiline = is_multiline try: self.search_end = re.compile(end, re.M | re.S).search except Exception as exc: raise HighlighterError("%s: %s %s" % (exc, name, end)) class PartitionScanner(object): # The idea to partition the source into different contexts comes # from Eclipse. # http://wiki.eclipse.org/FAQ_What_is_a_document_partition%3F def __init__(self, partitions): start_groups = [] self.partitions = [] for i, p in enumerate(partitions): if isinstance(p, (tuple, list)): p = Partition(*p) elif isinstance(p, dict): p = Partition(**p) else: assert isinstance(p, Partition), \ "Partition expected, got %r" % p self.partitions.append(p) start_groups.append("(?P<g%s_%s>%s)" % (i, p.name, p.start)) start_pat = "|".join(start_groups) try: self.search_start = re.compile(start_pat, re.M | re.S).search except Exception as exc: raise HighlighterError("%s: %s" % (exc, start_pat)) def scan(self, current_state, text): last_pos = 0 length = len(text) parts = self.partitions search_start = self.search_start # loop yields (start, end, partition, new_state, is_inside) while last_pos < length: if current_state == -1: found = search_start(text, last_pos) if found: start, end = found.span() yield last_pos, start, None, -1, True current_state = found.lastindex - 1 p = parts[current_state] yield start, end, p.name, current_state, False last_pos = end else: current_state = -1 yield last_pos, length, None, -1, True break else: p = parts[current_state] found = p.search_end(text, last_pos) if found: start, end = found.span() yield last_pos, start, p.name, current_state, True yield start, end, p.name, current_state, False last_pos = end current_state = -1 else: yield last_pos, length, p.name, current_state, True break if current_state != -1: p = parts[current_state] if not p.is_multiline: current_state = -1 yield length, length, None, current_state, False class Token(object): __slots__ = ("name", "pattern", "prefix", "suffix") def __init__(self, name, pattern, prefix="", suffix=""): self.name = name if isinstance(pattern, list): pattern = "|".join(pattern) self.pattern = pattern self.prefix = prefix self.suffix = suffix class Scanner(object): __slots__ = ("groups", "tokens", "search") def __init__(self, tokens): self.tokens = [] self.groups = [] for t in tokens: if isinstance(t, (list, tuple)): t = Token(*t) elif isinstance(t, dict): t = Token(**t) else: assert isinstance(t, Token), "Token expected, got %r" % t gdef = "?P<%s>" % t.name if gdef in t.pattern: p = t.pattern else: p = ("(%s%s)" % (gdef, t.pattern)) p = t.prefix + p + t.suffix self.groups.append(p) self.tokens.append(t) pat = "|".join(self.groups) self.search = re.compile(pat).search def add_token(self, token): self.__clean_highlight() tpattern = token[1] if tpattern != "": t = Token(*token) gdef = "?P<%s>" % t.name if gdef in t.pattern: p = t.pattern else: p = ("(%s%s)" % (gdef, t.pattern)) p = t.prefix + p + t.suffix self.groups.append(p) self.tokens.append(t) pat = "|".join(self.groups) self.search = re.compile(pat).search def __clean_highlight(self): for group in self.groups: if group.startswith('(?P<highlight_word>'): self.groups.remove(group) break for token in self.tokens: if token.name == "highlight_word": self.tokens.remove(token) break def scan(self, s): search = self.search last_pos = 0 # loop yields (token, start_pos, end_pos) while True: found = search(s, last_pos) if found: lg = found.lastgroup start, last_pos = found.span(lg) yield lg, start, last_pos else: break class SyntaxHighlighter(QSyntaxHighlighter): def __init__(self, parent, partition_scanner, scanner, formats, neditable=None): """ :param parent: QDocument or QTextEdit/QPlainTextEdit instance 'partition_scanner: PartitionScanner instance :param scanner: dictionary of token scanners for each partition The key is the name of the partition, the value is a Scanner instance The default scanner has the key None :formats: list of tuples consisting of a name and a format definition The name is the name of a partition or token """ super(SyntaxHighlighter, self).__init__(parent) self._neditable = neditable self._old_search = None if self._neditable: self.connect(self._neditable, SIGNAL("checkersUpdated(PyQt_PyObject)"), self._rehighlight_checkers) if isinstance(partition_scanner, (list, tuple)): partition_scanner = PartitionScanner(partition_scanner) else: assert isinstance(partition_scanner, PartitionScanner), \ "PartitionScanner expected, got %r" % partition_scanner self.partition_scanner = partition_scanner self.scanner = scanner for inside_part, inside_scanner in list(scanner.items()): if isinstance(inside_scanner, (list, tuple)): inside_scanner = Scanner(inside_scanner) self.scanner[inside_part] = inside_scanner else: assert isinstance(inside_scanner, Scanner), \ "Scanner expected" self.formats = {} for f in formats: if isinstance(f, tuple): fname, f = f else: assert isinstance(f, (Format, dict)), \ "Format expected, got %r" % f if isinstance(f, basestring): f = (f,) # only color specified if isinstance(f, (tuple, list)): f = Format(*((fname,) + f)) elif isinstance(f, dict): f = Format(**dict(name=fname, **f)) else: assert isinstance(f, Format), "Format expected, got %r" % f f.tcf.setFontFamily(parent.defaultFont().family()) self.formats[f.name] = f.tcf # reduce name look-ups for better speed scan_inside = {} for inside_part, inside_scanner in list(self.scanner.items()): scan_inside[inside_part] = inside_scanner.scan self.get_scanner = scan_inside.get self.scan_partitions = partition_scanner.scan self.get_format = self.formats.get def __apply_proper_style(self, char_format, color): if settings.UNDERLINE_NOT_BACKGROUND: char_format.setUnderlineColor(color) char_format.setUnderlineStyle(QTextCharFormat.WaveUnderline) else: color.setAlpha(60) char_format.setBackground(color) def __highlight_checker(self, char_format, user_data, color_name): """Highlight the lines with lint errors.""" user_data.error = True color = QColor(color_name) self.__apply_proper_style(char_format, color) return char_format def __remove_error_highlight(self, char_format, user_data, color_name=None): user_data.error = False char_format.setUnderlineStyle(QTextCharFormat.NoUnderline) char_format.clearBackground() return char_format def highlightBlock(self, text): """automatically called by Qt""" text += "\n" previous_state = self.previousBlockState() new_state = previous_state # User data and errors block = self.currentBlock() user_data = get_user_data(block) user_data.clear_data() valid_error_line, highlight_errors, color = self.get_error_highlighter( block) # speed-up name-lookups get_format = self.get_format set_format = self.setFormat get_scanner = self.get_scanner for start, end, partition, new_state, is_inside in \ self.scan_partitions(previous_state, text): f = get_format(partition, None) if f: f = highlight_errors(f, user_data, color) set_format(start, end - start, f) elif valid_error_line: f = TextCharFormat() f = highlight_errors(f, user_data, color) set_format(start, end - start, f) if is_inside: scan = get_scanner(partition) if scan: for token, token_pos, token_end in scan(text[start:end]): f = get_format(token) if f: f = highlight_errors(f, user_data, color) set_format(start + token_pos, token_end - token_pos, f) if partition and partition == "string": user_data.add_str_group(start, end) block.setUserData(user_data) self.setCurrentBlockState(new_state) def get_error_highlighter(self, block): block_number = block.blockNumber() highlight_errors = self.__remove_error_highlight color = None valid_error_line = False if self._neditable: checkers = self._neditable.sorted_checkers for items in checkers: checker, color, _ = items if block_number in checker.checks: highlight_errors = self.__highlight_checker valid_error_line = True break return valid_error_line, highlight_errors, color def set_selected_word(self, word, partial=False): """Set the word to highlight.""" hl_worthy = len(word) > 1 if hl_worthy: suffix = "(?![A-Za-z_\\d])" prefix = "(?<![A-Za-z_\\d])" word = re.escape(word) if not partial: word = "%s%s%s" % (prefix, word, suffix) self.scanner[None].add_token(('highlight_word', word)) else: self.scanner[None].add_token(('highlight_word', "")) lines = [] pat_find = re.compile(word) document = self.document() for lineno, text in enumerate(document.toPlainText().splitlines()): if hl_worthy and pat_find.search(text): lines.append(lineno) elif self._old_search and self._old_search.search(text): lines.append(lineno) # Ask perrito if i don't know what the next line does: self._old_search = hl_worthy and pat_find self.rehighlight_lines(lines) def _rehighlight_lines(self, lines): """If the document is valid, highlight the list of lines received.""" if self.document() is None: return for line in lines: block = self.document().findBlockByNumber(line) self.document().markContentsDirty(block.position(), block.position() + block.length()) self.rehighlightBlock(block) def _get_errors_lines(self): """Return the number of lines that contains errors to highlight.""" errors_lines = [] block = self.document().begin() while block.isValid(): user_data = get_user_data(block) if user_data.error: errors_lines.append(block.blockNumber()) block = block.next() return errors_lines def _rehighlight_checkers(self): checkers = self._neditable.registered_checkers lines = [] for item in checkers: checker, _, _ = item lines += list(checker.checks.keys()) self.rehighlight_lines(lines, errors=True) def rehighlight_lines(self, lines, errors=True): """Rehighlight the lines for errors or selected words.""" if errors: errors_lines = self._get_errors_lines() refresh_lines = set(lines + errors_lines) else: refresh_lines = set(lines) self._rehighlight_lines(refresh_lines) def _create_scheme(): scheme = { "syntax_comment": dict(color=resources.CUSTOM_SCHEME.get( "Comment", resources.COLOR_SCHEME["Comment"]), italic=True), "syntax_string": resources.CUSTOM_SCHEME.get( "SingleQuotedString", resources.COLOR_SCHEME["SingleQuotedString"]), "syntax_builtin": resources.CUSTOM_SCHEME.get( "Decorator", resources.COLOR_SCHEME["Decorator"]), "syntax_keyword": (resources.CUSTOM_SCHEME.get( "Keyword", resources.COLOR_SCHEME["Keyword"]), True), "syntax_definition": (resources.CUSTOM_SCHEME.get( "FunctionMethodName", resources.COLOR_SCHEME["FunctionMethodName"]), True), "syntax_braces": resources.CUSTOM_SCHEME.get( "Brace", resources.COLOR_SCHEME["Brace"]), "syntax_number": resources.CUSTOM_SCHEME.get( "Number", resources.COLOR_SCHEME["Number"]), "syntax_proper_object": resources.CUSTOM_SCHEME.get( "SelfReference", resources.COLOR_SCHEME["SelfReference"]), "syntax_operators": resources.CUSTOM_SCHEME.get( "Operator", resources.COLOR_SCHEME["Operator"]), "syntax_highlight_word": dict(color=resources.CUSTOM_SCHEME.get( "SelectedWord", resources.COLOR_SCHEME["SelectedWord"]), background=resources.CUSTOM_SCHEME.get( "SelectedWordBackground", resources.COLOR_SCHEME["SelectedWordBackground"])), "syntax_pending": resources.COLOR_SCHEME["Pending"], } return scheme def load_syntax(syntax): context = _create_scheme() or {} partition_scanner = PartitionScanner(syntax.get("partitions", [])) scanners = {} for part_name, part_scanner in list(syntax.get("scanner", {}).items()): scanners[part_name] = Scanner(part_scanner) formats = [] for fname, fstyle in list(syntax.get("formats", {}).items()): if isinstance(fstyle, basestring): if fstyle.startswith("%(") and fstyle.endswith(")s"): key = fstyle[2:-2] fstyle = context[key] else: fstyle = fstyle % context formats.append((fname, fstyle)) return partition_scanner, scanners, formats
19,282
Python
.py
459
31
80
0.576944
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,505
mixin.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/mixin.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtGui import QTextCursor from PyQt5.QtCore import QPoint class EditorMixin(object): @property def cursor_position(self): """Get or set the current cursor position""" cursor = self.textCursor() return (cursor.blockNumber(), cursor.columnNumber()) @cursor_position.setter def cursor_position(self, position): line, column = position line = min(line, self.line_count() - 1) column = min(column, len(self.line_text(line))) cursor = QTextCursor(self.document().findBlockByNumber(line)) cursor.setPosition(cursor.block().position() + column, QTextCursor.MoveAnchor) self.setTextCursor(cursor) def first_visible_block(self): return self.firstVisibleBlock() def last_visible_block(self): return self.cursorForPosition( QPoint(0, self.viewport().height())).block() def selection_range(self): """Returns the start and end number of selected lines""" text_cursor = self.textCursor() start = self.document().findBlock( text_cursor.selectionStart()).blockNumber() end = self.document().findBlock( text_cursor.selectionEnd()).blockNumber() if text_cursor.columnNumber() == 0 and start != end: end -= 1 return start, end def selected_text(self): """Returns the selected text""" return self.textCursor().selectedText() def has_selection(self): return self.textCursor().hasSelection() def get_right_word(self): """Gets the word on the right of the text cursor""" cursor = self.textCursor() cursor.movePosition(QTextCursor.WordRight, QTextCursor.KeepAnchor) return cursor.selectedText().strip() def get_right_character(self): """Gets the right character on the right of the text cursor""" right_word = self.get_right_word() right_char = None if right_word: right_char = right_word[0] return right_char def move_up_down(self, up=False): cursor = self.textCursor() move = cursor with self: has_selection = cursor.hasSelection() start, end = cursor.selectionStart(), cursor.selectionEnd() if has_selection: move.setPosition(start) move.movePosition(QTextCursor.StartOfBlock) move.setPosition(end, QTextCursor.KeepAnchor) m = QTextCursor.EndOfBlock if move.atBlockStart(): m = QTextCursor.Left move.movePosition(m, QTextCursor.KeepAnchor) else: move.movePosition(QTextCursor.StartOfBlock) move.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) text = cursor.selectedText() move.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) move.removeSelectedText() if up: move.movePosition(QTextCursor.PreviousBlock) move.insertBlock() move.movePosition(QTextCursor.Left) else: move.movePosition(QTextCursor.EndOfBlock) if move.atBlockStart(): move.movePosition(QTextCursor.NextBlock) move.insertBlock() move.movePosition(QTextCursor.Left) else: move.insertBlock() start = move.position() move.clearSelection() move.insertText(text) end = move.position() if has_selection: move.setPosition(end) move.setPosition(start, QTextCursor.KeepAnchor) else: move.setPosition(start) self.setTextCursor(move) def duplicate_line(self): cursor = self.textCursor() if cursor.hasSelection(): text = cursor.selectedText() start = cursor.selectionStart() end = cursor.selectionEnd() cursor_at_start = cursor.position() == start cursor.setPosition(end) cursor.insertText("\n" + text) cursor.setPosition(end if cursor_at_start else start) cursor.setPosition(start if cursor_at_start else end, QTextCursor.KeepAnchor) else: position = cursor.position() block = cursor.block() text = block.text() + "\n" cursor.setPosition(block.position()) cursor.insertText(text) cursor.setPosition(position) self.setTextCursor(cursor) def line_text(self, line=-1): """Returns the text of the specified line""" if line == -1: line, _ = self.cursor_position block = self.document().findBlockByNumber(line) return block.text() def line_count(self): """Returns the number of lines""" return self.document().blockCount() @property def text(self): """Get or set the plain text editor's content. The previous contents are removed.""" return self.toPlainText() @text.setter def text(self, text): self.setPlainText(text) def insert_text(self, text): if not self.isReadOnly(): self.textCursor().insertText(text) def line_indent(self, line=-1): """Returns the indentation level of `line`""" if line == -1: line, _ = self.cursor_position text = self.line_text(line) indentation = len(text) - len(text.lstrip()) return indentation def select_lines(self, start=0, end=0): """Selects enteri lines between start and end line numbers""" if end == -1: end = self.line_count() - 1 if start < 0: start = 0 cursor = self.textCursor() block = self.document().findBlockByNumber(start) cursor.setPosition(block.position()) if end > start: cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor, end - start) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) elif end < start: cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.Up, QTextCursor.KeepAnchor, start - end) cursor.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) else: cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) self.setTextCursor(cursor) def go_to_line(self, lineno, column=0, center=True): """Go to an specific line""" if self.line_count() >= lineno: self.cursor_position = lineno, column if center: self.centerCursor() else: self.ensureCursorVisible() self.addBackItemNavigation.emit() def text_before_cursor(self, text_cursor=None): if text_cursor is None: text_cursor = self.textCursor() text_block = text_cursor.block().text() return text_block[:text_cursor.positionInBlock()]
8,052
Python
.py
191
31.356021
78
0.608874
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,506
_editor.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/_editor.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import re import bisect from tokenize import generate_tokens, TokenError try: from StringIO import StringIO except BaseException: from io import StringIO from PyQt4.QtGui import QAction from PyQt4.QtGui import QInputDialog from PyQt4.QtGui import QMenu from PyQt4.QtGui import QColor from PyQt4.QtGui import QKeySequence from PyQt4.QtCore import SIGNAL from PyQt4.QtCore import QMimeData from PyQt4.QtCore import Qt from PyQt4.QtCore import QTimer from ninja_ide import resources from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide.gui.editor import highlighter from ninja_ide.gui.editor import helpers from ninja_ide.gui.editor import minimap from ninja_ide.gui.editor import document_map from ninja_ide.extensions import handlers from PyQt4.Qsci import QsciScintilla # , QsciCommand from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.gui.editor.editor') BRACE_DICT = {')': '(', ']': '[', '}': '{', '(': ')', '[': ']', '{': '}'} class Editor(QsciScintilla): ############################################################################### # EDITOR SIGNALS ############################################################################### """ modificationChanged(bool) fileSaved(QPlainTextEdit) locateFunction(QString, QString, bool) [functionName, filePath, isVariable] openDropFile(QString) addBackItemNavigation() findOcurrences(QString) cursorPositionChange(int, int) #row, col migrationAnalyzed() currentLineChanged(int) """ ############################################################################### __indicator_word = 0 __indicator_folded = 2 __indicator_navigation = 3 def _configure_qscintilla(self): self._first_visible_line = 0 self.patFold = re.compile( r"(\s)*\"\"\"|(\s)*def |(\s)*class |(\s)*if |(\s)*while |" "(\\s)*else:|(\\s)*elif |(\\s)*for |" "(\\s)*try:|(\\s)*except:|(\\s)*except |(.)*\\($") self.setAutoIndent(True) self.setBackspaceUnindents(True) self.setCaretLineVisible(True) line_color = QColor( resources.CUSTOM_SCHEME.get( 'CurrentLine', resources.COLOR_SCHEME['CurrentLine'])) caretColor = QColor( resources.CUSTOM_SCHEME.get( 'Caret', resources.COLOR_SCHEME['Caret'])) self.setCaretLineBackgroundColor(line_color) self.setCaretForegroundColor(caretColor) self.setBraceMatching(QsciScintilla.StrictBraceMatch) self.SendScintilla(QsciScintilla.SCI_SETBUFFEREDDRAW, 0) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.setMatchedBraceBackgroundColor(QColor( resources.CUSTOM_SCHEME.get( 'BraceBackground', resources.COLOR_SCHEME.get('BraceBackground')))) self.setMatchedBraceForegroundColor(QColor( resources.CUSTOM_SCHEME.get( 'BraceForeground', resources.COLOR_SCHEME.get('BraceForeground')))) self.SendScintilla(QsciScintilla.SCI_INDICSETFORE, self.__indicator_word, int(resources.get_color_hex("SelectedWord"), 16)) self.SendScintilla(QsciScintilla.SCI_INDICSETSTYLE, self.__indicator_word, 6) self.SendScintilla(QsciScintilla.SCI_INDICSETFORE, self.__indicator_folded, int("ffffff", 16)) self.SendScintilla(QsciScintilla.SCI_INDICSETSTYLE, self.__indicator_folded, 0) self._navigation_highlight_active = False self.SendScintilla(QsciScintilla.SCI_INDICSETFORE, self.__indicator_navigation, int(resources.get_color_hex("LinkNavigate"), 16)) self.SendScintilla(QsciScintilla.SCI_INDICSETSTYLE, self.__indicator_navigation, 8) self.SendScintilla(QsciScintilla.SCI_INDICSETALPHA, self.__indicator_navigation, 40) # Sets QScintilla into unicode mode self.SendScintilla(QsciScintilla.SCI_SETCODEPAGE, 65001) # Enable multiple selection self.SendScintilla(QsciScintilla.SCI_SETMULTIPLESELECTION, 1) self.SendScintilla(QsciScintilla.SCI_SETADDITIONALSELECTIONTYPING, 1) def __init__(self, neditable): super(Editor, self).__init__() self._neditable = neditable # QScintilla Configuration self._configure_qscintilla() # Markers self.foldable_lines = [] self.breakpoints = [] self.bookmarks = [] self.search_lines = [] self._fold_expanded_marker = 1 self._fold_collapsed_marker = 2 self._bookmark_marker = 3 self._breakpoint_marker = 4 self.setMarginSensitivity(1, True) self.connect( self, SIGNAL('marginClicked(int, int, Qt::KeyboardModifiers)'), self.on_margin_clicked) color_fore = resources.get_color("FoldArea") # Marker Fold Expanded self.markerDefine(QsciScintilla.DownTriangle, self._fold_expanded_marker) color = resources.get_color("FoldArrowExpanded") self.setMarkerBackgroundColor(QColor(color), self._fold_expanded_marker) self.setMarkerForegroundColor(QColor(color_fore), self._fold_expanded_marker) # Marker Fold Collapsed self.markerDefine(QsciScintilla.RightTriangle, self._fold_collapsed_marker) color = resources.get_color("FoldArrowCollapsed") self.setMarkerBackgroundColor(QColor(color), self._fold_collapsed_marker) self.setMarkerForegroundColor(QColor(color_fore), self._fold_collapsed_marker) # Marker Breakpoint self.markerDefine(QsciScintilla.Circle, self._breakpoint_marker) self.setMarkerBackgroundColor(QColor(255, 11, 11), self._breakpoint_marker) self.setMarkerForegroundColor(QColor(color_fore), self._breakpoint_marker) # Marker Bookmark self.markerDefine(QsciScintilla.SmallRectangle, self._bookmark_marker) self.setMarkerBackgroundColor(QColor(10, 158, 227), self._bookmark_marker) self.setMarkerForegroundColor(QColor(color_fore), self._bookmark_marker) # Configure key bindings self._configure_keybindings() self.lexer = highlighter.get_lexer(self._neditable.extension()) if self.lexer is not None: self.setLexer(self.lexer) # Config Editor self._mini = None if settings.SHOW_MINIMAP: self._load_minimap(settings.SHOW_MINIMAP) self._docmap = None if settings.SHOW_DOCMAP: self._load_docmap(settings.SHOW_DOCMAP) self.cursorPositionChanged.connect(self._docmap.update) self._last_block_position = 0 self.set_flags() # FIXME this lang should be guessed in the same form as lexer. self.lang = highlighter.get_lang(self._neditable.extension()) self._cursor_line = self._cursor_index = -1 self.__lines_count = 0 self.pos_margin = 0 self._indentation_guide = 0 self._indent = 0 self.__font = None self.__encoding = None self.__positions = [] # Caret positions self.SCN_CHARADDED.connect(self._on_char_added) # FIXME these should be language bound self.allows_less_indentation = ['else', 'elif', 'finally', 'except'] self.set_font(settings.FONT) self._selected_word = '' self._patIsWord = re.compile('\\w+') # Completer # Dict functions for KeyPress self.preKeyPress = { Qt.Key_Backspace: self.__backspace, Qt.Key_Enter: self.__ignore_extended_line, Qt.Key_Return: self.__ignore_extended_line, # Qt.Key_Colon: self.__retreat_to_keywords, Qt.Key_BracketRight: self.__brace_completion, Qt.Key_BraceRight: self.__brace_completion, Qt.Key_ParenRight: self.__brace_completion, Qt.Key_Apostrophe: self.__quot_completion, Qt.Key_QuoteDbl: self.__quot_completion} self.postKeyPress = { Qt.Key_Enter: self.__auto_indent, Qt.Key_Return: self.__auto_indent, Qt.Key_BracketLeft: self.__complete_braces, Qt.Key_BraceLeft: self.__complete_braces, Qt.Key_ParenLeft: self.__complete_braces, Qt.Key_Apostrophe: self.__complete_quotes, Qt.Key_QuoteDbl: self.__complete_quotes} # Highlight word timer self._highlight_word_timer = QTimer() self._highlight_word_timer.setSingleShot(True) self._highlight_word_timer.timeout.connect(self.highlight_selected_word) # Highlight the words under cursor after 500 msec, starting when # the cursor changes position self.cursorPositionChanged.connect( lambda: self._highlight_word_timer.start(500)) self.connect(self, SIGNAL("linesChanged()"), self._update_sidebar) self.connect(self, SIGNAL("blockCountChanged(int)"), self._update_file_metadata) self.load_project_config() # Context Menu Options self.__actionFindOccurrences = QAction(self.tr("Find Usages"), self) self.connect(self.__actionFindOccurrences, SIGNAL("triggered()"), self._find_occurrences) ninjaide = IDE.get_service('ide') self.connect( ninjaide, SIGNAL("ns_preferences_editor_font(PyQt_PyObject)"), self.set_font) self.connect( ninjaide, SIGNAL("ns_preferences_editor_showTabsAndSpaces(PyQt_PyObject)"), self.set_flags) self.connect( ninjaide, SIGNAL("ns_preferences_editor_showIndentationGuide(PyQt_PyObject)"), self.set_flags) # TODO: figure it out it doesn´t work if gets shown after init self.connect(ninjaide, SIGNAL("ns_preferences_editor_minimapShow(PyQt_PyObject)"), self._load_minimap) self.connect(ninjaide, SIGNAL("ns_preferences_editor_docmapShow(PyQt_PyObject)"), self._load_docmap) self.connect( ninjaide, SIGNAL("ns_preferences_editor_indent(PyQt_PyObject)"), self.load_project_config) self.connect( ninjaide, SIGNAL("ns_preferences_editor_marginLine(PyQt_PyObject)"), self._set_margin_line) self.connect( ninjaide, SIGNAL("ns_preferences_editor_showLineNumbers(PyQt_PyObject)"), self._show_line_numbers) self.connect(ninjaide, SIGNAL( "ns_preferences_editor_errorsUnderlineBackground(PyQt_PyObject)"), self._change_indicator_style) # self.connect( # ninjaide, # self.restyle) # self.connect( # ninjaide, # lambda: self.restyle()) self.additional_builtins = None # Set the editor after initialization if self._neditable.editor: self.setDocument(self._neditable.document) else: self._neditable.set_editor(self) if self._neditable.file_path in settings.BREAKPOINTS: self.breakpoints = settings.BREAKPOINTS[self._neditable.file_path] if self._neditable.file_path in settings.BOOKMARKS: self.bookmarks = settings.BOOKMARKS[self._neditable.file_path] # Add breakpoints for line in self.breakpoints: self.markerAdd(line, self._breakpoint_marker) # Add bookmarks for line in self.bookmarks: self.markerAdd(line, self._bookmark_marker) self.connect( self._neditable, SIGNAL("checkersUpdated(PyQt_PyObject)"), self._highlight_checkers) @property def display_name(self): self._neditable.display_name @property def nfile(self): return self._neditable.nfile @property def neditable(self): return self._neditable @property def file_path(self): return self._neditable.file_path @property def is_modified(self): return self.isModified() def _configure_keybindings(self): self.SendScintilla(QsciScintilla.SCI_ASSIGNCMDKEY, QsciScintilla.SCI_HOMEDISPLAY, Qt.Key_Home) def on_margin_clicked(self, nmargin, nline, modifiers): position = self.positionFromLineIndex(nline, 0) length = self.lineLength(nline) if nline in self.contractedFolds(): self.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, self.__indicator_folded) self.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, position, length) self.markerDelete(nline, self._fold_collapsed_marker) self.markerAdd(nline, self._fold_expanded_marker) self.foldLine(nline) if self._mini: self._mini.fold(nline) elif nline in self.foldable_lines: self.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, self.__indicator_folded) self.SendScintilla(QsciScintilla.SCI_INDICATORFILLRANGE, position, length) self.markerDelete(nline, self._fold_expanded_marker) self.markerAdd(nline, self._fold_collapsed_marker) self.foldLine(nline) if self._mini: self._mini.fold(nline) else: self.handle_bookmarks_breakpoints(nline, modifiers) def handle_bookmarks_breakpoints(self, line, modifiers): # Breakpoints Default marker = self._breakpoint_marker list_markers = self.breakpoints if modifiers == Qt.ControlModifier: # Bookmarks marker = self._bookmark_marker list_markers = self.bookmarks if self.markersAtLine(line) != 0: self.markerDelete(line, marker) list_markers.remove(line) else: self.markerAdd(line, marker) list_markers.append(line) self._save_breakpoints_bookmarks() def _change_indicator_style(self, underline): ncheckers = len(self._neditable.sorted_checkers) indicator_style = QsciScintilla.INDIC_SQUIGGLE if not underline: indicator_style = QsciScintilla.INDIC_STRAIGHTBOX indicator_index = 4 for i in range(ncheckers): self.SendScintilla(QsciScintilla.SCI_INDICSETSTYLE, indicator_index, indicator_style) indicator_index += 1 def _save_breakpoints_bookmarks(self): if self.bookmarks and not self._neditable.new_document: settings.BOOKMARKS[self._neditable.file_path] = self.bookmarks elif self._neditable.file_path in settings.BOOKMARKS: settings.BOOKMARKS.pop(self._neditable.file_path) if self.breakpoints and not self._neditable.new_document: settings.BREAKPOINTS[self._neditable.file_path] = self.breakpoints elif self._neditable.file_path in settings.BREAKPOINTS: settings.BREAKPOINTS.pop(self._neditable.file_path) def _highlight_checkers(self, checkers): checkers = self._neditable.sorted_checkers indicator_index = 4 # Start from 4 (valid), before numbers are used painted_lines = [] for items in checkers: checker, color, _ = items lines = list(checker.checks.keys()) # Set current self.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, indicator_index) # Clear self.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, 0, len(self.text())) # Set Color color = color.replace("#", "") self.SendScintilla(QsciScintilla.SCI_INDICSETFORE, indicator_index, int(color, 16)) # Set Style indicator_style = QsciScintilla.INDIC_SQUIGGLE if not settings.UNDERLINE_NOT_BACKGROUND: indicator_style = QsciScintilla.INDIC_STRAIGHTBOX self.SendScintilla(QsciScintilla.SCI_INDICSETSTYLE, indicator_index, indicator_style) # Paint Lines for line in lines: if line in painted_lines: continue position = self.positionFromLineIndex(line, 0) length = self.lineLength(line) self.SendScintilla(QsciScintilla.SCI_INDICATORFILLRANGE, position, length) painted_lines.append(line) indicator_index += 1 def cursor_before_focus_lost(self): return self._cursor_line, self._cursor_index def load_project_config(self): ninjaide = IDE.get_service('ide') project = ninjaide.get_project_for_file(self._neditable.file_path) if project is not None: self._indent = project.indentation self.useTabs = project.use_tabs self.connect(project, SIGNAL("projectPropertiesUpdated()"), self.load_project_config) self.additional_builtins = project.additional_builtins else: self._indent = settings.INDENT self.useTabs = settings.USE_TABS self.additional_builtins = None self.setIndentationsUseTabs(self.useTabs) self.setIndentationWidth(self._indent) if self._mini: self._mini.setIndentationsUseTabs(self.useTabs) self._mini.setIndentationWidth(self._indent) self._set_margin_line(settings.MARGIN_LINE) def _update_sidebar(self): # Margin 0 is used for line numbers if settings.SHOW_LINE_NUMBERS: self.setMarginWidth(0, '0' * (len(str(self.lines())) + 1)) else: self.setMarginWidth(0, 0) # Fold self.foldable_lines = [] lines = self.lines() for line in range(lines): text = self.text(line) if self.patFold.match(text): self.foldable_lines.append(line) if line in self.contractedFolds(): self.markerDelete(line, self._fold_collapsed_marker) self.markerDelete(line, self._fold_expanded_marker) self.markerAdd(line, self._fold_collapsed_marker) else: self.markerDelete(line, self._fold_collapsed_marker) self.markerDelete(line, self._fold_expanded_marker) self.markerAdd(line, self._fold_expanded_marker) def _load_minimap(self, show): if show: if self._mini is None: self._mini = minimap.MiniMap(self) # Signals self.SCN_UPDATEUI.connect(self._mini.scroll_map) self.SCN_ZOOM.connect(self._mini.slider.update_position) self._mini.setDocument(self.document()) self._mini.setLexer(self.lexer) # FIXME: register syntax self._mini.show() self._mini.adjust_to_parent() elif self._mini is not None: # FIXME: lost doc pointer? self._mini.shutdown() self._mini.deleteLater() self._mini = None def _load_docmap(self, show): if show: if self._docmap is None: self._docmap = document_map.DocumentMap(self) self._docmap.initialize() elif self._docmap is not None: self._docmap.deleteLater() self._docmap = None # """Unindent some kind of blocks if needed.""" def __get_encoding(self): """Get the current encoding of 'utf-8' otherwise.""" if self.__encoding is not None: return self.__encoding return 'utf-8' def __set_encoding(self, encoding): """Set the current encoding.""" self.__encoding = encoding encoding = property(__get_encoding, __set_encoding) def set_flags(self): """Set some configuration flags for the Editor.""" if settings.ALLOW_WORD_WRAP: self.setWrapMode(QsciScintilla.WrapWord) else: self.setWrapMode(QsciScintilla.WrapNone) self.setMouseTracking(True) if settings.SHOW_TABS_AND_SPACES: self.setWhitespaceVisibility(QsciScintilla.WsVisible) else: self.setWhitespaceVisibility(QsciScintilla.WsInvisible) self.setIndentationGuides(settings.SHOW_INDENTATION_GUIDE) self.setEolVisibility(settings.USE_PLATFORM_END_OF_LINE) self.SendScintilla(QsciScintilla.SCI_SETENDATLASTLINE, settings.END_AT_LAST_LINE) def _update_file_metadata(self): """Update the info of bookmarks, breakpoint and checkers.""" new_count = self.lines() if (self.bookmarks or self.breakpoints): line, index = self.getCursorPosition() diference = new_count - self.__lines_count lineNumber = line - abs(diference) contains_text = self.lineLength(line) != 0 self._update_sidebar_marks(lineNumber, diference, contains_text) self.__lines_count = new_count def _update_sidebar_marks(self, lineNumber, diference, atLineStart=False): if self.breakpoints: self.breakpoints = helpers.add_line_increment( self.breakpoints, lineNumber, diference, atLineStart) if not self._neditable.new_document: settings.BREAKPOINTS[self._neditable.file_path] = \ self._breakpoints if self.bookmarks: self.bookmarks = helpers.add_line_increment( self.bookmarks, lineNumber, diference, atLineStart) if not self._neditable.new_document: settings.BOOKMARKS[self._neditable.file_path] = self._bookmarks def _show_line_numbers(self): self.setMarginsFont(self.__font) # Margin 0 is used for line numbers self.setMarginLineNumbers(0, settings.SHOW_LINE_NUMBERS) self._update_sidebar() def set_font(self, font): self.__font = font self.lexer.setFont(font) self._show_line_numbers() background = resources.CUSTOM_SCHEME.get( 'SidebarBackground', resources.COLOR_SCHEME['SidebarBackground']) foreground = resources.CUSTOM_SCHEME.get( 'SidebarForeground', resources.COLOR_SCHEME['SidebarForeground']) self.setMarginsBackgroundColor(QColor(background)) self.setMarginsForegroundColor(QColor(foreground)) def jump_to_line(self, lineno=None): """ Jump to a specific line number or ask to the user for the line """ if lineno is not None: self.emit(SIGNAL("addBackItemNavigation()")) self._cursor_line = self._cursor_index = -1 self.go_to_line(lineno) return maximum = self.lines() line = QInputDialog.getInt(self, self.tr("Jump to Line"), self.tr("Line:"), 1, 1, maximum, 1) if line[1]: self.emit(SIGNAL("addBackItemNavigation()")) self.go_to_line(line[0] - 1) def _find_occurrences(self): if self.hasSelectedText(): word = self.selectedText() else: word = self._text_under_cursor() self.emit(SIGNAL("findOcurrences(QString)"), word) def go_to_line(self, lineno): """ Go to an specific line """ if self.lines() >= lineno: self.setCursorPosition(lineno, 0) def zoom_in(self): self.zoomIn() def zoom_out(self): self.zoomOut() def _set_margin_line(self, margin=None): color_margin = QColor(resources.CUSTOM_SCHEME.get( "MarginLine", resources.COLOR_SCHEME["MarginLine"])) self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(margin) self.setEdgeColor(color_margin) def set_cursor_position(self, line, index=0): if self.lines() >= line: self._first_visible_line = line self._cursor_line = self._cursor_index = -1 self.setCursorPosition(line, index) def add_caret(self): """ Adds additional caret in current position """ cur_pos = self.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS) if cur_pos not in self.__positions: self.__positions.append(cur_pos) # Same position arguments is use for just adding carets # rather than selections. for e, pos in enumerate(self.__positions): if e == 0: # The first selection should be added with SCI_SETSELECTION # and later selections added with SCI_ADDSELECTION self.SendScintilla(QsciScintilla.SCI_CLEARSELECTIONS) self.SendScintilla(QsciScintilla.SCI_SETSELECTION, pos, pos) else: self.SendScintilla(QsciScintilla.SCI_ADDSELECTION, pos, pos) def _on_char_added(self): """ When char is added, cursors change position. This function obtains new positions and adds them to the list of positions. """ # For rectangular selection if not self.__positions: return selections = self.SendScintilla(QsciScintilla.SCI_GETSELECTIONS) if selections > 1: for sel in range(selections): new_pos = self.SendScintilla( QsciScintilla.SCI_GETSELECTIONNCARET, sel) self.__positions[sel] = new_pos def indent_less(self): if self.hasSelectedText(): self.SendScintilla(QsciScintilla.SCI_BEGINUNDOACTION, 1) line_from, _, line_to, _ = self.getSelection() for i in range(line_from, line_to): self.unindent(i) self.SendScintilla(QsciScintilla.SCI_ENDUNDOACTION, 1) else: line, _ = self.getCursorPosition() self.unindent(line) def indent_more(self): if self.hasSelectedText(): self.SendScintilla(QsciScintilla.SCI_BEGINUNDOACTION, 1) line_from, _, line_to, _ = self.getSelection() for i in range(line_from, line_to): self.indent(i) self.SendScintilla(QsciScintilla.SCI_ENDUNDOACTION, 1) else: line, _ = self.getCursorPosition() self.indent(line) def find_match(self, expr, reg, cs, wo, wrap=True, forward=True, line=-1, index=-1): if self.hasSelectedText(): line, index, lto, ito = self.getSelection() index += 1 elif line < 0 or index < 0: line, index = self._cursor_line, self._cursor_index found = self.findFirst(expr, reg, cs, wo, wrap, forward, line, index) if found: self.highlight_selected_word(expr, case_sensitive=cs) return self._get_find_index_result(expr, cs, wo) else: return 0, 0 def _get_find_index_result(self, expr, cs, wo): text = self.text() hasSearch = len(expr) > 0 current_index = 0 if wo: pattern = r'\b%s\b' % expr temp_text = ' '.join(re.findall(pattern, text, re.IGNORECASE)) text = temp_text if temp_text != '' else text if cs: search = expr totalMatches = text.count(expr) else: text = text.lower() search = expr.lower() totalMatches = text.count(search) if hasSearch and totalMatches > 0: line, index, lto, ito = self.getSelection() position = self.positionFromLineIndex(line, index) current_index = text[:position].count(search) if current_index <= totalMatches: index = current_index else: index = text.count(search) + 1 else: index = 0 totalMatches = 0 return current_index + 1, totalMatches def replace_match(self, wordOld, wordNew, allwords=False, selection=False): """Find if searched text exists and replace it with new one. If there is a selection just do it inside it and exit. """ if selection and self.hasSelectedText(): lstart, istart, lend, iend = self.getSelection() text = self.selectedText() max_replace = -1 # all text = text.replace(wordOld, wordNew, max_replace) self.replaceSelectedText(text) return self.SendScintilla(QsciScintilla.SCI_BEGINUNDOACTION, 1) line, index, lto, ito = self.getSelection() self.replace(wordNew) while allwords: result = self.findNext() if result: self.replace(wordNew) else: break if allwords: self.setCursorPosition(line, index) self.SendScintilla(QsciScintilla.SCI_ENDUNDOACTION, 1) def focusInEvent(self, event): super(Editor, self).focusInEvent(event) self.emit(SIGNAL("editorFocusObtained()")) selected = False if self.hasSelectedText(): selected = True line, index, lto, ito = self.getSelection() else: line, index = self._cursor_line, self._cursor_index if line != -1: self.setCursorPosition(line, index) if selected: self.setSelection(line, index, lto, ito) self.SendScintilla(QsciScintilla.SCI_SETFIRSTVISIBLELINE, self._first_visible_line) def focusOutEvent(self, event): """Hide Popup on focus lost.""" self._first_visible_line = int( self.SendScintilla(QsciScintilla.SCI_GETFIRSTVISIBLELINE)) self._cursor_line, self._cursor_index = self.getCursorPosition() super(Editor, self).focusOutEvent(event) def resizeEvent(self, event): super(Editor, self).resizeEvent(event) if self._mini: self._mini.adjust_to_parent() if self._docmap: self._docmap.adjust() def __backspace(self, event): if self.hasSelectedText(): return False line, index = self.getCursorPosition() text = self.text(line) if index < len(text): char = text[index - 1] next_char = text[index] if (char in settings.BRACES and next_char in settings.BRACES.values()) \ or (char in settings.QUOTES and next_char in settings.QUOTES.values()): self.setSelection(line, index - 1, line, index) self.removeSelectedText() def __ignore_extended_line(self, event): if event.modifiers() == Qt.ShiftModifier: return True def __reverse_select_text_portion_from_offset(self, begin, end): """Backwards select text, go from current+begin to current - end possition, returns text""" line, index = self.getCursorPosition() text = self.text(line) cursor_position = index # QT silently fails on invalid position, ergo breaks when EOF < begin while ((index + begin) == index) and begin > 0: begin -= 1 index = cursor_position + begin return text[index:cursor_position - end] def __quot_completion(self, event): """Indicate if this is some sort of quote that needs to be completed This is a very simple boolean table, given that quotes are a simmetrical symbol, is a little more cumbersome guessing the completion table. """ text = event.text() line, index = self.getCursorPosition() PENTA_Q = 5 * text TETRA_Q = 4 * text TRIPLE_Q = 3 * text DOUBLE_Q = 2 * text supress_echo = False pre_context = self.__reverse_select_text_portion_from_offset(0, 3) pos_context = self.__reverse_select_text_portion_from_offset(3, 0) if pre_context == pos_context == TRIPLE_Q: supress_echo = True elif pos_context[:2] == DOUBLE_Q: pre_context = self.__reverse_select_text_portion_from_offset(0, 4) if pre_context == TETRA_Q: supress_echo = True elif pos_context[:1] == text: pre_context = self.__reverse_select_text_portion_from_offset(0, 5) if pre_context == PENTA_Q: supress_echo = True elif pre_context[-1] == text: supress_echo = True if supress_echo: line, index = self.getCursorPosition() self.setCursorPosition(line, index + 1) return supress_echo def __brace_completion(self, event): """Indicate if this symbol is part of a given pair and needs to be completed. """ text = event.text() if text in list(settings.BRACES.values()): line, index = self.getCursorPosition() line_text = self.text(line) portion = line_text[index - 1:index + 1] brace_open = portion[0] brace_close = (len(portion) > 1) and portion[1] or None balance = BRACE_DICT.get(brace_open, None) == text == brace_close if balance: self.setCursorPosition(line, index + 1) return True def __auto_indent(self, event): line, index = self.getCursorPosition() text = self.text(line - 1).strip() symbols_to_look = tuple(settings.BRACES.keys()) + (",",) if text and text[-1] in symbols_to_look: symbol = " " * self._indent if self.useTabs: symbol = "\t" self.insertAt(symbol, line, index) self.setCursorPosition(line, index + self._indent) if settings.COMPLETE_DECLARATIONS and text and text[-1] == ":": helpers.check_for_assistance_completion(self, text) def complete_declaration(self): settings.COMPLETE_DECLARATIONS = not settings.COMPLETE_DECLARATIONS self.insert_new_line() settings.COMPLETE_DECLARATIONS = not settings.COMPLETE_DECLARATIONS def insert_new_line(self): line, index = self.getCursorPosition() length = self.lineLength(line) - 1 at_block_end = index == length self.insertAt("\n", line, length) if not at_block_end: length = self.lineLength(line + 1) self.setCursorPosition(line + 1, length) self.__auto_indent(None) def __complete_braces(self, event): """Complete () [] and {} using a mild inteligence to see if corresponds and also do some more magic such as complete in classes and functions. """ brace = event.text() if brace not in settings.BRACES: # Thou shalt not waste cpu cycles if this brace compleion dissabled return line, index = self.getCursorPosition() text = self.text(line) complementary_brace = BRACE_DICT.get(brace) token_buffer = [] _, tokens = self.__tokenize_text(text) is_unbalance = 0 for tkn_type, tkn_rep, tkn_begin, tkn_end in tokens: if tkn_rep == brace: is_unbalance += 1 elif tkn_rep == complementary_brace: is_unbalance -= 1 if tkn_rep.strip() != "": token_buffer.append((tkn_rep, tkn_end[1])) is_unbalance = (is_unbalance >= 0) and is_unbalance or 0 if (self.lang == "python") and (len(token_buffer) == 3) and \ (token_buffer[2][0] == brace) and (token_buffer[0][0] in ("def", "class")): self.insertAt("):", line, index) # are we in presence of a function? # TODO: IMPROVE THIS AND GENERALIZE IT WITH INTELLISENSEI if token_buffer[0][0] == "def": symbols_handler = handlers.get_symbols_handler('py') split_source = self.text().split("\n") indent = re.match('^\\s+', str(split_source[line])) indentation = (indent.group() + " " * self._indent if indent is not None else " " * self._indent) new_line = "%s%s" % (indentation, 'pass') split_source.insert(line + 1, new_line) source = '\n'.join(split_source) source = source.encode(self.encoding) _, symbols_simplified = symbols_handler.obtain_symbols( source, simple=True, only_simple=True) symbols_index = sorted(symbols_simplified.keys()) symbols_simplified = sorted( list(symbols_simplified.items()), key=lambda x: x[0]) index_symbol = bisect.bisect(symbols_index, line) if (index_symbol >= len(symbols_index) or symbols_index[index_symbol] > (line + 1)): index -= 1 belongs_to_class = symbols_simplified[index_symbol][1][2] if belongs_to_class: self.insertAt("self", line, index) index += 4 if self.selected_text != "": self.insertAt(", ", line, index) index += 2 self.insertAt(self.selected_text, line, index) self.setCursorPosition(line, index) elif (token_buffer and (not is_unbalance) and self.selected_text): self.insertAt(self.selected_text, line, index) elif is_unbalance: next_char = text[index:index + 1].strip() if self.selected_text or next_char == "": self.insertAt(complementary_brace, line, index) self.insertAt(self.selected_text, line, index) def __complete_quotes(self, event): """ Completion for single and double quotes, which since are simmetrical symbols used for different things can not be balanced as easily as braces or equivalent. """ line, index = self.getCursorPosition() symbol = event.text() if symbol in settings.QUOTES: pre_context = self.__reverse_select_text_portion_from_offset(0, 3) if pre_context == 3 * symbol: self.insertAt(3 * symbol, line, index) else: self.insertAt(symbol, line, index) self.insertAt(self.selected_text, line, index) def clear_additional_carets(self): reset_pos = self.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS) self.__positions = [] self.SendScintilla(QsciScintilla.SCI_CLEARSELECTIONS) self.SendScintilla(QsciScintilla.SCI_SETSELECTION, reset_pos, reset_pos) def keyPressEvent(self, event): # Completer pre key event # On Return == True stop the execution of this method if self.preKeyPress.get(event.key(), lambda x: False)(event): # emit a signal so that plugins can do their thing self.emit(SIGNAL("keyPressEvent(QEvent)"), event) return self.selected_text = self.selectedText() self._check_auto_copy_cut(event) # Clear additional carets if undo undo = event.matches(QKeySequence.Undo) if undo and self.__positions: self.clear_additional_carets() super(Editor, self).keyPressEvent(event) if event.key() == Qt.Key_Escape: self.clear_additional_carets() elif event.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down): if self.__positions: self.clear_additional_carets() if event.modifiers() == Qt.AltModifier: cur_pos = self.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS) if not self.__positions: self.__positions = [cur_pos] self.postKeyPress.get(event.key(), lambda x: False)(event) # Completer post key event # emit a signal so that plugins can do their thing self.emit(SIGNAL("keyPressEvent(QEvent)"), event) def keyReleaseEvent(self, event): super(Editor, self).keyReleaseEvent(event) line, _ = self.getCursorPosition() if line != self._last_block_position: self._last_block_position = line self.emit(SIGNAL("currentLineChanged(int)"), line) def _check_auto_copy_cut(self, event): """Convenience method, when the user hits Ctrl+C or Ctrl+X with no text selected, we automatically select the entire line under the cursor.""" copyOrCut = event.matches(QKeySequence.Copy) or \ event.matches(QKeySequence.Cut) if copyOrCut and not self.hasSelectedText(): line, index = self.getCursorPosition() length = self.lineLength(line) self.setSelection(line, 0, line, length) def _text_under_cursor(self): line, index = self.getCursorPosition() word = self.wordAtLineIndex(line, index) result = self._patIsWord.findall(word) word = result[0] if result else '' return word def wheelEvent(self, event, forward=True): if event.modifiers() == Qt.ControlModifier: if event.delta() > 0: self.zoom_in() elif event.delta() < 0: self.zoom_out() event.ignore() super(Editor, self).wheelEvent(event) def contextMenuEvent(self, event): popup_menu = self.createStandardContextMenu() menu_lint = QMenu(self.tr("Ignore Lint")) ignoreLineAction = menu_lint.addAction( self.tr("Ignore This Line")) ignoreSelectedAction = menu_lint.addAction( self.tr("Ignore Selected Area")) self.connect(ignoreLineAction, SIGNAL("triggered()"), lambda: helpers.lint_ignore_line(self)) self.connect(ignoreSelectedAction, SIGNAL("triggered()"), lambda: helpers.lint_ignore_selection(self)) popup_menu.insertSeparator(popup_menu.actions()[0]) popup_menu.insertMenu(popup_menu.actions()[0], menu_lint) popup_menu.insertAction(popup_menu.actions()[0], self.__actionFindOccurrences) # add extra menus (from Plugins) # show menu popup_menu.exec_(event.globalPos()) def mouseMoveEvent(self, event): position = event.pos() line = self.lineAt(position) checkers = self._neditable.sorted_checkers for items in checkers: checker, color, _ = items message = checker.message(line) if message: QToolTip.showText(self.mapToGlobal(position), message, self) if event.modifiers() == Qt.ControlModifier: self._navigation_highlight_active = True word = self.wordAtPoint(position) self.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, self.__indicator_navigation) self.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, 0, len(self.text())) text = self.text() word_length = len(word) index = text.find(word) while index != -1: self.SendScintilla(QsciScintilla.SCI_INDICATORFILLRANGE, index, word_length) index = text.find(word, index + 1) elif self._navigation_highlight_active: self._navigation_highlight_active = False self.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, self.__indicator_navigation) self.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, 0, len(self.text())) super(Editor, self).mouseMoveEvent(event) def mousePressEvent(self, event): super(Editor, self).mousePressEvent(event) if event.modifiers() == Qt.ControlModifier: self.go_to_definition() elif event.modifiers() == Qt.AltModifier: self.add_caret() else: self.clear_additional_carets() line, _ = self.getCursorPosition() if line != self._last_block_position: self._last_block_position = line self.emit(SIGNAL("currentLineChanged(int)"), line) def dropEvent(self, event): if len(event.mimeData().urls()) > 0: path = event.mimeData().urls()[0].path() self.emit(SIGNAL("openDropFile(QString)"), path) event.ignore() event.mimeData = QMimeData() super(Editor, self).dropEvent(event) self.undo() def go_to_definition(self): line, index = self.getCursorPosition() word = self.wordAtLineIndex(line, index) text = self.text(line) brace_pos = text.find("(", index) back_text = text[:index] dot_pos = back_text.rfind(".") prop_pos = back_text.rfind("@") is_function = (brace_pos != -1 and text[index:brace_pos + 1] in ("%s(" % word)) is_attribute = (dot_pos != -1 and text[dot_pos:index] in (".%s" % word)) is_property = (prop_pos != -1 and text[prop_pos:index] in ("@%s" % word)) if is_function or is_property: self.emit(SIGNAL("locateFunction(QString, QString, bool)"), word, self.file_path, False) elif is_attribute: self.emit(SIGNAL("locateFunction(QString, QString, bool)"), word, self.file_path, True) def __tokenize_text(self, text): invalid_syntax = False token_buffer = [] try: for tkn_type, tkn_rep, tkn_begin, tkn_end, _ in \ generate_tokens(StringIO(text).readline): token_buffer.append((tkn_type, tkn_rep, tkn_begin, tkn_end)) except (TokenError, IndentationError, SyntaxError): invalid_syntax = True return (invalid_syntax, token_buffer) def highlight_selected_word(self, word_find=None, case_sensitive=True, reset=False): """Highlight selected variable""" self.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, self.__indicator_word) word = self._text_under_cursor() if word_find is not None: word = word_find if word != self._selected_word and not reset: self.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, 0, len(self.text())) self._selected_word = word word_length = len(self._selected_word) text = self.text() search = self._selected_word if not case_sensitive: search = search.lower() text = text.lower() index = text.find(search) self.search_lines = [] # Restore search lines appendLine = self.search_lines.append while index != -1 and word: line = self.SendScintilla(QsciScintilla.SCI_LINEFROMPOSITION, index) if line not in self.search_lines: appendLine(line) self.SendScintilla(QsciScintilla.SCI_INDICATORFILLRANGE, index, word_length) index = text.find(search, index + 1) # FIXME: if self._docmap is not None: self._docmap.update() elif ((word == self._selected_word) and (word_find is None)) or reset: self.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, 0, len(self.text())) self._selected_word = None def to_upper(self): self.SendScintilla(QsciScintilla.SCI_BEGINUNDOACTION, 1) if self.hasSelectedText(): text = self.selectedText().upper() self.replaceSelectedText(text) self.SendScintilla(QsciScintilla.SCI_ENDUNDOACTION, 1) def to_lower(self): self.SendScintilla(QsciScintilla.SCI_BEGINUNDOACTION, 1) if self.hasSelectedText(): text = self.selectedText().lower() self.replaceSelectedText(text) self.SendScintilla(QsciScintilla.SCI_ENDUNDOACTION, 1) def to_title(self): self.SendScintilla(QsciScintilla.SCI_BEGINUNDOACTION, 1) if self.hasSelectedText(): text = self.selectedText().title() self.replaceSelectedText(text) self.SendScintilla(QsciScintilla.SCI_ENDUNDOACTION, 1) def create_editor(neditable): editor = Editor(neditable) return editor
50,733
Python
.py
1,114
33.741472
91
0.594973
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,507
neditable.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/neditable.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import collections from PyQt5.QtCore import QObject from PyQt5.QtCore import pyqtSignal from ninja_ide.core.file_handling import file_manager from ninja_ide.gui.editor import checkers from ninja_ide.gui.editor import helpers from ninja_ide.core import settings class NEditable(QObject): """ SIGNALS: @checkersUpdated(PyQt_PyObject) @askForSaveFileClosing(PyQt_PyObject) @fileClosing(PyQt_PyObject) @fileSaved(PyQt_PyObject) """ fileSaved = pyqtSignal('PyQt_PyObject') fileLoaded = pyqtSignal(['PyQt_PyObject'], [str]) canBeRecovered = pyqtSignal('PyQt_PyObject') fileRemoved = pyqtSignal('PyQt_PyObject') fileChanged = pyqtSignal('PyQt_PyObject') fileClosing = pyqtSignal('PyQt_PyObject') askForSaveFileClosing = pyqtSignal('PyQt_PyObject') checkersUpdated = pyqtSignal('PyQt_PyObject') def __init__(self, nfile=None): super(NEditable, self).__init__() self.__editor = None # Create NFile self._nfile = nfile self._has_checkers = False self.__language = None self.text_modified = False self.ignore_checkers = False # Hot exit and autosave feature from ninja_ide.core.file_handling import nswapfile self._swap_file = nswapfile.NSwapFile(self) # Checkers: self.registered_checkers = [] self._checkers_executed = 0 # Connect signals if self._nfile: self._nfile.fileClosing['QString', bool].connect(self._about_to_close_file) self._nfile.fileChanged.connect( lambda: self.fileChanged.emit(self)) self._nfile.fileRemoved.connect( self._on_file_removed_from_disk) def _on_file_removed_from_disk(self): # FIXME: maybe we should ask for save, save as... pass def extension(self): # FIXME This sucks, we should have a way to define lang if self._nfile is None: return "" return self._nfile.file_ext() def language(self): if self.__language is None: self.__language = settings.LANGUAGE_MAP.get(self.extension()) if self.__language is None and self._nfile.is_new_file: self.__language = "python" return self.__language def _about_to_close_file(self, path, force_close): modified = False if self.__editor: modified = self.__editor.is_modified if modified and not force_close: self.askForSaveFileClosing.emit(self) else: self._nfile.remove_watcher() self.fileClosing.emit(self) def clone(self): clone = self.__class__(self._nfile) return clone def set_editor(self, editor): """Set the Editor (UI component) associated with this object.""" self.__editor = editor # If we have an editor, let's include the checkers: self.include_checkers(self.language()) content = '' if not self._nfile.is_new_file: content = self._nfile.read() self._nfile.start_watching() self.__editor.text = content self.__editor.document().setModified(False) encoding = file_manager.get_file_encoding(content) self.__editor.encoding = encoding if not self.ignore_checkers: self.run_checkers(content) else: self.ignore_checkers = False # New file then try to add a coding line if not content: helpers.insert_coding_line(self.__editor) self.fileLoaded.emit(self) self.fileLoaded[str].emit(self.file_path) def reload_file(self): if self._nfile: content = self._nfile.read() self._nfile.start_watching() self.__editor.text = content self.__editor.document().setModified(False) encoding = file_manager.get_file_encoding(content) self.__editor.encoding = encoding if not self.ignore_checkers: self.run_checkers(content) else: self.ignore_checkers = False def discard(self): self._swap_file.discard() def recover(self): self._swap_file.recover() @property def file_path(self): return self._nfile.file_path @property def document(self): if self.__editor: return self.__editor.document() return None @property def display_name(self): return self._nfile.display_name @property def new_document(self): return self._nfile.is_new_file @property def has_checkers(self): """Return True if checkers where installaed, False otherwise""" return self._has_checkers @property def editor(self): return self.__editor @property def nfile(self): return self._nfile @property def sorted_checkers(self): return sorted(self.registered_checkers, key=lambda x: x[2], reverse=True) @property def is_dirty(self): dirty = False for items in self.registered_checkers: checker, _, _ = items if checker.dirty: dirty = True break return dirty def save_content(self, path=None, force=False): """Save the content of the UI to a file.""" if self.__editor.is_modified or force: content = self.__editor.text nfile = self._nfile.save(content, path) self._nfile = nfile if not self.ignore_checkers: self.run_checkers(content) else: self.ignore_checkers = False self.__editor.document().setModified(False) self.fileSaved.emit(self) def include_checkers(self, lang='python'): """Initialize the Checkers, should be refreshed on checkers change.""" self.registered_checkers = sorted(checkers.get_checkers_for(lang), key=lambda x: x[2]) self._has_checkers = len(self.registered_checkers) > 0 for i, values in enumerate(self.registered_checkers): Checker, color, priority = values check = Checker(self.__editor) self.registered_checkers[i] = (check, color, priority) check.finished.connect(self.show_checkers_notifications) def run_checkers(self, content, path=None, encoding=None): for items in self.registered_checkers: checker = items[0] checker.run_checks() def show_checkers_notifications(self): """Show the notifications obtained for the proper checker.""" self._checkers_executed += 1 if self._checkers_executed == len(self.registered_checkers): self._checkers_executed = 0 self.checkersUpdated.emit(self) def update_checkers_display(self): for items in self.registered_checkers: checker, _, _ = items func = getattr(checker, 'refresh_display', None) if isinstance(func, collections.Callable): func()
7,928
Python
.py
201
30.383085
78
0.623262
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,508
highlighter.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/highlighter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import re from PyQt5.QtGui import QSyntaxHighlighter from PyQt5.QtGui import QColor from PyQt5.QtGui import QTextCharFormat from PyQt5.QtGui import QFont from PyQt5.QtGui import QBrush from PyQt5.QtGui import QTextFormat from ninja_ide.core import settings from ninja_ide import resources from ninja_ide.gui.ide import IDE class TextCharFormat(QTextCharFormat): NAME = QTextFormat.UserProperty + 1 class Format(object): __slots__ = ("name", "tcf") def __init__(self, name, color=None, bold=None, italic=None, base_format=None): self.name = name tcf = TextCharFormat() if base_format is not None: if isinstance(base_format, Format): base_format = base_format.tcf tcf.merge(base_format) tcf.setFont(base_format.font()) if color is not None: if not isinstance(color, QColor): color = QColor(color) tcf.setForeground(QBrush(color)) if bold is not None: if bold: tcf.setFontWeight(QFont.Bold) else: tcf.setFontWeight(QFont.Normal) if italic is not None: tcf.setFontItalic(italic) tcf.setProperty(TextCharFormat.NAME, name) self.tcf = tcf class HighlighterError(Exception): pass class Partition(object): # every partition maps to a specific state in QSyntaxHighlighter __slots__ = ("name", "start", "end", "is_multiline", "search_end") def __init__(self, name, start, end, is_multiline=False): self.name = name self.start = start self.end = end self.is_multiline = is_multiline try: self.search_end = re.compile(end, re.M | re.S).search except Exception as exc: raise HighlighterError("{0}: {1} {2}".format(exc, name, end)) class PartitionScanner(object): # The idea to partition the source into different # contexts comes from Eclipse. # http://wiki.eclipse.org/FAQ_What_is_a_document_partition%3F def __init__(self, partitions): start_groups = [] self.partitions = [] for i, p in enumerate(partitions): if isinstance(p, (tuple, list)): p = Partition(*p) elif isinstance(p, dict): p = Partition(**p) else: assert isinstance( p, Partition), "Partition expected, got %r" % p self.partitions.append(p) start_groups.append("(?P<g%s_%s>%s)" % (i, p.name, p.start)) start_pat = "|".join(start_groups) try: self.search_start = re.compile(start_pat, re.M | re.S).search except Exception as exc: raise HighlighterError("%s: %s" % (exc, start_pat)) def scan(self, current_state, text): last_pos = 0 length = len(text) parts = self.partitions search_start = self.search_start # loop yields (start, end, partition, new_state, is_inside) while last_pos < length: if current_state == -1: found = search_start(text, last_pos) if found: start, end = found.span() yield last_pos, start, None, -1, True current_state = found.lastindex - 1 p = parts[current_state] yield start, end, p.name, current_state, False last_pos = end else: current_state = -1 yield last_pos, length, None, -1, True break else: p = parts[current_state] found = p.search_end(text, last_pos) if found: start, end = found.span() yield last_pos, start, p.name, current_state, True yield start, end, p.name, current_state, False last_pos = end current_state = -1 else: yield last_pos, length, p.name, current_state, True break if current_state != -1: p = parts[current_state] if not p.is_multiline: current_state = -1 yield length, length, None, current_state, False class Token(object): __slots__ = ("name", "pattern", "prefix", "suffix") def __init__(self, name, pattern, prefix="", suffix=""): self.name = name if isinstance(pattern, list): pattern = "|".join(pattern) self.pattern = pattern self.prefix = prefix self.suffix = suffix class Scanner(object): __slots__ = ("tokens", "search") def __init__(self, tokens): self.tokens = [] groups = [] for t in tokens: if isinstance(t, (list, tuple)): t = Token(*t) elif isinstance(t, dict): t = Token(**t) else: assert isinstance(t, Token), "Token expected, got %r" % t gdef = "?P<%s>" % t.name if gdef in t.pattern: p = t.pattern else: p = ("(%s%s)" % (gdef, t.pattern)) p = t.prefix + p + t.suffix groups.append(p) self.tokens.append(t) pat = "|".join(groups) self.search = re.compile(pat).search def scan(self, s): search = self.search last_pos = 0 # loop yields (token, start_pos, end_pos) while True: found = search(s, last_pos) if found: lg = found.lastgroup start, last_pos = found.span(lg) yield lg, start, last_pos else: break class SyntaxHighlighter(QSyntaxHighlighter): def __init__(self, parent, partition_scanner, scanner, formats, default_font=None): """ :param parent: QDocument or QTextEdit/QPlainTextEdit instance 'partition_scanner: PartitionScanner instance :param scanner: dictionary of token scanners for each partition The key is the name of the partition, the value is a Scanner instance The default scanner has the key None :formats: list of tuples consisting of a name and a format definition The name is the name of a partition or token """ super(SyntaxHighlighter, self).__init__(parent) if default_font: parent.setDefaultFont(default_font) if isinstance(partition_scanner, (list, tuple)): partition_scanner = PartitionScanner(partition_scanner) else: assert isinstance( partition_scanner, PartitionScanner), ("PartitionScanner expected, " "got {!r}".format(partition_scanner)) self.partition_scanner = partition_scanner self.scanner = scanner for inside_part, inside_scanner in list(scanner.items()): if isinstance(inside_scanner, (list, tuple)): inside_scanner = Scanner(inside_scanner) self.scanner[inside_part] = inside_scanner else: assert isinstance( inside_scanner, Scanner), ("Scanner expected, " "got {!r}".format( inside_scanner)) self.formats = {} for f in formats: if isinstance(f, tuple): fname, f = f else: assert isinstance( f, (Format, dict)), "Format expected, got %r" % f if isinstance(f, str): f = (f,) # only color specified if isinstance(f, (tuple, list)): f = Format(*((fname,) + f)) elif isinstance(f, dict): f = Format(**dict(name=fname, **f)) else: assert isinstance(f, Format), "Format expected, got %r" % f f.tcf.setFontFamily(parent.defaultFont().family()) self.formats[f.name] = f.tcf # reduce name look-ups for better speed scan_inside = {} for inside_part, inside_scanner in list(self.scanner.items()): scan_inside[inside_part] = inside_scanner.scan self.get_scanner = scan_inside.get self.scan_partitions = partition_scanner.scan self.get_format = self.formats.get def highlightBlock(self, text): """automatically called by Qt""" text = str(text) + "\n" previous_state = self.previousBlockState() new_state = previous_state # speed-up name-lookups get_format = self.get_format set_format = self.setFormat get_scanner = self.get_scanner for start, end, partition, new_state, is_inside in \ self.scan_partitions(previous_state, text): f = get_format(partition, None) if f: set_format(start, end - start, f) if is_inside: scan = get_scanner(partition) if scan: for token, token_pos, token_end in scan(text[start:end]): f = get_format(token) if f: set_format( start + token_pos, token_end - token_pos, f) self.setCurrentBlockState(new_state) class Syntax(object): __slots__ = ("partition_scanner", "scanners", "context") def __init__(self, part_scanner, scanners): self.partition_scanner = part_scanner self.scanners = scanners self.context = [] def build_context(self): for color in resources.COLOR_SCHEME.get("colors"): scope = color.get("scope") colors = color.get("settings") self.context.append((scope, colors)) def build_highlighter(language, force=False): syntax_registry = IDE.get_service("syntax_registry") syntax = syntax_registry.get_syntax_for(language) if syntax is None: syntax_structure = settings.SYNTAX.get(language) if syntax_structure is None: print("Error") return None part_scanner = PartitionScanner(syntax_structure.get("partitions")) scanners = {} for scanner in syntax_structure.get("scanner"): name = scanner.get("partition_name") scanners[name] = Scanner(scanner.get("tokens")) syntax = Syntax(part_scanner, scanners) syntax.build_context() syntax_registry.register_syntax(language, syntax) return syntax
11,483
Python
.py
280
29.625
77
0.56385
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,509
__highlighter.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/__highlighter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. # based on Python Syntax highlighting from: # http://diotavelli.net/PyQtWiki/Python%20syntax%20highlighting from __future__ import absolute_import import re from ninja_ide.gui.editor.extended_lexers.all_lexers import ( PythonLexer, AVSLexer, BashLexer, BatchLexer, CMakeLexer, CPPLexer, CSSLexer, CSharpLexer, CoffeeScriptLexer, DLexer, DiffLexer, FortranLexer, Fortran77Lexer, HTMLLexer, IDLLexer, JavaLexer, JavaScriptLexer, LuaLexer, MakefileLexer, MatlabLexer, OctaveLexer, POLexer, POVLexer, PascalLexer, PerlLexer, PostScriptLexer, PropertiesLexer, RubyLexer, SQLLexer, SpiceLexer, TCLLexer, TeXLexer, VHDLLexer, VerilogLexer, XMLLexer, YAMLLexer) from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.gui.editor.highlighter') LEXERS = { "python": PythonLexer, "avs": AVSLexer, "bash": BashLexer, "batch": BatchLexer, "cmake": CMakeLexer, "cpp": CPPLexer, "css": CSSLexer, "csharp": CSharpLexer, "coffeescript": CoffeeScriptLexer, "d": DLexer, "diff": DiffLexer, "fortran": FortranLexer, "fortran77": Fortran77Lexer, "html": HTMLLexer, "idl": IDLLexer, "java": JavaLexer, "javascript": JavaScriptLexer, "lua": LuaLexer, "makefile": MakefileLexer, "matlab": MatlabLexer, "octave": OctaveLexer, "po": POLexer, "pov": POVLexer, "pascal": PascalLexer, "perl": PerlLexer, "postscript": PostScriptLexer, "properties": PropertiesLexer, "ruby": RubyLexer, "sql": SQLLexer, "spice": SpiceLexer, "tcl": TCLLexer, "tex": TeXLexer, "vhdl": VHDLLexer, "verilog": VerilogLexer, "xml": XMLLexer, "yaml": YAMLLexer, } LEXER_MAP = { "asm": "assembler", "json": "json", "cs": "csharp", "rb": "ruby_on_rails", "cpp": "cpp", "coffee": "coffeescript", "tex": "bibtex", "js": "javascript", "qml": "javascript", "mo": "gettext", "po": "gettext", "pot": "gettext", "v": "verilog", "sh": "shell", "shell": "shell", "bash": "shell", "ksh": "shell", "pas": "pascal", "html": "html", "list": "sourceslist", "lol": "lolcode", "h": "header", "conf": "apache", "php": "php", "php4": "php", "php5": "php", "css": "css", "qss": "css", "scss": "css", "sass": "css", "tex": "latex", "py": "python", "pyw": "python", "rpy": "python", "tac": "python", "pyx": "cython", "pxd": "cython", "pxi": "cython", "go": "go", "asp": "asp", "rst": "rst", "c": "c", "java": "java", } BUILT_LEXERS = { } def get_lang(extension): if not extension: extension = "py" return LEXER_MAP.get(extension, "") def get_lexer(extension="py"): return build_lexer(get_lang(extension)) def build_lexer(lang): global BUILT_LEXERS Lexer = BUILT_LEXERS.get(lang, None) if Lexer is None: Lexer = LEXERS.get(lang, None) if Lexer is not None: lex = Lexer() lex.initialize_color_scheme() BUILT_LEXERS[lang] = lex return lex return Lexer
3,845
Python
.py
132
24.659091
80
0.644769
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,510
base_editor.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/base_editor.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import QPlainTextEdit from PyQt5.QtWidgets import QAbstractSlider from PyQt5.QtGui import QTextBlockUserData from PyQt5.QtGui import QTextDocument from PyQt5.QtGui import QColor from PyQt5.QtGui import QTextCursor from PyQt5.QtCore import Qt from PyQt5.QtCore import pyqtSignal from ninja_ide import resources from ninja_ide.core import settings from ninja_ide.gui.editor.mixin import EditorMixin class BaseEditor(QPlainTextEdit, EditorMixin): zoomChanged = pyqtSignal(int) def __init__(self): QPlainTextEdit.__init__(self) EditorMixin.__init__(self) # Word separators # Can be used by code completion and the link emulator self.word_separators = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?" # Style self.__init_style() self.__apply_style() self.__visible_blocks = [] @property def visible_blocks(self): return self.__visible_blocks @property def background_color(self): """Get or set the background color. :param color: Color to set (name or hexa). :type color: QColor or str. :return: Background color. :rtype: QColor.""" return self._background_color @background_color.setter def background_color(self, color): if isinstance(color, str): color = QColor(color) self._background_color = color # Refresh stylesheet self.__apply_style() @property def foreground_color(self): """Get or set the foreground color. :param color: Color to set (name or hexa). :type color: QColor or str. :return: Foreground color. :rtype: QColor""" return self._foreground_color @foreground_color.setter def foreground_color(self, color): if isinstance(color, str): color = QColor(color) self._foreground_color = color self.__apply_style() def __init_style(self): self._background_color = QColor( resources.COLOR_SCHEME.get("editor.background")) # resources.get_color('editor.background')) self._foreground_color = QColor( resources.COLOR_SCHEME.get("editor.foreground")) # resources.get_color('editor.foreground')) self._selection_color = QColor( resources.COLOR_SCHEME.get("editor.selection.foreground")) # resources.get_color('EditorSelectionColor')) self._selection_background_color = QColor( resources.COLOR_SCHEME.get("editor.selection.background")) # resources.get_color('EditorSelectionBackground')) def __apply_style(self): palette = self.palette() palette.setColor(palette.Base, self._background_color) palette.setColor(palette.Text, self._foreground_color) palette.setColor(palette.HighlightedText, self._selection_color) palette.setColor(palette.Highlight, self._selection_background_color) self.setPalette(palette) def paintEvent(self, event): self._update_visible_blocks() super().paintEvent(event) def _update_visible_blocks(self): """Updates the list of visible blocks""" self.__visible_blocks.clear() append = self.__visible_blocks.append block = self.firstVisibleBlock() block_number = block.blockNumber() top = self.blockBoundingGeometry(block).translated( self.contentOffset()).top() bottom = top + self.blockBoundingRect(block).height() editor_height = self.height() while block.isValid(): visible = bottom <= editor_height if not visible: break if block.isVisible(): append((top, block_number, block)) block = block.next() top = bottom bottom = top + self.blockBoundingRect(block).height() block_number += 1 def replace_match(self, word_old, word_new, cs=False, wo=False, wrap_around=True): """ Find if searched text exists and replace it with new one. If there is a selection just do it inside it and exit """ cursor = self.textCursor() text = cursor.selectedText() if not cs: word_old = word_old.lower() text = text.lower() if text == word_old: cursor.insertText(word_new) # Next return self.find_match(word_old, cs, wo, forward=True, wrap_around=wrap_around) def replace_all(self, word_old, word_new, cs=False, wo=False): # Save cursor for restore later cursor = self.textCursor() with self: # Move to beginning of text and replace all self.moveCursor(QTextCursor.Start) found = True while found: found = self.replace_match(word_old, word_new, cs, wo, wrap_around=False) # Reset position self.setTextCursor(cursor) def find_match(self, search, case_sensitive=False, whole_word=False, backward=False, forward=False, wrap_around=True): if not backward and not forward: self.moveCursor(QTextCursor.StartOfWord) flags = QTextDocument.FindFlags() if case_sensitive: flags |= QTextDocument.FindCaseSensitively if whole_word: flags |= QTextDocument.FindWholeWords if backward: flags |= QTextDocument.FindBackward cursor = self.textCursor() found = self.document().find(search, cursor, flags) if not found.isNull(): self.setTextCursor(found) elif wrap_around: if not backward and not forward: cursor.movePosition(QTextCursor.Start) elif forward: cursor.movePosition(QTextCursor.Start) else: cursor.movePosition(QTextCursor.End) # Try again found = self.document().find(search, cursor, flags) if not found.isNull(): self.setTextCursor(found) return not found.isNull() def line_from_position(self, position): height = self.fontMetrics().height() for top, line, block in self.__visible_blocks: if top <= position <= top + height: return line return -1 def scroll_step_up(self): self.verticalScrollBar().triggerAction( QAbstractSlider.SliderSingleStepSub) def scroll_step_down(self): self.verticalScrollBar().triggerAction( QAbstractSlider.SliderSingleStepAdd) def __enter__(self): self.textCursor().beginEditBlock() def __exit__(self, exc_type, exc_value, traceback): self.textCursor().endEditBlock() def word_under_cursor(self, cursor=None, ignore=None): """Returns QTextCursor that contains a word under passed cursor or actual cursor""" if cursor is None: cursor = self.textCursor() word_separators = self.word_separators if ignore is not None: word_separators = [w for w in self.word_separators if w not in ignore] start_pos = end_pos = cursor.position() while not cursor.atStart(): cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor) selected_text = cursor.selectedText() if not selected_text: break char = selected_text[0] if (selected_text in word_separators and ( selected_text != "n" and selected_text != "t") or char.isspace()): break start_pos = cursor.position() cursor.setPosition(start_pos) cursor.setPosition(end_pos) while not cursor.atEnd(): cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) selected_text = cursor.selectedText() if not selected_text: break char = selected_text[0] if (selected_text in word_separators and ( selected_text != "n" and selected_text != "t") or char.isspace()): break end_pos = cursor.position() cursor.setPosition(end_pos) cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) return cursor def user_data(self, block=None): if block is None: block = self.textCursor().block() user_data = block.userData() if user_data is None: user_data = BlockUserData() block.setUserData(user_data) return user_data def wheelEvent(self, event): if event.modifiers() == Qt.ControlModifier: if not settings.SCROLL_WHEEL_ZOMMING: return delta = event.angleDelta().y() / 120. if delta != 0: self.zoom(delta) return super().wheelEvent(event) def zoom(self, delta: int): font = self.default_font previous_point_size = font.pointSize() new_point_size = int(max(1, previous_point_size + delta)) if new_point_size != previous_point_size: font.setPointSize(new_point_size) self.set_font(font) # Emit signal for indicator default_point_size = settings.FONT.pointSize() percent = new_point_size / default_point_size * 100.0 self.zoomChanged.emit(percent) # # Update all side widgets def reset_zoom(self): font = self.default_font default_point_size = settings.FONT.pointSize() if font.pointSize() != default_point_size: font.setPointSize(default_point_size) self.set_font(font) # Emit signal for indicator self.zoomChanged.emit(100) # # Update all side widgets def remove_trailing_spaces(self): cursor = self.textCursor() block = self.document().findBlockByLineNumber(0) with self: while block.isValid(): text = block.text() if text.endswith(' '): cursor.setPosition(block.position()) cursor.select(QTextCursor.LineUnderCursor) cursor.insertText(text.rstrip()) block = block.next() def insert_block_at_end(self): last_line = self.line_count() - 1 text = self.line_text(last_line) if text: cursor = self.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertBlock() def text_before_cursor(self, text_cursor=None): if text_cursor is None: text_cursor = self.textCursor() text_block = text_cursor.block().text() return text_block[:text_cursor.positionInBlock()] class BlockUserData(QTextBlockUserData): """Representation of the data for a block""" def __init__(self): QTextBlockUserData.__init__(self) self.attrs = {} def get(self, name, default=None): return self.attrs.get(name, default) def __getitem__(self, name): return self.attrs[name] def __setitem__(self, name, value): self.attrs[name] = value
12,168
Python
.py
296
31.070946
74
0.610745
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,511
proposal_widget.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/proposal_widget.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import QFrame from PyQt5.QtWidgets import QListView from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QAbstractItemView from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QStyle from PyQt5.QtWidgets import QStylePainter from PyQt5.QtWidgets import QStyleOptionFrame from PyQt5.QtWidgets import QSizePolicy from PyQt5.QtWidgets import QStyledItemDelegate from PyQt5.QtGui import QIcon from PyQt5.QtGui import QColor from PyQt5.QtCore import QAbstractListModel from PyQt5.QtCore import Qt from PyQt5.QtCore import QModelIndex from PyQt5.QtCore import QEvent from PyQt5.QtCore import QTimer from PyQt5.QtCore import QPoint from PyQt5.QtCore import pyqtSignal from PyQt5.QtCore import QSize from ninja_ide.core import settings # TODO: implement delegate class ProposalItem(object): """ The ProposalItem class acts as an interface for representing an assist proposal item. """ __slots__ = ("text", "type", "detail", "__icon") def __init__(self, text): self.text = text self.type = None self.detail = None self.__icon = None @property def lower_text(self): return self.text.lower() @property def icon(self): return self.__icon def set_icon(self, icon_name): self.__icon = QIcon(":img/{}".format(icon_name)) def __repr__(self): return self.__str__() def __str__(self): return "<ProposalItem:%s:%s>" % (self.text, self.type) class ProposalModel(QAbstractListModel): """ List model for proposals """ PROPOSALS_STEP = 20 def __init__(self, parent=None): super().__init__(parent) def fetchMore(self, parent): remainder = len(self.__current_proposals) - self.__item_count items_to_fetch = min(self.PROPOSALS_STEP, remainder) self.beginInsertRows( QModelIndex(), self.__item_count, self.__item_count + items_to_fetch - 1) self.__item_count += items_to_fetch self.endInsertRows() def canFetchMore(self, parent): if self.__item_count < len(self.__current_proposals): return True return False def set_items(self, items): self.beginResetModel() self.__current_proposals = items self.__original_proposals = items self.__item_count = self.PROPOSALS_STEP self.endResetModel() def rowCount(self, index=None): count = self.__item_count if len(self.__current_proposals) < count: count = len(self.__current_proposals) return count def data(self, index, role=Qt.DisplayRole): if not index.isValid() or index.row() >= len(self.__current_proposals): return None item = self.__current_proposals[index.row()] if role == Qt.DisplayRole: return item.text elif role == Qt.DecorationRole: return item.icon elif role == Qt.UserRole: return item.type elif role == Qt.WhatsThisRole: return item.detail return None def item(self, index): return self.__current_proposals[index] def has_proposals(self): return len(self.__current_proposals) > 0 def filter(self, prefix): if not prefix: # Reset self.__current_proposals = self.__original_proposals return self.__current_proposals = [item for item in self.__original_proposals if item.lower_text.startswith( prefix.lower())] def is_pre_filtered(self, prefix): return self.__prefix and prefix == self.__prefix class ProposalDelegate(QStyledItemDelegate): """Custom delegate that adds the proposal type""" def paint(self, painter, opt, index): self.initStyleOption(opt, index) painter.save() widget = opt.widget widget.style().drawControl( QStyle.CE_ItemViewItem, opt, painter, widget) proposal_type = index.data(Qt.UserRole) font = painter.font() font.setItalic(True) font.setPointSize(font.pointSize() * 0.98) painter.setFont(font) if opt.state & QStyle.State_Selected: painter.setPen(QColor(opt.palette.text())) else: painter.setPen( opt.palette.color(opt.palette.Disabled, opt.palette.Text)) rect = opt.rect # Just a margin rect.setRight(rect.right() - 10) painter.drawText(rect, Qt.AlignRight, proposal_type) painter.restore() def sizeHint(self, opt, index): sh = super().sizeHint(opt, index) return QSize(sh.width() + 130, sh.height()) class ProposalView(QListView): """ View for proposals """ MAX_VISIBLE_ITEMS = 10 def __init__(self, parent=None): super().__init__(parent) self.setFont(settings.FONT) self.setUniformItemSizes(True) self.setSelectionBehavior(QAbstractItemView.SelectItems) self.setSelectionMode(QAbstractItemView.SingleSelection) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollMode(QAbstractItemView.ScrollPerItem) def select_row(self, row): self.setCurrentIndex(self.model().index(row, 0)) def select_first(self): self.select_row(0) def select_last(self): self.select_row(self.model().rowCount() - 1) def row_selected(self): return self.currentIndex().row() def is_first_selected(self): return self.row_selected() == 0 def is_last_selected(self): return self.row_selected() == self.model().rowCount() - 1 def info_frame_position(self): r = self.rectForIndex(self.currentIndex()) point = QPoint((self.parentWidget().mapToGlobal( self.parentWidget().rect().topRight() )).x() + 3, self.mapToGlobal(r.topRight()).y() - self.verticalOffset()) return point def calculate_size(self): """Determine size by calculating the space of the visible items""" visible_items = min(self.model().rowCount(), self.MAX_VISIBLE_ITEMS) first_visible_row = self.verticalScrollBar().value() option = self.viewOptions() size_hint = QSize() for index in range(visible_items): tmp_size = self.itemDelegate().sizeHint( option, self.model().index(index + first_visible_row, 0)) if size_hint.width() < tmp_size.width(): size_hint = tmp_size height = size_hint.height() height *= visible_items size_hint.setHeight(height) return size_hint class InfoFrame(QFrame): """Widget to show call tips""" def __init__(self, parent): super().__init__(parent, Qt.ToolTip | Qt.WindowStaysOnTopHint) self.setObjectName("custom_tip") self.setFocusPolicy(Qt.NoFocus) self.setAttribute(Qt.WA_DeleteOnClose) self._label = QLabel() self._label.setStyleSheet("border: none") font = parent.font() font.setPointSize(font.pointSize() * 0.9) self._label.setFont(font) self._label.setSizePolicy( QSizePolicy.Fixed, self._label.sizePolicy().verticalPolicy()) layout = QVBoxLayout(self) layout.setContentsMargins(3, 3, 3, 3) layout.addWidget(self._label) def set_text(self, text): self._label.setText(text) def paintEvent(self, event): p = QStylePainter(self) opt = QStyleOptionFrame() opt.initFrom(self) p.drawPrimitive(QStyle.PE_PanelTipLabel, opt) p.end() def calculate_width(self): desk = QApplication.desktop() desk_width = desk.availableGeometry(desk.primaryScreen()).width() if desk.isVirtualDesktop(): desk_width = desk.width() widget_margins = self.contentsMargins() layout_margins = self.layout().contentsMargins() margins = widget_margins.left() + widget_margins.right() + \ layout_margins.left() + layout_margins.right() self._label.setMaximumWidth(desk_width - self.pos().x() - margins) class ProposalWidget(QFrame): """ Proposal Widget for display completions and snippets """ proposalItemActivated = pyqtSignal("PyQt_PyObject") def __init__(self, parent): super().__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) self._editor = parent self._model = None self._prefix = None self._auto_width = True self._info_frame = None self._info_timer = QTimer(self) self._info_timer.setSingleShot(True) self._info_timer.setInterval(100) self._info_timer.timeout.connect(self.show_info) vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) self._proposal_view = ProposalView() self.setFrameStyle(self._proposal_view.frameStyle()) self._proposal_view.setFrameStyle(QFrame.NoFrame) self._proposal_view.installEventFilter(self) vbox.addWidget(self._proposal_view) # Connections vertical_scrollbar = self._proposal_view.verticalScrollBar() vertical_scrollbar.valueChanged.connect( self.update_size_and_position) self._proposal_view.clicked.connect(self._handle_view_activation) vertical_scrollbar.sliderPressed.connect(self._turn_off_autowidth) vertical_scrollbar.sliderReleased.connect(self._turn_on_autowidth) def _handle_view_activation(self, index): self.abort() self.insert_proposal(index.row()) def show_info(self): current = self._proposal_view.currentIndex() if not current.isValid(): return info = current.data(Qt.WhatsThisRole) if not info: if self._info_frame is not None: self._info_frame.close() self._info_frame = None return if self._info_frame is None: self._info_frame = InfoFrame(self._proposal_view) self._info_frame.move(self._proposal_view.info_frame_position()) self._info_frame.set_text(info) self._info_frame.calculate_width() self._info_frame.adjustSize() self._info_frame.show() self._info_frame.raise_() self._info_timer.setInterval(0) def set_model(self, model): if self._model is not None: self._model.deleteLater() del self._model self._model = None self._model = model self._proposal_view.setModel(self._model) self._proposal_view.selectionModel().currentChanged.connect( self._info_timer.start) def show_proposal(self, prefix=None): self._proposal_view.setFont(self._editor.font()) self.update_size_and_position() self.show() self._proposal_view.select_first() self._proposal_view.setFocus() def _turn_off_autowidth(self): self._auto_width = False def _turn_on_autowidth(self): self._auto_width = True self.update_size_and_position() def update_size_and_position(self): if not self._auto_width: return size_hint = self._proposal_view.calculate_size() frame_width = self.frameWidth() width = size_hint.width() + frame_width * 2 + 30 height = size_hint.height() + frame_width * 2 desktop = QApplication.instance().desktop() screen = desktop.screenGeometry(desktop.screenNumber(self._editor)) if settings.IS_MAC_OS: screen = desktop.availableGeometry( desktop.screenNumber(self._editor)) cr = self._editor.cursorRect() pos = cr.bottomLeft() rx = pos.x() + 60 # FIXME: why 60? pos.setX(rx) if pos.y() + height > screen.bottom(): pos.setY(max(0, cr.top() - height)) if pos.x() + width > screen.right(): pos.setX(max(0, screen.right() - width)) self.setGeometry(pos.x(), pos.y(), min(width, screen.width()), min(height, screen.height())) def eventFilter(self, obj, event): if event.type() == QEvent.FocusOut: self.abort() if self._info_frame is not None: self._info_frame.close() return True elif event.type() == QEvent.KeyPress: if event.key() == Qt.Key_Escape: self.abort() event.accept() return True elif event.key() in (Qt.Key_Return, Qt.Key_Enter, Qt.Key_Tab): self.abort() self.insert_proposal() return True elif event.key() == Qt.Key_Up: if self._proposal_view.is_first_selected(): self._proposal_view.select_last() return True return False elif event.key() == Qt.Key_Down: if self._proposal_view.is_last_selected(): self._proposal_view.select_first() return True return False elif event.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Home, Qt.Key_End): self.abort() else: pass QApplication.sendEvent(self._editor, event) if self.isVisible(): self.update_proposal() return True return False def update_proposal(self): word = self._editor.word_under_cursor().selectedText() self._model.filter(word) if not self._model.has_proposals(): self.abort() self._proposal_view.select_first() self.update_size_and_position() if self._info_frame is not None: self._info_frame.move(self._proposal_view.info_frame_position()) def insert_proposal(self, row=None): if row is None: if self._proposal_view.currentIndex().isValid(): row = self._proposal_view.currentIndex().row() item = self._proposal_view.model().item(row) self.proposalItemActivated.emit(item) def abort(self): if self.isVisible(): self.close() self._editor.setFocus()
15,122
Python
.py
375
31.405333
79
0.624974
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,512
minimap.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/minimap.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt4.QtGui import QFrame from PyQt4.QtGui import QPainter from PyQt4.QtGui import QPen from PyQt4.QtGui import QColor from PyQt4.QtGui import QBrush from PyQt4.QtCore import QPropertyAnimation from PyQt4.QtGui import QGraphicsOpacityEffect from PyQt4.QtCore import Qt from PyQt4.Qsci import QsciScintilla from ninja_ide.core import settings from ninja_ide import resources ACTIVATE_OPACITY = True if not settings.IS_MAC_OS else False class MiniMap(QsciScintilla): def __init__(self, editor): super(MiniMap, self).__init__(editor) self._editor = editor self.SendScintilla(QsciScintilla.SCI_SETCARETSTYLE, 0) self.SendScintilla(QsciScintilla.SCI_SETBUFFEREDDRAW, 0) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.SendScintilla(QsciScintilla.SCI_SETVSCROLLBAR, 0) self.SendScintilla(QsciScintilla.SCI_SETZOOM, -10) self.SendScintilla(QsciScintilla.SCI_SETREADONLY, 1) self.SendScintilla(QsciScintilla.SCI_HIDESELECTION, 1) self.SendScintilla(QsciScintilla.SCI_SETCURSOR, 8) # Hide markers for i in range(1, 5): self.SendScintilla( QsciScintilla.SCI_MARKERDEFINE, i, QsciScintilla.SC_MARK_EMPTY) self.SendScintilla(QsciScintilla.SCI_SETMARGINWIDTHN, 1, 0) self.setMouseTracking(True) if ACTIVATE_OPACITY: self.goe = QGraphicsOpacityEffect() self.setGraphicsEffect(self.goe) self.goe.setOpacity(settings.MINIMAP_MIN_OPACITY) self.animation = QPropertyAnimation(self.goe, "opacity") self.animation.setDuration(300) self.slider = SliderArea(self) self.slider.show() def adjust_to_parent(self): self.setFixedHeight(self._editor.height()) self.setFixedWidth(self._editor.width() * settings.SIZE_PROPORTION) x = self._editor.width() - self.width() self.move(x, 0) self.slider.update_position() def shutdown(self): self._editor.SCN_UPDATEUI.disconnect() self._editor.SCN_ZOOM.disconnect() def fold(self, line): self.foldLine(line) def scroll_map(self): first_visible_line = self._editor.SendScintilla( QsciScintilla.SCI_GETFIRSTVISIBLELINE) num_doc_lines = self._editor.SendScintilla( QsciScintilla.SCI_GETLINECOUNT) num_visible_lines = self._editor.SendScintilla( QsciScintilla.SCI_DOCLINEFROMVISIBLE, num_doc_lines) lines_on_screen = self._editor.SendScintilla( QsciScintilla.SCI_LINESONSCREEN) if num_visible_lines > lines_on_screen: last_top_visible_line = num_visible_lines - lines_on_screen num_map_visible_lines = self.SendScintilla( QsciScintilla.SCI_DOCLINEFROMVISIBLE, num_doc_lines) # Lines on screen map lines_on_screenm = self.SendScintilla( QsciScintilla.SCI_LINESONSCREEN) # Last top visible line on map last_top_visible_linem = num_map_visible_lines - lines_on_screenm # Portion covered portion = first_visible_line / last_top_visible_line first_visible_linem = round(last_top_visible_linem * portion) # Scroll self.verticalScrollBar().setValue(first_visible_linem) # Move slider higher_pos = self._editor.SendScintilla( QsciScintilla.SCI_POSITIONFROMPOINT, 0, 0) y = self.SendScintilla( QsciScintilla.SCI_POINTYFROMPOSITION, 0, higher_pos) self.slider.move(0, y) self._current_scroll_value = self._editor.verticalScrollBar().value() def scroll_area(self, pos_parent, line_area): line = self.__line_from_position(pos_parent) self._editor.verticalScrollBar().setValue(line - line_area) def mousePressEvent(self, event): super(MiniMap, self).mousePressEvent(event) line = self.__line_from_position(event.pos()) self._editor.jump_to_line(line) # Go to center los = self._editor.SendScintilla(QsciScintilla.SCI_LINESONSCREEN) / 2 scroll_value = self._editor.verticalScrollBar().value() if self._current_scroll_value < scroll_value: self._editor.verticalScrollBar().setValue(scroll_value + los) else: self._editor.verticalScrollBar().setValue(scroll_value - los) def __line_from_position(self, point): position = self.SendScintilla(QsciScintilla.SCI_POSITIONFROMPOINT, point.x(), point.y()) return self.SendScintilla(QsciScintilla.SCI_LINEFROMPOSITION, position) def enterEvent(self, event): if ACTIVATE_OPACITY: self.animation.setStartValue(settings.MINIMAP_MIN_OPACITY) self.animation.setEndValue(settings.MINIMAP_MAX_OPACITY) self.animation.start() def leaveEvent(self, event): if ACTIVATE_OPACITY: self.animation.setStartValue(settings.MINIMAP_MAX_OPACITY) self.animation.setEndValue(settings.MINIMAP_MIN_OPACITY) self.animation.start() def wheelEvent(self, event): super(MiniMap, self).wheelEvent(event) self._editor.wheelEvent(event) def resizeEvent(self, event): super(MiniMap, self).resizeEvent(event) self.slider.update_position() class SliderArea(QFrame): def __init__(self, minimap): super(SliderArea, self).__init__(minimap) self._minimap = minimap self.pressed = False self.setMouseTracking(True) self.setCursor(Qt.OpenHandCursor) color = resources.CUSTOM_SCHEME.get( 'MinimapVisibleArea', resources.COLOR_SCHEME['MinimapVisibleArea']) if ACTIVATE_OPACITY: self.setStyleSheet("background: %s;" % color) self.goe = QGraphicsOpacityEffect() self.setGraphicsEffect(self.goe) self.goe.setOpacity(settings.MINIMAP_MAX_OPACITY / 2) else: self.setStyleSheet("background: transparent;") def mousePressEvent(self, event): super(SliderArea, self).mousePressEvent(event) self.pressed = True self.setCursor(Qt.ClosedHandCursor) # Get line number from lines on screen # This is to moving the slider from the point where you clicked first_visible_line = self._minimap._editor.SendScintilla( QsciScintilla.SCI_GETFIRSTVISIBLELINE) pos_parent = self.mapToParent(event.pos()) position = self._minimap.SendScintilla( QsciScintilla.SCI_POSITIONFROMPOINT, pos_parent.x(), pos_parent.y()) line = self._minimap.SendScintilla( QsciScintilla.SCI_LINEFROMPOSITION, position) self.line_on_visible_area = (line - first_visible_line) + 1 def mouseReleaseEvent(self, event): super(SliderArea, self).mouseReleaseEvent(event) self.pressed = False self.setCursor(Qt.OpenHandCursor) def update_position(self): font_size = round(self._minimap.font().pointSize() / 2.5) lines_count = self._minimap._editor.SendScintilla( QsciScintilla.SCI_LINESONSCREEN) height = lines_count * font_size self.setFixedHeight(height) self.setFixedWidth(self._minimap.width()) def paintEvent(self, event): """Paint over the widget to overlay its content.""" if not ACTIVATE_OPACITY: painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.Antialiasing, True) painter.fillRect(event.rect(), QBrush( QColor(226, 0, 0, 80))) painter.setPen(QPen(Qt.NoPen)) painter.end() super(SliderArea, self).paintEvent(event) def mouseMoveEvent(self, event): super(SliderArea, self).mouseMoveEvent(event) if self.pressed: pos = self.mapToParent(event.pos()) self._minimap.scroll_area(pos, self.line_on_visible_area)
8,844
Python
.py
187
38.245989
80
0.67293
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,513
__init__.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
692
Python
.py
16
42.25
70
0.760355
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,514
editor.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/editor.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import re import sys import sre_constants from collections import OrderedDict from PyQt5.QtWidgets import QFrame from PyQt5.QtWidgets import QToolTip from PyQt5.QtGui import QTextCursor from PyQt5.QtGui import QFontMetrics from PyQt5.QtGui import QKeySequence from PyQt5.QtCore import pyqtSignal from PyQt5.QtCore import pyqtSlot from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from PyQt5.QtCore import QEvent from ninja_ide import resources from ninja_ide.tools import utils from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide.gui.editor import indenter from ninja_ide.gui.editor import highlighter from ninja_ide.gui.editor import base_editor from ninja_ide.gui.editor import scrollbar from ninja_ide.gui.editor import extra_selection # Extensions from ninja_ide.gui.editor.extensions import symbol_highlighter from ninja_ide.gui.editor.extensions import line_highlighter from ninja_ide.gui.editor.extensions import margin_line from ninja_ide.gui.editor.extensions import indentation_guides from ninja_ide.gui.editor.extensions import braces from ninja_ide.gui.editor.extensions import quotes # Side from ninja_ide.gui.editor.side_area import manager from ninja_ide.gui.editor.side_area import line_number_widget from ninja_ide.gui.editor.side_area import text_change_widget from ninja_ide.gui.editor.side_area import code_folding from ninja_ide.gui.editor.side_area import marker_widget # TODO: separte this module and create a editor component class NEditor(base_editor.BaseEditor): goToDefRequested = pyqtSignal("PyQt_PyObject") painted = pyqtSignal("PyQt_PyObject") keyPressed = pyqtSignal("PyQt_PyObject") keyReleased = pyqtSignal("PyQt_PyObject") postKeyPressed = pyqtSignal("PyQt_PyObject") addBackItemNavigation = pyqtSignal() editorFocusObtained = pyqtSignal() # FIXME: cambiar nombre cursor_position_changed = pyqtSignal(int, int) current_line_changed = pyqtSignal(int) _MAX_CHECKER_SELECTIONS = 150 # For good performance def __init__(self, neditable): super().__init__() self.setFrameStyle(QFrame.NoFrame) self._neditable = neditable self.allow_word_wrap(False) self.setMouseTracking(True) self.setCursorWidth(2) self.__encoding = None self._highlighter = None self._last_line_position = 0 # Extra Selections self._extra_selections = ExtraSelectionManager(self) # Load indenter based on language self._indenter = indenter.load_indenter(self, neditable.language()) # Widgets on side area self.side_widgets = manager.SideWidgetManager(self) self.__link_pressed = False # Set editor font before build lexer self.set_font(settings.FONT) # Register extensions self.__extensions = {} # Brace matching self._brace_matching = self.register_extension( symbol_highlighter.SymbolHighlighter) self.brace_matching = settings.BRACE_MATCHING # Current line highlighter self._line_highlighter = self.register_extension( line_highlighter.CurrentLineHighlighter) self.highlight_current_line = settings.HIGHLIGHT_CURRENT_LINE # Right margin line self._margin_line = self.register_extension(margin_line.RightMargin) self.margin_line = settings.SHOW_MARGIN_LINE self.margin_line_position = settings.MARGIN_LINE self.margin_line_background = settings.MARGIN_LINE_BACKGROUND # Indentation guides self._indentation_guides = self.register_extension( indentation_guides.IndentationGuide) self.show_indentation_guides(settings.SHOW_INDENTATION_GUIDES) # Autocomplete braces self.__autocomplete_braces = self.register_extension( braces.AutocompleteBraces) self.autocomplete_braces(settings.AUTOCOMPLETE_BRACKETS) # Autocomplete quotes self.__autocomplete_quotes = self.register_extension( quotes.AutocompleteQuotes) self.autocomplete_quotes(settings.AUTOCOMPLETE_QUOTES) # Calltips # Highlight word under cursor self.__word_occurrences = [] self._highlight_word_timer = QTimer() self._highlight_word_timer.setSingleShot(True) self._highlight_word_timer.setInterval(1000) self._highlight_word_timer.timeout.connect( self.highlight_selected_word) # Install custom scrollbar self._scrollbar = scrollbar.NScrollBar(self) self._scrollbar.setAttribute(Qt.WA_OpaquePaintEvent, False) self.setVerticalScrollBar(self._scrollbar) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.additional_builtins = None # Set the editor after initialization if self._neditable is not None: if self._neditable.editor: self.setDocument(self._neditable.document) else: self._neditable.set_editor(self) self._neditable.checkersUpdated.connect(self._highlight_checkers) self.cursorPositionChanged.connect(self._on_cursor_position_changed) self.blockCountChanged.connect(self.update) # Mark text changes self._text_change_widget = self.side_widgets.add( text_change_widget.TextChangeWidget) self.show_text_changes(settings.SHOW_TEXT_CHANGES) # Breakpoints/bookmarks widget self._marker_area = self.side_widgets.add( marker_widget.MarkerWidget) # Line number widget self._line_number_widget = self.side_widgets.add( line_number_widget.LineNumberWidget) self.show_line_numbers(settings.SHOW_LINE_NUMBERS) # Code folding self.side_widgets.add(code_folding.CodeFoldingWidget) from ninja_ide.gui.editor import intellisense_assistant as ia self._iassistant = None intellisense = IDE.get_service("intellisense") if intellisense is not None: if intellisense.provider_services(self._neditable.language()): self._iassistant = ia.IntelliSenseAssistant(self) @property def nfile(self): return self._neditable.nfile @property def neditable(self): return self._neditable @property def file_path(self): return self._neditable.file_path @property def is_modified(self): return self.document().isModified() @property def encoding(self): if self.__encoding is not None: return self.__encoding return "utf-8" @encoding.setter def encoding(self, encoding): self.__encoding = encoding @property def default_font(self): return self.document().defaultFont() @default_font.setter def default_font(self, font): super().setFont(font) self._update_tab_stop_width() @property def indentation_width(self): return self._indenter.width @property def extra_selections(self): return self._extra_selections @indentation_width.setter def indentation_width(self, width): self._indenter.width = width self._update_tab_stop_width() @pyqtSlot() def _on_cursor_position_changed(self): line, col = self.cursor_position self.cursor_position_changed.emit(line, col) if line != self._last_line_position: self._last_line_position = line self.current_line_changed.emit(line) # Create marker for scrollbar self.update_current_line_in_scrollbar(line) # Mark occurrences self._highlight_word_timer.stop() self._highlight_word_timer.start() def scrollbar(self): return self._scrollbar def insertFromMimeData(self, source): if self.isReadOnly(): return text = source.text() if not text: return cursor = self.textCursor() with self: cursor.removeSelectedText() cursor.insertText(text) self.setTextCursor(cursor) def update_current_line_in_scrollbar(self, current_line): """Update current line highlight in scrollbar""" self._scrollbar.remove_marker('current_line') if self._scrollbar.maximum() > 0: self._scrollbar.add_marker( "current_line", current_line, "white", priority=2) def show_line_numbers(self, value): self._line_number_widget.setVisible(value) def show_text_changes(self, value): self._text_change_widget.setVisible(value) def __clear_occurrences(self): self.__word_occurrences.clear() self._extra_selections.remove("occurrences") def highlight_selected_word(self): """Highlight word under cursor""" # Clear previous selections self.__clear_occurrences() if self._extra_selections.get("find"): # No re-highlight occurrences when have "find" extra selections return word = self.word_under_cursor().selectedText() if not word: return results = self._get_find_index_results(word, cs=False, wo=True)[1] selections = [] append = selections.append # On very big files where a lots of occurrences can be found, # this freeze the editor during a few seconds. So, we can limit of 500 # and make sure the editor will always remain responsive for start_pos, end_pos in results[:500]: selection = extra_selection.ExtraSelection( self.textCursor(), start_pos=start_pos, end_pos=end_pos ) color = resources.COLOR_SCHEME.get("editor.occurrence") selection.set_background(color) append(selection) # TODO: highlight results in scrollbar # FIXME: from settings self._extra_selections.add("occurrences", selections) def clear_found_results(self): self._scrollbar.remove_marker("find") self._extra_selections.remove("find") def highlight_found_results(self, text, cs=False, wo=False): """Highlight all found results from find/replace widget""" index, results = self._get_find_index_results(text, cs=cs, wo=wo) selections = [] append = selections.append color = resources.COLOR_SCHEME.get("editor.search.result") for start, end in results: selection = extra_selection.ExtraSelection( self.textCursor(), start_pos=start, end_pos=end ) selection.set_background(color) selection.set_foreground(utils.get_inverted_color(color)) append(selection) line = selection.cursor.blockNumber() self._scrollbar.add_marker("find", line, color) self._extra_selections.add("find", selections) return index, len(results) def _highlight_checkers(self, neditable): """Add checker selections to the Editor""" # Remove selections if they exists self._extra_selections.remove("checker") self._scrollbar.remove_marker("checker") # Get checkers from neditable checkers = neditable.sorted_checkers selections = [] append = selections.append # Reduce name look-ups for better speed for items in checkers: checker, color, _ = items lines = sorted(checker.checks.keys()) for line in lines[:self._MAX_CHECKER_SELECTIONS]: cursor = self.textCursor() # Scrollbar marker self._scrollbar.add_marker("checker", line, color, priority=1) ms = checker.checks[line] for (col_start, col_end), _, _ in ms: selection = extra_selection.ExtraSelection( cursor, start_line=line, col_start=col_start, col_end=col_end ) selection.set_underline(color) append(selection) self._extra_selections.add("checker", selections) def show_indentation_guides(self, value): self._indentation_guides.actived = value def register_extension(self, Extension): extension_instance = Extension() self.__extensions[Extension.name] = extension_instance extension_instance.initialize(self) return extension_instance def autocomplete_braces(self, value): self.__autocomplete_braces.actived = value def autocomplete_quotes(self, value): self.__autocomplete_quotes.actived = value def navigate_bookmarks(self, forward=True): if forward: self._marker_area.next_bookmark() else: self._marker_area.previous_bookmark() def register_syntax_for(self, language="python", force=False): syntax = highlighter.build_highlighter(language) if syntax is not None: self._highlighter = highlighter.SyntaxHighlighter( self.document(), syntax.partition_scanner, syntax.scanners, syntax.context ) def set_font(self, font): """Set font and update tab stop width""" super().setFont(font) self.side_widgets.resize() self.side_widgets.update_viewport() self._update_tab_stop_width() def _update_tab_stop_width(self): """Update the tab stop width""" width = self.fontMetrics().width(' ') * self._indenter.width self.setTabStopWidth(width) def allow_word_wrap(self, value): wrap_mode = wrap_mode = self.NoWrap if value: wrap_mode = self.WidgetWidth self.setLineWrapMode(wrap_mode) def font_antialiasing(self, value): font = self.default_font style = font.PreferAntialias if not value: style = font.NoAntialias font.setStyleStrategy(style) self.default_font = font def viewportEvent(self, event): if event.type() == QEvent.ToolTip: pos = event.pos() tc = self.cursorForPosition(pos) block = tc.block() line = block.layout().lineForTextPosition(tc.positionInBlock()) if line.isValid(): if pos.x() <= self.blockBoundingRect(block).left() + \ line.naturalTextRect().right(): column = tc.positionInBlock() line = self.line_from_position(pos.y()) checkers = self._neditable.sorted_checkers for items in checkers: checker, _, _ = items messages_for_line = checker.message(line) if messages_for_line is not None: for (start, end), message, content in \ messages_for_line: if column >= start and column <= end: QToolTip.showText( self.mapToGlobal(pos), message, self) return True QToolTip.hideText() return super().viewportEvent(event) def focusInEvent(self, event): super().focusInEvent(event) if event.reason() == Qt.MouseFocusReason: self.editorFocusObtained.emit() def dropEvent(self, event): if event.type() == Qt.ControlModifier and self.has_selection: insertion_cursor = self.cursorForPosition(event.pos()) insertion_cursor.insertText(self.selected_text()) else: super().dropEvent(event) def paintEvent(self, event): super().paintEvent(event) self.painted.emit(event) def resizeEvent(self, event): super().resizeEvent(event) self.side_widgets.resize() self.side_widgets.update_viewport() self.adjust_scrollbar_ranges() def __smart_backspace(self): accepted = False cursor = self.textCursor() text_before_cursor = self.text_before_cursor(cursor) text = cursor.block().text() indentation = self._indenter.text() space_at_start_len = len(text) - len(text.lstrip()) column_number = cursor.positionInBlock() if text_before_cursor.endswith(indentation) and \ space_at_start_len == column_number and \ not cursor.hasSelection(): to_remove = len(text_before_cursor) % len(indentation) if to_remove == 0: to_remove = len(indentation) cursor.setPosition(cursor.position() - to_remove, QTextCursor.KeepAnchor) cursor.removeSelectedText() accepted = True return accepted def __manage_key_home(self, event): """Performs home key action""" cursor = self.textCursor() indent = self.line_indent() # For selection move = QTextCursor.MoveAnchor if event.modifiers() == Qt.ShiftModifier: move = QTextCursor.KeepAnchor # Operation if cursor.positionInBlock() == indent: cursor.movePosition(QTextCursor.StartOfBlock, move) elif cursor.atBlockStart(): cursor.setPosition(cursor.block().position() + indent, move) elif cursor.positionInBlock() > indent: cursor.movePosition(QTextCursor.StartOfLine, move) cursor.setPosition(cursor.block().position() + indent, move) self.setTextCursor(cursor) event.accept() def is_keyword(self, text): import keyword return text in keyword.kwlist def mouseReleaseEvent(self, event): super().mouseReleaseEvent(event) if event.modifiers() == Qt.ControlModifier: if event.button() == Qt.LeftButton: if self.__link_pressed: cursor = self.cursorForPosition(event.pos()) self._go_to_definition_requested(cursor) def _go_to_definition_requested(self, cursor): text = self.word_under_cursor(cursor).selectedText() if text and not self.inside_string_or_comment(cursor): self._iassistant.invoke("definitions") def _update_link(self, mouse_event): if mouse_event.modifiers() == Qt.ControlModifier: cursor = self.cursorForPosition(mouse_event.pos()) text = self.word_under_cursor(cursor).selectedText() if self.inside_string_or_comment(cursor) or self.is_keyword(text): return if not text: self.clear_link() return self.show_link(cursor) self.viewport().setCursor(Qt.PointingHandCursor) return self.clear_link() def show_link(self, cursor): start_s, end_s = cursor.selectionStart(), cursor.selectionEnd() selection = extra_selection.ExtraSelection( cursor, start_pos=start_s, end_pos=end_s ) link_color = resources.COLOR_SCHEME.get("editor.link.navigate") selection.set_underline(link_color, style=1) selection.set_foreground(link_color) self._extra_selections.add("link", selection) self.__link_pressed = True def clear_link(self): self._extra_selections.remove("link") self.viewport().setCursor(Qt.IBeamCursor) self.__link_pressed = False def wheelEvent(self, event): # Avoid scrolling the editor when the completions view is displayed if self._iassistant is not None: if self._iassistant._proposal_widget is not None: if not self._iassistant._proposal_widget.isVisible(): super().wheelEvent(event) else: super().wheelEvent(event) else: super().wheelEvent(event) def mouseMoveEvent(self, event): if self._highlighter is not None: self._update_link(event) # Restore mouse cursor if settings say hide while typing if self.viewport().cursor().shape() == Qt.BlankCursor: self.viewport().setCursor(Qt.IBeamCursor) super(NEditor, self).mouseMoveEvent(event) def is_modifier(self, key_event): key = key_event.key() modifiers = (Qt.Key_Shift, Qt.Key_Control, Qt.Key_Meta, Qt.Key_Alt) if key in modifiers: return True return False def keyReleaseEvent(self, event): self.keyReleased.emit(event) if event.key() == Qt.Key_Control: self.clear_link() super().keyReleaseEvent(event) def show_tooltip(self, text, position, duration=1000 * 60): QToolTip.showText(position, text, self, self.rect(), duration) def hide_tooltip(self): QToolTip.hideText() def current_color(self, cursor=None): """Get the sintax highlighting color for the current QTextCursor""" if cursor is None: cursor = self.textCursor() block = cursor.block() pos = cursor.position() - block.position() layout = block.layout() block_formats = layout.additionalFormats() if block_formats: if cursor.atBlockEnd(): current_format = block_formats[-1].format else: current_format = None for fmt in block_formats: if (pos >= fmt.start) and (pos < fmt.start + fmt.length): current_format = fmt.format if current_format is None: return None color = current_format.foreground().color().name() return color else: return None def inside_string_or_comment(self, cursor=None): """Check if the cursor is inside a comment or string""" if self._highlighter is None: return False if cursor is None: cursor = self.textCursor() current_color = self.current_color(cursor) colors = [] for k, v in self._highlighter.formats.items(): if k.startswith("comment") or k.startswith("string"): colors.append(v.foreground().color().name()) if current_color in colors: return True return False def _complete_declaration(self): if not self.neditable.language() == "python": return line, _ = self.cursor_position line_text = self.line_text(line - 1).strip() pat_class = re.compile("(\\s)*class.+\\:$") if pat_class.match(line_text): cursor = self.textCursor() block = cursor.block() init = False while block.isValid(): text = block.text().strip() if text and text.startswith("def __init__(self"): init = True break block = block.next() if init: return class_name = [name for name in re.split("(\\s)*class(\\s)+|:|\\(", line_text) if name is not None and name.strip()][0] line, col = self.cursor_position indentation = self.line_indent(line) * " " init_def = "def __init__(self):" definition = "\n{}{}\n{}".format( indentation, init_def, indentation * 2 ) super_include = "" if line_text.find("(") != -1: classes = line_text.split("(") parents = [] if len(classes) > 1: parents += classes[1].split(",") if len(parents) > 0 and "object):" not in parents: super_include = "super({}, self).__init__()".format( class_name) definition = "\n{}{}\n{}{}\n{}".format( indentation, init_def, indentation * 2, super_include, indentation * 2 ) self.insert_text(definition) def keyPressEvent(self, event): if not self.is_modifier(event) and settings.HIDE_MOUSE_CURSOR: self.viewport().setCursor(Qt.BlankCursor) if self.isReadOnly(): return text = event.text() if text: self.__clear_occurrences() event.ignore() # Emit a signal then plugins can do something self.keyPressed.emit(event) if event.matches(QKeySequence.InsertParagraphSeparator): cursor = self.textCursor() if not self.inside_string_or_comment(cursor): self._indenter.indent_block(self.textCursor()) self._complete_declaration() return if event.key() == Qt.Key_Home: self.__manage_key_home(event) return elif event.key() == Qt.Key_Tab: if self.textCursor().hasSelection(): self._indenter.indent_selection() else: self._indenter.indent() event.accept() elif event.key() == Qt.Key_Backspace: if not event.isAccepted(): if self.__smart_backspace(): event.accept() if not event.isAccepted(): super().keyPressEvent(event) # Post key press self.postKeyPressed.emit(event) # TODO: generalize it with triggers # TODO: shortcut def adjust_scrollbar_ranges(self): line_spacing = QFontMetrics(self.font()).lineSpacing() if line_spacing == 0: return offset = self.contentOffset().y() self._scrollbar.set_visible_range( (self.viewport().rect().height() - offset) / line_spacing) self._scrollbar.set_range_offset(offset / line_spacing) def _get_find_index_results(self, expr, cs, wo): text = self.text current_index = 0 if not cs: text = text.lower() expr = expr.lower() expr = re.escape(expr) if wo: expr = r"\b" + re.escape(expr) + r"\b" def find_all_iter(string, sub): try: reobj = re.compile(sub) except sre_constants.error: return for match in reobj.finditer(string): yield match.span() matches = list(find_all_iter(text, expr)) if len(matches) > 0: position = self.textCursor().position() current_index = sum(1 for _ in re.finditer(expr, text[:position])) return current_index, matches def show_run_cursor(self): """Highlight momentarily a piece of code""" cursor = self.textCursor() if self.has_selection(): # Get selection range start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() else: # If no selected text, highlight current line cursor.movePosition(QTextCursor.StartOfLine) start_pos = cursor.position() cursor.movePosition(QTextCursor.EndOfLine) end_pos = cursor.position() # Create extra selection selection = extra_selection.ExtraSelection( cursor, start_pos=start_pos, end_pos=end_pos ) selection.set_background("gray") self._extra_selections.add("run_cursor", selection) # Clear selection for show correctly the extra selection cursor.clearSelection() self.setTextCursor(cursor) # Remove extra selection after 0.3 seconds QTimer.singleShot( 300, lambda: self._extra_selections.remove("run_cursor")) def link(self, clone): """Links the clone with its original""" # TODO: errro en compute indent clone.cursor_position = self.cursor_position for kind, selections in self._extra_selections.items(): clone._extra_selections.add(kind, selections) clone.scrollbar().link(self._scrollbar) def comment_or_uncomment(self): cursor = self.textCursor() doc = self.document() block_start = doc.findBlock(cursor.selectionStart()) block_end = doc.findBlock(cursor.selectionEnd()).next() key = self.neditable.language() card = settings.SYNTAX[key].get("comment", [])[0] has_selection = self.has_selection() lines_commented = 0 lines_without_comment = 0 with self: # Save blocks for use later temp_start, temp_end = block_start, block_end min_indent = sys.maxsize comment = True card_lenght = len(card) # Get operation (comment/uncomment) and the minimum indent # of selected lines while temp_start != temp_end: block_number = temp_start.blockNumber() indent = self.line_indent(block_number) block_text = temp_start.text().lstrip() if not block_text: temp_start = temp_start.next() continue min_indent = min(indent, min_indent) if block_text.startswith(card): lines_commented += 1 comment = False elif block_text.startswith(card.strip()): lines_commented += 1 comment = False card_lenght -= 1 else: lines_without_comment += 1 comment = True temp_start = temp_start.next() total_lines = lines_commented + lines_without_comment if lines_commented > 0 and lines_commented != total_lines: comment = True # Comment/uncomment blocks while block_start != block_end: cursor.setPosition(block_start.position()) cursor.movePosition(QTextCursor.StartOfLine) cursor.movePosition(QTextCursor.Right, QTextCursor.MoveAnchor, min_indent) if block_start.text().lstrip(): if comment: cursor.insertText(card) else: cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, card_lenght) cursor.removeSelectedText() block_start = block_start.next() if not has_selection: cursor.movePosition(QTextCursor.Down) self.setTextCursor(cursor) class ExtraSelectionManager(object): def __init__(self, neditor): self._neditor = neditor self.__selections = OrderedDict() def __len__(self): return len(self.__selections) def __iter__(self): return iter(self.__selections) def __getitem__(self, kind): return self.__selections[kind] def get(self, kind): return self.__selections.get(kind, []) def add(self, kind, selection): """Adds a extra selection on a editor instance""" if not isinstance(selection, list): selection = [selection] self.__selections[kind] = selection self.update() def remove(self, kind): """Removes a extra selection from the editor""" if kind in self.__selections: self.__selections[kind].clear() self.update() def items(self): return self.__selections.items() def remove_all(self): for kind in self: self.remove(kind) def update(self): selections = [] for kind, selection in self.__selections.items(): selections.extend(selection) selections = sorted(selections, key=lambda sel: sel.order) self._neditor.setExtraSelections(selections) def create_editor(neditable=None): neditor = NEditor(neditable) language = neditable.language() if language is None: # For python files without the extension # FIXME: Move to another module # FIXME: Generalize it? for line in neditor.text.splitlines(): if not line.strip(): continue if line.startswith("#!"): shebang = line[2:] if "python" in shebang: language = "python" else: break neditor.register_syntax_for(language) return neditor
33,555
Python
.py
791
31.587863
79
0.606897
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,515
intellisense_assistant.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/intellisense_assistant.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtCore import QObject from PyQt5.QtCore import Qt from ninja_ide import translations from ninja_ide.gui.editor import proposal_widget from ninja_ide.gui.ide import IDE from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger(__name__) class IntelliSenseAssistant(QObject): def __init__(self, editor): QObject.__init__(self) self._editor = editor # Proposal widget self._proposal_widget = None self.__kind = "completions" self.__handlers = { "completions": self._handle_completions, "calltips": self._handle_calltips, "definitions": self._handle_definitions } self._intellisense = IDE.get_service("intellisense") self._provider = self._intellisense.provider( editor.neditable.language()) # Connections self._editor.postKeyPressed.connect(self._on_post_key_pressed) self._editor.keyReleased.connect(self._on_key_released) self._editor.destroyed.connect(self.deleteLater) def _on_key_released(self, event): key = event.key() if key in (Qt.Key_ParenLeft, Qt.Key_Comma): self.invoke("calltips") elif key in ( Qt.Key_ParenRight, Qt.Key_Return, Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, Qt.Key_Backspace, Qt.Key_Escape): self._editor.hide_tooltip() def _on_post_key_pressed(self, key_event): if key_event.key() == Qt.Key_Escape: self._editor.hide_tooltip() key = key_event.text() if not key: return # TODO: shortcut if key in self._provider.triggers and not \ self._editor.inside_string_or_comment(): self.invoke("completions") def invoke(self, kind): self.__kind = kind self._intellisense.resultAvailable.connect(self._on_result_available) if kind == "completions": if self._proposal_widget is not None: self._proposal_widget.abort() self._intellisense.process(kind, self._editor) def _on_result_available(self, result): self._intellisense.resultAvailable.disconnect( self._on_result_available) try: handler = self.__handlers[self.__kind] handler(result) except KeyError as reason: logger.error(reason) def _handle_calltips(self, signatures: list): if not signatures: return calltip = "<p style='white-space:pre'>{0}(".format( signatures.get("signature.name")) params = signatures.get("signature.params") for i, param in enumerate(params): if i == signatures.get("signature.index"): calltip += "<b><u>" calltip += param if i == signatures.get("signature.index"): calltip += "</u></b>" if i < len(params) - 1: calltip += ", " calltip += ")" font = self._editor.default_font crect = self._editor.cursorRect() crect.setX(crect.x() + self._editor.viewport().x()) position = self._editor.mapToGlobal(crect.topLeft()) position.setY(position.y() + font.pointSize() + 1) self._editor.show_tooltip(calltip, position) def _handle_completions(self, completions: list): if not completions: return _completions = [] append = _completions.append for completion in completions: item = proposal_widget.ProposalItem(completion["text"]) completion_type = completion["type"] item.type = completion_type item.detail = completion["detail"] item.set_icon(completion_type) append(item) self._create_view(_completions) def _handle_definitions(self, defs): if defs: defs = defs[0] if defs["line"] is not None: line = defs["line"] - 1 column = defs["column"] fname = defs["filename"] if fname == self._editor.file_path: self._editor.go_to_line(line, column) else: main_container = IDE.get_service("main_container") main_container.open_file(fname, line, column) return ide = IDE.get_service("ide") ide.show_message(translations.TR_DEFINITION_NOT_FOUND) def _create_view(self, completions): """Create proposal widget to show completions""" self._proposal_widget = proposal_widget.ProposalWidget(self._editor) self._proposal_widget.destroyed.connect(self.finalize) self._proposal_widget.proposalItemActivated.connect( self._process_proposal_item) model = proposal_widget.ProposalModel(self._proposal_widget) model.set_items(completions) self._proposal_widget.set_model(model) self._proposal_widget.show_proposal() def finalize(self): del self._proposal_widget self._proposal_widget = None def _process_proposal_item(self, item): prefix = self._editor.word_under_cursor().selectedText() to_insert = item.text[len(prefix):] prefix_inserted = item.text[:len(prefix)] if prefix_inserted != prefix: # If the item to be inserted is different from what # we are writing, then we fix that # e.g. str.CAPIT --> str.capitalize instead of str.CAPITalize cursor = self._editor.textCursor() cursor.movePosition( cursor.Left, cursor.KeepAnchor, len(prefix_inserted)) cursor.removeSelectedText() self._editor.textCursor().insertText(prefix_inserted) self._editor.textCursor().insertText(to_insert) if item.type == "function": self._editor.textCursor().insertText("()")
6,751
Python
.py
159
32.603774
77
0.61084
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,516
base.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/base.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. """ Base editor """ from PyQt5.QtWidgets import QPlainTextEdit from PyQt5.QtGui import QTextBlockUserData from PyQt5.QtGui import QTextDocument from PyQt5.QtGui import QTextCursor from PyQt5.QtCore import QPoint _WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:\'\",.<>/?' class BaseTextEditor(QPlainTextEdit): def __init__(self): super().__init__() self.word_separators = _WORD_SEPARATORS def __enter__(self): self.textCursor().beginEditBlock() def __exit__(self, exc_type, exc_value, traceback): self.textCursor().endEditBlock() @property def cursor_position(self): """Get or set the current cursor position""" cursor = self.textCursor() return (cursor.blockNumber(), cursor.columnNumber()) @cursor_position.setter def cursor_position(self, position): line, column = position line = min(line, self.line_count() - 1) column = min(column, len(self.line_text(line))) cursor = QTextCursor(self.document().findBlockByNumber(line)) cursor.setPosition(cursor.block().position() + column, QTextCursor.MoveAnchor) self.setTextCursor(cursor) @property def text(self): """Get or set the plain text editor's content. The previous contents are removed.""" return self.toPlainText() @text.setter def text(self, text): self.setPlainText(text) def line_text(self, line=-1): """Returns the text of the specified line""" if line == -1: line, _ = self.cursor_position block = self.document().findBlockByNumber(line) return block.text() def line_count(self): """Returns the number of lines""" return self.document().blockCount() def line_indent(self, line=-1): """Returns the indentation level of `line`""" if line == -1: line, _ = self.cursor_position text = self.line_text(line) indentation = len(text) - len(text.lstrip()) return indentation def insert_text(self, text): if not self.isReadOnly(): self.textCursor().insertText(text) def first_visible_block(self): return self.firstVisibleBlock() def last_visible_block(self): return self.cursorForPosition( QPoint(0, self.viewport().height())).block() def selection_range(self): """Returns the start and end number of selected lines""" text_cursor = self.textCursor() start = self.document().findBlock( text_cursor.selectionStart()).blockNumber() end = self.document().findBlock( text_cursor.selectionEnd()).blockNumber() if text_cursor.columnNumber() == 0 and start != end: end -= 1 return start, end def has_selection(self): return self.textCursor().hasSelection() def selected_text(self): """Returns the selected text""" return self.textCursor().selectedText() def get_right_word(self): """Gets the word on the right of the text cursor""" cursor = self.textCursor() cursor.movePosition(QTextCursor.WordRight, QTextCursor.KeepAnchor) return cursor.selectedText().strip() def get_right_character(self): """Gets the right character on the right of the text cursor""" right_word = self.get_right_word() right_char = None if right_word: right_char = right_word[0] return right_char def word_under_cursor(self, cursor=None, ignore=None): """Returns QTextCursor that contains a word under passed cursor or actual cursor""" if cursor is None: cursor = self.textCursor() word_separators = self.word_separators if ignore is not None: word_separators = [w for w in self.word_separators if w not in ignore] start_pos = end_pos = cursor.position() while not cursor.atStart(): cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor) selected_text = cursor.selectedText() if not selected_text: break char = selected_text[0] if (selected_text in word_separators and ( selected_text != "n" and selected_text != "t") or char.isspace()): break start_pos = cursor.position() cursor.setPosition(start_pos) cursor.setPosition(end_pos) while not cursor.atEnd(): cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) selected_text = cursor.selectedText() if not selected_text: break char = selected_text[0] if (selected_text in word_separators and ( selected_text != "n" and selected_text != "t") or char.isspace()): break end_pos = cursor.position() cursor.setPosition(end_pos) cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) return cursor def move_up_down(self, up=False): cursor = self.textCursor() move = cursor with self: has_selection = cursor.hasSelection() start, end = cursor.selectionStart(), cursor.selectionEnd() if has_selection: move.setPosition(start) move.movePosition(QTextCursor.StartOfBlock) move.setPosition(end, QTextCursor.KeepAnchor) m = QTextCursor.EndOfBlock if move.atBlockStart(): m = QTextCursor.Left move.movePosition(m, QTextCursor.KeepAnchor) else: move.movePosition(QTextCursor.StartOfBlock) move.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) text = cursor.selectedText() move.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) move.removeSelectedText() if up: move.movePosition(QTextCursor.PreviousBlock) move.insertBlock() move.movePosition(QTextCursor.Left) else: move.movePosition(QTextCursor.EndOfBlock) if move.atBlockStart(): move.movePosition(QTextCursor.NextBlock) move.insertBlock() move.movePosition(QTextCursor.Left) else: move.insertBlock() start = move.position() move.clearSelection() move.insertText(text) end = move.position() if has_selection: move.setPosition(end) move.setPosition(start, QTextCursor.KeepAnchor) else: move.setPosition(start) self.setTextCursor(move) def duplicate_line(self): cursor = self.textCursor() if cursor.hasSelection(): text = cursor.selectedText() start = cursor.selectionStart() end = cursor.selectionEnd() cursor_at_start = cursor.position() == start cursor.setPosition(end) cursor.insertText("\n" + text) cursor.setPosition(end if cursor_at_start else start) cursor.setPosition(start if cursor_at_start else end, QTextCursor.KeepAnchor) else: position = cursor.position() block = cursor.block() text = block.text() + "\n" cursor.setPosition(block.position()) cursor.insertText(text) cursor.setPosition(position) self.setTextCursor(cursor) class BlockUserData(QTextBlockUserData): """Representation of the data for a block""" def __init__(self): QTextBlockUserData.__init__(self) self.attrs = {} def get(self, name, default=None): return self.attrs.get(name, default) def __getitem__(self, name): return self.attrs[name] def __setitem__(self, name, value): self.attrs[name] = value class CodeEditor(BaseTextEditor): def __init__(self): super().__init__() self.__visible_blocks = [] @property def visible_blocks(self): return self.__visible_blocks def _update_visible_blocks(self): """Updates the list of visible blocks""" self.__visible_blocks.clear() append = self.__visible_blocks.append block = self.firstVisibleBlock() block_number = block.blockNumber() top = self.blockBoundingGeometry(block).translated( self.contentOffset()).top() bottom = top + self.blockBoundingRect(block).height() editor_height = self.height() while block.isValid(): visible = bottom <= editor_height if not visible: break if block.isVisible(): append((top, block_number, block)) block = block.next() top = bottom bottom = top + self.blockBoundingRect(block).height() block_number += 1 def user_data(self, block=None): if block is None: block = self.textCursor().block() user_data = block.userData() if user_data is None: user_data = BlockUserData() block.setUserData(user_data) return user_data def replace_match(self, word_old, word_new, cs=False, wo=False, wrap_around=True): """ Find if searched text exists and replace it with new one. If there is a selection just do it inside it and exit """ cursor = self.textCursor() text = cursor.selectedText() if not cs: word_old = word_old.lower() text = text.lower() if text == word_old: cursor.insertText(word_new) # Next return self.find_match(word_old, cs, wo, forward=True, wrap_around=wrap_around) def replace_all(self, word_old, word_new, cs=False, wo=False): # Save cursor for restore later cursor = self.textCursor() with self: # Move to beginning of text and replace all self.moveCursor(QTextCursor.Start) found = True while found: found = self.replace_match(word_old, word_new, cs, wo, wrap_around=False) # Reset position self.setTextCursor(cursor) def find_match(self, search, case_sensitive=False, whole_word=False, backward=False, forward=False, wrap_around=True): if not backward and not forward: self.moveCursor(QTextCursor.StartOfWord) flags = QTextDocument.FindFlags() if case_sensitive: flags |= QTextDocument.FindCaseSensitively if whole_word: flags |= QTextDocument.FindWholeWords if backward: flags |= QTextDocument.FindBackward cursor = self.textCursor() found = self.document().find(search, cursor, flags) if not found.isNull(): self.setTextCursor(found) elif wrap_around: if not backward and not forward: cursor.movePosition(QTextCursor.Start) elif forward: cursor.movePosition(QTextCursor.Start) else: cursor.movePosition(QTextCursor.End) # Try again found = self.document().find(search, cursor, flags) if not found.isNull(): self.setTextCursor(found) return not found.isNull()
12,568
Python
.py
308
30.097403
76
0.597163
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,517
extra_selection.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extra_selection.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import QTextEdit from PyQt5.QtGui import ( QTextCursor, QColor, QPen, QTextFormat, QTextCharFormat ) class ExtraSelection(QTextEdit.ExtraSelection): def __init__(self, cursor, start_pos=None, end_pos=None, start_line=None, col_start=None, col_end=None): super().__init__() self.cursor = QTextCursor(cursor) # Highest value will appear on top of the lowest values self.order = 0 if start_pos is not None: self.cursor.setPosition(start_pos) if end_pos is not None: self.cursor.setPosition(end_pos, QTextCursor.KeepAnchor) if start_line is not None: self.cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) self.cursor.movePosition(QTextCursor.Down, QTextCursor.MoveAnchor, start_line) self.cursor.movePosition(QTextCursor.Right, QTextCursor.MoveAnchor, col_end - 1) self.cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, col_end - col_start) def set_underline(self, color, style=QTextCharFormat.DashUnderline): if isinstance(color, str): color = QColor(color) self.format.setUnderlineStyle(style) self.format.setUnderlineColor(color) def set_foreground(self, color): if isinstance(color, str): color = QColor(color) self.format.setForeground(color) def set_background(self, color): if isinstance(color, str): color = QColor(color) self.format.setBackground(color) def set_outline(self, color): self.format.setProperty(QTextFormat.OutlinePen, QPen(QColor(color))) def set_full_width(self): self.format.setProperty(QTextFormat.FullWidthSelection, True)
2,676
Python
.py
62
34.241935
78
0.654127
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,518
symbol_completer.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/symbol_completer.py
from PyQt5.QtGui import QTextCursor from PyQt5.QtCore import Qt class SymbolCompleter(object): """Automatically complete quotes and parentheses""" OPEN_SYMBOLS = '{[(' CLOSE_SYMBOLS = '}])' SYMBOLS = {key: value for (key, value) in zip(OPEN_SYMBOLS, CLOSE_SYMBOLS)} QUOTES = { '"': '"', "'": "'" } def __init__(self, neditor): self._neditor = neditor self._neditor.keyPressed.connect(self._on_key_pressed) self._neditor.post_key_press.connect(self._on_post_key_press) def _on_post_key_press(self, event): symbol = event.text() cursor = self._neditor.textCursor() if symbol and symbol in self.OPEN_SYMBOLS: complementary = self.SYMBOLS[symbol] cursor.insertText(complementary) cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor) self._neditor.setTextCursor(cursor) event.accept() def _on_key_pressed(self, event): char = event.text() cursor = self._neditor.textCursor() if cursor.hasSelection(): if char in self.QUOTES.keys(): complementary = self.QUOTES[char] cursor.insertText( '%s%s%s' % (char, cursor.selectedText(), complementary) ) event.accept() right_char = self._neditor.get_right_character() if event.key() == Qt.Key_Backspace: cursor = self._neditor.textCursor() cursor.movePosition(QTextCursor.Left) cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) remove_char = cursor.selectedText() if remove_char in self.OPEN_SYMBOLS: close_symbol = self.SYMBOLS.get(remove_char, None) if close_symbol is not None and close_symbol == right_char: with self._neditor: cursor.movePosition( QTextCursor.Right, QTextCursor.KeepAnchor) cursor.insertText('') event.accept() if char in self.CLOSE_SYMBOLS: if right_char == char: cursor = self._neditor.textCursor() cursor.clearSelection() cursor.movePosition( QTextCursor.Right, QTextCursor.MoveAnchor) self._neditor.setTextCursor(cursor) event.accept()
2,449
Python
.py
56
31.464286
79
0.579212
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,519
side_area_manager.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/side_area_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. """Manager for side areas""" from PyQt5.QtCore import ( QObject, pyqtSlot, pyqtSignal ) class SideAreaManager(QObject): updateViewportMarginsRequested = pyqtSignal(int) def __init__(self, neditor): super().__init__() self.neditor = neditor self.__widgets = {} self.neditor.blockCountChanged.connect(self._update_margins) def add_area(self, widget): widget.setParent(self.neditor) self.__widgets[widget.object_name] = widget @pyqtSlot() def _update_margins(self): print("Updating margins...") total_width = 0 for side_area in self.__widgets.values(): width = side_area.width() total_width += width self.updateViewportMarginsRequested.emit(total_width)
1,487
Python
.py
40
32.575
70
0.699097
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,520
sidebar_widget.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/sidebar_widget.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import math import re from PyQt4.QtGui import QWidget from PyQt4.QtGui import QBrush from PyQt4.QtGui import QLinearGradient from PyQt4.QtGui import QPixmap from PyQt4.QtGui import QColor from PyQt4.QtGui import QPolygonF from PyQt4.QtGui import QFontMetrics from PyQt4.QtGui import QPainter from PyQt4.QtCore import Qt from PyQt4.QtCore import QPointF from ninja_ide import resources from ninja_ide.core import settings from ninja_ide.gui.editor import helpers # based on: http://john.nachtimwald.com/2009/08/15/qtextedit-with-line-numbers/ # (MIT license) class SidebarWidget(QWidget): def __init__(self, editor, neditable): QWidget.__init__(self, editor) self.edit = editor self._neditable = neditable self.highest_line = 0 self.foldArea = 15 self.rightArrowIcon = QPixmap() self.downArrowIcon = QPixmap() self.pat = re.compile( r"(\s)*\"\"\"|(\s)*def |(\s)*class |(\s)*if |(\s)*while |" "(\\s)*else:|(\\s)*elif |(\\s)*for |" "(\\s)*try:|(\\s)*except:|(\\s)*except |(\\s)*#begin-fold:") self.patNotPython = re.compile('(\\s)*#begin-fold:|(.)*{') self.patComment = re.compile(r"(\s)*\"\"\"") self._endDocstringBlocks = [] self.foldedBlocks = [] self.breakpoints = [] self.bookmarks = [] if self._neditable.file_path in settings.BREAKPOINTS: self.breakpoints = settings.BREAKPOINTS[self._neditable.file_path] if self._neditable.file_path in settings.BOOKMARKS: self.bookmarks = settings.BOOKMARKS[self._neditable.file_path] def update_area(self): maxLine = math.ceil(math.log10(self.edit.blockCount())) width = QFontMetrics( self.edit.document().defaultFont()).width( '0' * int(maxLine)) + 10 + self.foldArea if self.width() != width: self.setFixedWidth(width) self.edit.setViewportMargins(width, 0, 0, 0) self.update() def update(self, *args): QWidget.update(self, *args) def code_folding_event(self, lineNumber): if self._is_folded(lineNumber): self._fold(lineNumber) else: self._unfold(lineNumber) self.edit.update() self.update() def _fold(self, lineNumber): startBlock = self.edit.document().findBlockByNumber(lineNumber - 1) endPos = self._find_fold_closing(startBlock) endBlock = self.edit.document().findBlockByNumber(endPos) block = startBlock.next() while block.isValid() and block != endBlock: block.setVisible(False) block.setLineCount(0) block = block.next() self.foldedBlocks.append(startBlock.blockNumber()) self.edit.document().markContentsDirty(startBlock.position(), endPos) def _unfold(self, lineNumber): startBlock = self.edit.document().findBlockByNumber(lineNumber - 1) endPos = self._find_fold_closing(startBlock) endBlock = self.edit.document().findBlockByNumber(endPos) block = startBlock.next() while block.isValid() and block != endBlock: block.setVisible(True) block.setLineCount(block.layout().lineCount()) endPos = block.position() + block.length() if block.blockNumber() in self.foldedBlocks: close = self._find_fold_closing(block) block = self.edit.document().findBlockByNumber(close) else: block = block.next() self.foldedBlocks.remove(startBlock.blockNumber()) self.edit.document().markContentsDirty(startBlock.position(), endPos) def _is_folded(self, line): block = self.edit.document().findBlockByNumber(line) if not block.isValid(): return False return block.isVisible() def _find_fold_closing(self, block): text = block.text() pat = re.compile('(\\s)*#begin-fold:') patBrace = re.compile('(.)*{$') if pat.match(text): return self._find_fold_closing_label(block) elif patBrace.match(text): return self._find_fold_closing_brace(block) elif self.patComment.match(text): return self._find_fold_closing_docstring(block) spaces = helpers.get_leading_spaces(text) pat = re.compile('^\\s*$|^\\s*#') block = block.next() while block.isValid(): text2 = block.text() if not pat.match(text2): spacesEnd = helpers.get_leading_spaces(text2) if len(spacesEnd) <= len(spaces): if pat.match(block.previous().text()): return block.previous().blockNumber() else: return block.blockNumber() block = block.next() return block.previous().blockNumber() def _find_fold_closing_label(self, block): text = block.text() label = text.split(':')[1] block = block.next() pat = re.compile('\\s*#end-fold:' + label) while block.isValid(): if pat.match(block.text()): return block.blockNumber() + 1 block = block.next() return block.blockNumber() def _find_fold_closing_docstring(self, block): block = block.next() while block.isValid(): if block.text().count('"""') > 0: return block.blockNumber() + 1 block = block.next() return block.blockNumber() def _find_fold_closing_brace(self, block): block = block.next() openBrace = 1 while block.isValid(): openBrace += block.text().count('{') openBrace -= block.text().count('}') if openBrace == 0: return block.blockNumber() + 1 elif openBrace < 0: return block.blockNumber() block = block.next() return block.blockNumber() def paintEvent(self, event): page_bottom = self.edit.viewport().height() font_metrics = QFontMetrics(self.edit.document().defaultFont()) current_block = self.edit.document().findBlock( self.edit.textCursor().position()) pattern = self.pat if self.edit.lang == "python" else self.patNotPython painter = QPainter(self) background = resources.CUSTOM_SCHEME.get( 'sidebar-background', resources.COLOR_SCHEME['sidebar-background']) foreground = resources.CUSTOM_SCHEME.get( 'sidebar-foreground', resources.COLOR_SCHEME['sidebar-foreground']) background_selected = resources.CUSTOM_SCHEME.get( 'sidebar-selected-background', resources.COLOR_SCHEME['sidebar-selected-background']) foreground_selected = resources.CUSTOM_SCHEME.get( 'sidebar-selected-foreground', resources.COLOR_SCHEME['sidebar-selected-foreground']) painter.fillRect(self.rect(), QColor(background)) block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() line_count = block.blockNumber() painter.setFont(self.edit.document().defaultFont()) xofs = self.width() - self.foldArea painter.fillRect(xofs, 0, self.foldArea, self.height(), QColor(resources.CUSTOM_SCHEME.get('fold-area', resources.COLOR_SCHEME['fold-area']))) while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.blockBoundingGeometry(block).topLeft() + \ viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # Set the Painter Pen depending on special lines painter.setPen(QColor(foreground)) error = False checkers = self._neditable.sorted_checkers for items in checkers: checker, color, _ = items if (line_count - 1) in checker.checks: painter.setPen(QColor(color)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True break # We want the line number for the selected line to be bold. bold = False if block == current_block: painter.fillRect( 0, round(position.y()) + font_metrics.descent(), self.width(), font_metrics.ascent() + font_metrics.descent(), QColor(background_selected)) bold = True font = painter.font() font.setBold(True) if not error: painter.setPen(QColor(foreground_selected)) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). if block.isVisible(): painter.drawText( self.width() - self.foldArea - font_metrics.width(str(line_count)) - 3, round(position.y()) + font_metrics.ascent() + font_metrics.descent() - 1, str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) if error: font = painter.font() font.setItalic(False) font.setUnderline(False) painter.setFont(font) block = block.next() self.highest_line = line_count # Code Folding if self.foldArea != self.rightArrowIcon.width(): polygon = QPolygonF() self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea) self.rightArrowIcon.fill(Qt.transparent) self.downArrowIcon = QPixmap(self.foldArea, self.foldArea) self.downArrowIcon.fill(Qt.transparent) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25)) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75)) polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5)) iconPainter = QPainter(self.rightArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get( 'fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) polygon.clear() polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8)) iconPainter = QPainter(self.downArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get( 'fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) self.calculate_docstring_block_fold() block = self.edit.firstVisibleBlock() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break if pattern.match(block.text()) and block.isVisible(): can_fold = True if self.patComment.match(block.text()) and \ (block.blockNumber() in self._endDocstringBlocks): can_fold = False if can_fold: if block.blockNumber() in self.foldedBlocks: painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon) else: painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon) # Add Bookmarks and Breakpoint if block.blockNumber() in self.breakpoints: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(255, 11, 11)) linear_gradient.setColorAt(1, QColor(147, 9, 9)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse( xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1) elif block.blockNumber() in self.bookmarks: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(13, 62, 243)) linear_gradient.setColorAt(1, QColor(5, 27, 106)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawRoundedRect( xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3) block = block.next() painter.end() super(SidebarWidget, self).paintEvent(event) def calculate_docstring_block_fold(self): self._endDocstringBlocks = [] fold_docstring_open = False block = self.edit.firstVisibleBlock() while block.isValid(): # check if block is a docstring if self.patComment.match(block.text()): fold_docstring_open = not fold_docstring_open # if we are closing the docstring block we add it's line number, # so we can skip it later if not fold_docstring_open: self._endDocstringBlocks.append(block.blockNumber()) block = block.next() def mousePressEvent(self, event): if self.foldArea > 0: xofs = self.width() - self.foldArea font_metrics = QFontMetrics(self.edit.document().defaultFont()) fh = font_metrics.lineSpacing() ys = event.posF().y() lineNumber = 0 if event.pos().x() > xofs: pattern = self.pat if self.edit.lang != "python": pattern = self.patNotPython block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() page_bottom = self.edit.viewport().height() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset if position.y() > page_bottom: break if (position.y() < ys and (position.y() + fh) > ys and pattern.match(str(block.text()))): if not block.blockNumber() in self._endDocstringBlocks: lineNumber = block.blockNumber() + 1 break if (position.y() < ys and (position.y() + fh) > ys and event.button() == Qt.LeftButton): line = block.blockNumber() self.set_breakpoint(line) break elif (position.y() < ys and (position.y() + fh) > ys and event.button() == Qt.RightButton): line = block.blockNumber() self.set_bookmark(line) break block = block.next() if lineNumber > 0: self.code_folding_event(lineNumber) def _save_breakpoints_bookmarks(self): if self.bookmarks and not self._neditable.new_document: settings.BOOKMARKS[self._neditable.file_path] = self.bookmarks elif self._neditable.file_path in settings.BOOKMARKS: settings.BOOKMARKS.pop(self._neditable.file_path) if self.breakpoints and not self._neditable.new_document: settings.BREAKPOINTS[self._neditable.file_path] = self.breakpoints elif self._neditable.file_path in settings.BREAKPOINTS: settings.BREAKPOINTS.pop(self._neditable.file_path) def set_breakpoint(self, lineno): if lineno in self.breakpoints: self.breakpoints.remove(lineno) else: self.breakpoints.append(lineno) self.update() self._save_breakpoints_bookmarks() def set_bookmark(self, lineno): if lineno in self.bookmarks: self.bookmarks.remove(lineno) else: self.bookmarks.append(lineno) self.update() self._save_breakpoints_bookmarks()
18,606
Python
.py
399
33.616541
80
0.574285
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,521
helpers.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/helpers.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import re import sys from PyQt5.QtWidgets import QInputDialog from PyQt5.QtGui import QTextCursor from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.tools import introspection patIndent = re.compile('^\\s+') pat_word = re.compile(r"^[\t ]*$|[^\s]+") patSymbol = re.compile(r'[^\w]') patIsLocalFunction = re.compile('(\\s)+self\\.(\\w)+\\(\\)') patClass = re.compile("(\\s)*class.+\\:$") endCharsForIndent = [':', '{', '(', '['] closeBraces = {'{': '}', '(': ')', '[': ']'} # Coding line by language CODING_LINE = { 'python': '# -*- coding: utf-8 -*-' } def get_leading_spaces(line): global patIndent space = patIndent.match(line) if space is not None: return space.group() return '' def get_range(editor, line, col=-1): lineno = line line_text = editor.line_text(lineno) col_end = len(line_text) col_start = col if col > -1 else 0 if col > -1: match = pat_word.match(line_text[col:]) if match: col_end = col_start + match.end() else: col_start = editor.line_indent(lineno) return col_start, col_end def add_line_increment(lines, lineModified, diference, atLineStart=False): """Increment the line number of the list content when needed.""" def _inner_increment(line): if (not atLineStart and line <= lineModified) or ( lineModified == line + diference): return line return line + diference return list(map(_inner_increment, lines)) def add_line_increment_for_dict(data, lineModified, diference, atLineStart=False): """Increment the line number of the dict content when needed.""" def _inner_increment(line): if (not atLineStart and line <= lineModified) or ( lineModified == line + diference): return line newLine = line + diference summary = data.pop(line) data[newLine] = summary return newLine list(map(_inner_increment, list(data.keys()))) return data def insert_horizontal_line(editorWidget): line, index = editorWidget.getCursorPosition() lang = file_manager.get_file_extension(editorWidget.file_path) key = settings.EXTENSIONS.get(lang, 'python') comment_wildcard = settings.SYNTAX[key].get('comment', ['#'])[0] comment = comment_wildcard * ( (80 - editorWidget.lineLength(line) / len(comment_wildcard))) editorWidget.insertAt(comment, line, index) def insert_title_comment(editorWidget): result = str(QInputDialog.getText(editorWidget, editorWidget.tr("Title Comment"), editorWidget.tr("Enter the Title Name:"))[0]) if result: line, index = editorWidget.getCursorPosition() lang = file_manager.get_file_extension(editorWidget.file_path) key = settings.EXTENSIONS.get(lang, 'python') comment_wildcard = settings.SYNTAX[key].get('comment', ['#'])[0] comment = comment_wildcard * (80 / len(comment_wildcard)) editorWidget.SendScintilla(editorWidget.SCI_BEGINUNDOACTION, 1) editorWidget.insertAt(comment, line, index) text = "%s %s\n" % (comment_wildcard, result) editorWidget.insertAt(text, line + 1, 0) editorWidget.insertAt("\n", line + 2, 0) editorWidget.insertAt(comment, line + 2, index) editorWidget.SendScintilla(editorWidget.SCI_ENDUNDOACTION, 1) def insert_coding_line(editorWidget): key = settings.EXTENSIONS.get(editorWidget.nfile.file_ext) coding_line = CODING_LINE.get(key) if coding_line: editorWidget.insert("%s\n" % coding_line) def replace_tabs_with_spaces(editorWidget): text = editorWidget.text() text = text.replace('\t', ' ' * editorWidget._indent) editorWidget.selectAll(True) editorWidget.replaceSelectedText(text) def lint_ignore_line(editorWidget): if not editorWidget.hasSelectedText(): line, index = editorWidget.getCursorPosition() index = editorWidget.lineLength(line) editorWidget.insertAt(" # lint:ok", line, index) def lint_ignore_selection(editorWidget): if editorWidget.hasSelectedText(): editorWidget.SendScintilla(editorWidget.SCI_BEGINUNDOACTION, 1) lstart, istart, lend, iend = editorWidget.getSelection() iend = editorWidget.lineLength(lend) indentation = get_indentation(editorWidget.text(lstart)) editorWidget.insertAt("%s#lint:disable\n" % indentation, lstart, 0) editorWidget.insertAt("\n%s#lint:enable\n" % indentation, lend, iend) editorWidget.SendScintilla(editorWidget.SCI_ENDUNDOACTION, 1) def insert_debugging_prints(editorWidget): if editorWidget.hasSelectedText(): result = str(QInputDialog.getText(editorWidget, editorWidget.tr("Print Text"), editorWidget.tr("Insert a Text to use in the Print or " "leave empty to just print numbers:"))[0]) print_text = "" if result: print_text = "%s: " % result # begin Undo feature editorWidget.SendScintilla(editorWidget.SCI_BEGINUNDOACTION, 1) lstart, istart, lend, iend = editorWidget.getSelection() lines = lend - lstart for i in range(lines): pos = lstart + (i * 2) indentation = get_indentation(editorWidget.text(pos)) editorWidget.insertAt("%sprint('%s%i')\n" % ( indentation, print_text, i), pos, 0) # end Undo feature editorWidget.SendScintilla(editorWidget.SCI_ENDUNDOACTION, 1) def insert_pdb(editorWidget): """Insert a pdb statement into the current line to debug code.""" line, index = editorWidget.getCursorPosition() indentation = get_indentation(editorWidget.text(line)) editorWidget.insertAt("%simport pdb; pdb.set_trace()\n" % indentation, line, 0) def remove_line(editorWidget): if editorWidget.hasSelectedText(): lstart, istart, lend, iend = editorWidget.getSelection() lines = (lend - lstart) + 1 editorWidget.SendScintilla(editorWidget.SCI_BEGINUNDOACTION, 1) editorWidget.setCursorPosition(lstart, istart) for _ in range(lines): editorWidget.SendScintilla(editorWidget.SCI_LINEDELETE, 1) editorWidget.SendScintilla(editorWidget.SCI_ENDUNDOACTION, 1) else: editorWidget.SendScintilla(editorWidget.SCI_LINEDELETE, 1) def check_for_assistance_completion(editorWidget, line): global patClass if patClass.match(line) and editorWidget.lang == 'python': source = editorWidget.text() source = source.encode(editorWidget.encoding) symbols = introspection.obtain_symbols(source) clazzName = [name for name in re.split("(\\s)*class(\\s)+|:|\\(", line) if name is not None and name.strip()][0] clazz_key = [item for item in symbols.get('classes', []) if item.startswith(clazzName)] if clazz_key: clazz = symbols['classes'][clazz_key['lineno']] if [init for init in clazz['members']['functions'] if init.startswith('__init__')]: return lnumber, index = editorWidget.getCursorPosition() indent = get_indentation( line, editorWidget._indent, editorWidget.useTabs) init_def = 'def __init__(self):' definition = "\n%s%s\n%s" % (indent, init_def, indent * 2) super_include = '' if line.find('(') != -1: classes = line.split('(') parents = [] if len(classes) > 1: parents += classes[1].split(',') if len(parents) > 0 and 'object):' not in parents: super_include = "super({0}, self).__init__()".format(clazzName) definition = "\n%s%s\n%s%s\n%s" % ( indent, init_def, indent * 2, super_include, indent * 2) editorWidget.insertAt(definition, lnumber, index) lines = definition.count("\n") + 1 line_pos = lnumber + lines editorWidget.setCursorPosition( line_pos, editorWidget.lineLength(line_pos))
9,011
Python
.py
196
38.168367
79
0.650034
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,522
not_import_checker.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/checkers/not_import_checker.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from collections import defaultdict from PyQt5.QtCore import ( QThread, QTimer, # Qt, pyqtSignal ) from ninja_ide import resources from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.dependencies import notimportchecker as nic from ninja_ide.gui.editor.checkers import ( register_checker, remove_checker, ) from ninja_ide.gui.editor import helpers # TODO: limit results for performance class NotImporterChecker(QThread): checkerCompleted = pyqtSignal() def __init__(self, editor): super(NotImporterChecker, self).__init__() self._editor = editor self._path = '' self._encoding = '' self.checks = defaultdict(list) self.checker_icon = None # self.connect(ninjaide, # lambda: remove_pep8_checker()) self.checkerCompleted.connect(self.refresh_display) @property def dirty(self): return self.checks != {} @property def dirty_text(self): return translations.TR_NOT_IMPORT_CHECKER_TEXT + str(len(self.checks)) def run_checks(self): if not self.isRunning(): self._path = self._editor.file_path self._encoding = self._editor.encoding QTimer.singleShot(10, self.start) def reset(self): self.checks.clear() def run(self): exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) not_imports = dict() if file_ext in exts: self.reset() path = self._editor.file_path checker = nic.Checker(path) not_imports = checker.get_not_imports_on_file( checker.get_imports()) if not_imports is None: pass else: for key, values in not_imports.items(): if isinstance(values['mod_name'], dict): for v in values['mod_name']: message = '[NOTIMP] {}: Dont exist'.format( v) else: message = '[NOTIMP] {}: Dont exist'.format( values['mod_name']) range_ = helpers.get_range( self._editor, values['lineno'] - 1) self.checks[values['lineno'] - 1].append( (range_, message, "")) self.checkerCompleted.emit() def message(self, index): if index in self.checks: return self.checks[index] return None def refresh_display(self): """ if error_list: error_list.refresh_pep8_list(self.checks) """ def remove_nic_checker(): checker = (NotImporterChecker, resources.COLOR_SCHEME.get("editor.checker"), 2) remove_checker(checker) if settings.FIND_ERRORS: register_checker( checker=NotImporterChecker, color=resources.COLOR_SCHEME.get("editor.checker"), priority=2 )
3,829
Python
.py
104
28.413462
78
0.616838
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,523
migration_lists.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/checkers/migration_lists.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from PyQt4.QtGui import QDialog from PyQt4.QtGui import QListWidget from PyQt4.QtGui import QListWidgetItem from PyQt4.QtGui import QLabel from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QSpacerItem from PyQt4.QtGui import QSizePolicy from PyQt4.QtGui import QPlainTextEdit from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide.gui.explorer.explorer_container import ExplorerContainer class MigrationWidget(QDialog): """2to3 Migration Assistance Widget Class""" def __init__(self, parent=None): super(MigrationWidget, self).__init__(parent, Qt.WindowStaysOnTopHint) self._migration, vbox, hbox = {}, QVBoxLayout(self), QHBoxLayout() lbl_title = QLabel(translations.TR_CURRENT_CODE) lbl_suggestion = QLabel(translations.TR_SUGGESTED_CHANGES) self.current_list, self.suggestion = QListWidget(), QPlainTextEdit() self.suggestion.setReadOnly(True) self.btn_apply = QPushButton(translations.TR_APPLY_CHANGES + " !") self.suggestion.setToolTip(translations.TR_SAVE_BEFORE_APPLY + " !") self.btn_apply.setToolTip(translations.TR_SAVE_BEFORE_APPLY + " !") # pack up all widgets hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox.addWidget(self.btn_apply) vbox.addWidget(lbl_title) vbox.addWidget(self.current_list) vbox.addWidget(lbl_suggestion) vbox.addWidget(self.suggestion) vbox.addLayout(hbox) # connections self.connect( self.current_list, SIGNAL("itemClicked(QListWidgetItem*)"), self.load_suggestion) self.connect(self.btn_apply, SIGNAL("clicked()"), self.apply_changes) # registers IDE.register_service('tab_migration', self) ExplorerContainer.register_tab(translations.TR_TAB_MIGRATION, self) def install_tab(self): """Install the Tab on the IDE.""" ide = IDE.get_service('ide') self.connect(ide, SIGNAL("goingDown()"), self.close) def apply_changes(self): """Apply the suggested changes on the Python code.""" lineno = int(self.current_list.currentItem().data(Qt.UserRole)) lines = self._migration[lineno][0].split('\n') remove, code = -1, "" for line in lines: if line.startswith('-'): remove += 1 # line to remove elif line.startswith('+'): code += '{line_to_add}\n'.format(line_to_add=line[1:]) # get and apply changes on editor main_container = IDE.get_service('main_container') if main_container: editorWidget = main_container.get_current_editor() position = editorWidget.SendScintilla( editorWidget.SCI_POSITIONFROMLINE, lineno) curpos = editorWidget.SendScintilla(editorWidget.SCI_GETCURRENTPOS) if curpos != position: editorWidget.SendScintilla(editorWidget.SCI_GOTOPOS, position) endpos = editorWidget.SendScintilla( editorWidget.SCI_GETLINEENDPOSITION, lineno) editorWidget.SendScintilla(editorWidget.SCI_SETCURRENTPOS, endpos) editorWidget.replaceSelectedText(code[:-1]) def load_suggestion(self, item): """Take an argument item and load the suggestion.""" lineno, code = int(item.data(Qt.UserRole)), "" lines = self._migration[lineno][0].split('\n') for line in lines: if line.startswith('+'): code += '{line_to_add}\n'.format(line_to_add=line[1:]) self.suggestion.setPlainText(code) main_container = IDE.get_service('main_container') if main_container: editorWidget = main_container.get_current_editor() if editorWidget: editorWidget.jump_to_line(lineno) editorWidget.setFocus() def refresh_lists(self, migration): """Refresh the list of code suggestions.""" self._migration, base_lineno = migration, -1 self.current_list.clear() for lineno in sorted(migration.keys()): linenostr = 'L{line_number}\n'.format(line_number=str(lineno + 1)) data = migration[lineno] lines = data[0].split('\n') if base_lineno == data[1]: continue base_lineno = data[1] message = '' for line in lines: if line.startswith('-'): message += '{line_to_load}\n'.format(line_to_load=line) item = QListWidgetItem(linenostr + message) item.setToolTip(linenostr + message) item.setData(Qt.UserRole, lineno) self.current_list.addItem(item) def clear(self): """Clear the widget.""" self.current_list.clear() self.suggestion.clear() def reject(self): """Reject""" if self.parent() is None: self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self) def closeEvent(self, event): """Close""" self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self) event.ignore() migrationWidget = MigrationWidget() if settings.SHOW_MIGRATION_LIST else None
6,137
Python
.py
134
37.574627
79
0.661433
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,524
pep8_checker.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/checkers/pep8_checker.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from collections import defaultdict from PyQt5.QtCore import QThread from PyQt5.QtCore import QTimer from PyQt5.QtCore import pyqtSignal from ninja_ide import resources from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.gui.ide import IDE from ninja_ide.dependencies import pycodestyle from ninja_ide.gui.editor.checkers import register_checker from ninja_ide.gui.editor.checkers import remove_checker from ninja_ide.gui.editor import helpers from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger(__name__) class Pep8Checker(QThread): checkerCompleted = pyqtSignal() def __init__(self, editor): super(Pep8Checker, self).__init__() self._editor = editor self._path = '' self._encoding = '' self.checks = defaultdict(list) self.checker_icon = None self.checkerCompleted.connect(self.refresh_display) @property def dirty(self): return self.checks != {} @property def dirty_text(self): return translations.TR_PEP8_DIRTY_TEXT + str(len(self.checks)) def run_checks(self): if not self.isRunning(): self._path = self._editor.file_path self._encoding = self._editor.encoding QTimer.singleShot(0, self.start) def reset(self): self.checks.clear() def run(self): exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: try: self.reset() source = self._editor.text path = self._editor.file_path pep8_style = pycodestyle.StyleGuide( parse_argv=False, config_file='', checker_class=CustomChecker ) temp_data = pep8_style.input_file( path, lines=source.splitlines(True) ) source_lines = source.split('\n') # for lineno, offset, code, text, doc in temp_data: for lineno, col, code, text in temp_data: message = '[PEP8]: %s' % text range_ = helpers.get_range(self._editor, lineno - 1, col) self.checks[lineno - 1].append( (range_, message, source_lines[lineno - 1].strip())) except Exception as reason: logger.warning("Checker not finished: {}".format(reason)) self.checkerCompleted.emit() def message(self, line): if line in self.checks: return self.checks[line] return None def refresh_display(self): error_list = IDE.get_service('tab_errors') if error_list: error_list.refresh_pep8_list(self.checks) class CustomReport(pycodestyle.StandardReport): def get_file_results(self): data = [] for line_number, offset, code, text, doc in self._deferred_print: col = offset + 1 data.append((line_number, col, code, text)) return data class CustomChecker(pycodestyle.Checker): def __init__(self, *args, **kw): super().__init__(*args, report=CustomReport(kw.pop("options")), **kw) def remove_pep8_checker(): checker = (Pep8Checker, resources.COLOR_SCHEME.get("editor.pep8"), 2) remove_checker(checker) if settings.CHECK_STYLE: register_checker( checker=Pep8Checker, color=resources.COLOR_SCHEME.get("editor.pep8"), priority=2 )
4,354
Python
.py
109
31.733945
77
0.639165
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,525
errors_lists.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/checkers/errors_lists.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QDialog, QWidget, QVBoxLayout, QHBoxLayout ) from PyQt5.QtGui import QIcon from PyQt5.QtCore import ( pyqtSignal, QModelIndex, QAbstractItemModel, Qt ) from PyQt5.QtQuickWidgets import QQuickWidget from ninja_ide.core import settings from ninja_ide import resources from ninja_ide.gui.ide import IDE from ninja_ide.tools import ui_tools from ninja_ide import translations from ninja_ide.gui.explorer.explorer_container import ExplorerContainer class ErrorsWidget(QDialog): dockWidget = pyqtSignal('PyQt_PyObject') undockWidget = pyqtSignal('PyQt_PyObject') def __init__(self, parent=None): super().__init__(parent, Qt.WindowStaysOnTopHint) box = QVBoxLayout(self) box.setContentsMargins(0, 0, 0, 0) box.setSpacing(0) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) self._list = ErrorsList() hbox.addWidget(self._list) box.addLayout(hbox) IDE.register_service("tab_errors", self) ExplorerContainer.register_tab(translations.TR_TAB_ERRORS, self) def refresh_pep8_list(self, errors): model = [] for lineno, error in errors.items(): for content in error: pos, message, line_content = content model.append([message, line_content, lineno, pos[0]]) self._list.update_pep8_model(model) def refresh_error_list(self, errors): model = [] for lineno, error in errors.items(): for content in error: pos, message, line_content = content model.append([message, line_content, lineno, pos[0]]) self._list.update_error_model(model) def reject(self): if self.parent() is None: self.dockWidget.emit(self) def closeEvent(self, event): self.dockWidget.emit(self) event.ignore() class ErrorsList(QWidget): def __init__(self, parent=None): super(ErrorsList, self).__init__() self._main_container = IDE.get_service("main_container") # Create the QML user interface. self.view = QQuickWidget() self.view.rootContext().setContextProperty( "theme", resources.QML_COLORS) # Colors from theme warn_bug_colors = {} warn_bug_colors["warning"] = resources.COLOR_SCHEME.get("editor.pep8") warn_bug_colors["bug"] = resources.COLOR_SCHEME.get("editor.checker") self.view.rootContext().setContextProperty("colors", warn_bug_colors) self.view.setResizeMode(QQuickWidget.SizeRootObjectToView) self.view.setSource(ui_tools.get_qml_resource("ErrorsList.qml")) self._root = self.view.rootObject() vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) vbox.addWidget(self.view) self._root.open.connect(self._open) def _open(self, row): self._main_container.editor_go_to_line(row) def update_pep8_model(self, model): self._root.set_pep8_model(model) def update_error_model(self, model): self._root.set_error_model(model) class ModelWarningsErrors(QAbstractItemModel): def __init__(self, data): QAbstractItemModel.__init__(self) self.__data = data def rowCount(self, parent): return len(self.__data) + 1 def columnCount(self, parent): return 1 def index(self, row, column, parent): return self.createIndex(row, column, parent) def parent(self, child): return QModelIndex() def data(self, index, role): if not index.isValid(): return if not index.parent().isValid() and index.row() == 0: if role == Qt.DisplayRole: if self.rowCount(index) > 1: return '<Select Symbol>' return '<No Symbols>' return if role == Qt.DisplayRole: return self.__data[index.row() - 1][1][0] elif role == Qt.DecorationRole: _type = self.__data[index.row() - 1][1][1] if _type == 'f': icon = QIcon(":img/function") elif _type == 'c': icon = QIcon(":img/class") return icon if settings.SHOW_ERRORS_LIST: errorsWidget = ErrorsWidget() else: errorsWidget = None
5,080
Python
.py
132
31.151515
78
0.647561
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,526
__init__.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/checkers/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. NOTIFICATIONS_CHECKERS = {} def register_checker(lang='python', checker=None, color=None, priority=1): """Register a Checker (Like PEP8, Lint, etc) for some language. @lang: language that the checker apply. @checker: Class to be instantiated. @color: the color that this checker will use. @priority: the priority of this checker (1=LOW, >1 = HIGH...)""" global NOTIFICATIONS_CHECKERS checkers = NOTIFICATIONS_CHECKERS.get(lang, []) checkers.append((checker, color, priority)) NOTIFICATIONS_CHECKERS[lang] = checkers def remove_checker(checker): global NOTIFICATIONS_CHECKERS checkers = NOTIFICATIONS_CHECKERS.get('python', []) if checker in checkers: checkers.remove(checker) NOTIFICATIONS_CHECKERS['python'] = checkers def get_checkers_for(lang='python'): """Get a registered checker for some language.""" global NOTIFICATIONS_CHECKERS return NOTIFICATIONS_CHECKERS.get(lang, [])
1,656
Python
.py
37
41.513514
74
0.738213
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,527
migration_2to3.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/checkers/migration_2to3.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess from PyQt4.QtCore import QThread from PyQt4.QtCore import SIGNAL from ninja_ide import resources from ninja_ide.core.file_handling import file_manager from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide.gui.editor.checkers import ( register_checker, remove_checker, ) from ninja_ide.gui.editor.checkers import migration_lists # lint:ok class MigrationTo3(QThread): def __init__(self, editor): super(MigrationTo3, self).__init__() self._editor = editor self._path = '' self.dirty = False self.checks = {} if settings.IS_WINDOWS and settings.PYTHON_EXEC_CONFIGURED_BY_USER: tool_path = os.path.join(os.path.dirname(settings.PYTHON_EXEC), 'Tools', 'Scripts', '2to3.py') self._command = [settings.PYTHON_EXEC, tool_path] else: self._command = ['2to3'] self.checker_icon = None ninjaide = IDE.get_service('ide') self.connect( ninjaide, SIGNAL("ns_preferences_editor_showMigrationTips(PyQt_PyObject)"), lambda: remove_migration_checker()) self.connect(self, SIGNAL("checkerCompleted()"), self.refresh_display) def run_checks(self): if not self.isRunning() and settings.VALID_2TO3: self._path = self._editor.file_path self.start() def run(self): self.sleep(1) exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: self.checks = {} lineno = 0 lines_to_remove = [] lines_to_add = [] parsing_adds = False try: output = subprocess.check_output(self._command + [self._path]) output = output.decode('utf-8').split('\n') except OSError: settings.VALID_2TO3 = False return for line in output[2:]: if line.startswith('+'): lines_to_add.append(line) parsing_adds = True continue if parsing_adds: # Add in migration removes = '\n'.join([liner for _, liner in lines_to_remove]) adds = '\n'.join(lines_to_add) message = self.tr( 'The actual code looks like this:\n%s\n\n' 'For Python3 support, it should look like:\n%s' % (removes, adds)) lineno = -1 for nro, _ in lines_to_remove: if lineno == -1: lineno = nro self.checks[nro] = (message, lineno, "") parsing_adds = False lines_to_add = [] lines_to_remove = [] if line.startswith('-'): lines_to_remove.append((lineno, line)) lineno += 1 if line.startswith('@@'): lineno = int(line[line.index('-') + 1:line.index(',')]) - 1 self.emit(SIGNAL("checkerCompleted()")) def refresh_display(self): tab_migration = IDE.get_service('tab_migration') if tab_migration: tab_migration.refresh_lists(self.checks) def message(self, index): if index in self.checks: return self.checks[index][0] return None def remove_migration_checker(): checker = (MigrationTo3, resources.CUSTOM_SCHEME.get( 'MigrationUnderline', resources.COLOR_SCHEME['MigrationUnderline']), 1) remove_checker(checker) if settings.SHOW_MIGRATION_TIPS: register_checker(checker=MigrationTo3, color=resources.CUSTOM_SCHEME.get( 'MigrationUnderline', resources.COLOR_SCHEME['MigrationUnderline']))
4,905
Python
.py
118
30.228814
79
0.572148
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,528
errors_checker.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/checkers/errors_checker.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import _ast from collections import defaultdict from PyQt5.QtCore import ( QThread, pyqtSignal, QTimer ) from ninja_ide.gui.editor.checkers import ( register_checker, remove_checker ) from ninja_ide import resources from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.dependencies.pyflakes_mod import checker from ninja_ide.gui.ide import IDE from ninja_ide.gui.editor import helpers from ninja_ide.tools.logger import NinjaLogger from ninja_ide.core.file_handling import file_manager logger = NinjaLogger(__file__) class ErrorsChecker(QThread): checkerCompleted = pyqtSignal() def __init__(self, neditor): super().__init__() self._neditor = neditor self._path = '' self.checks = defaultdict(list) self.checker_icon = None self.checkerCompleted.connect(self.refresh_display) def run_checks(self): if not self.isRunning(): self._path = self._neditor.file_path QTimer.singleShot(0, self.start) def reset(self): self.checks.clear() def run(self): exts = settings.SYNTAX.get('python')['extension'] file_ext = file_manager.get_file_extension(self._path) if file_ext in exts: try: self.reset() source = self._neditor.text text = "[Error]: %s" # Compile into an AST and handle syntax errors try: tree = compile(source, self._path, "exec", _ast.PyCF_ONLY_AST) except SyntaxError as reason: if reason.text is None: logger.error("Syntax error") else: text = text % reason.args[0] range_ = helpers.get_range( self._neditor, reason.lineno - 1, reason.offset) self.checks[reason.lineno - 1].append((range_, text, "")) else: # Okay, now check it lint_checker = checker.Checker(tree, self._path) lint_checker.messages.sort(key=lambda msg: msg.lineno) source_lines = source.split('\n') for message in lint_checker.messages: lineno = message.lineno - 1 text = message.message % message.message_args range_ = helpers.get_range( self._neditor, lineno, message.col) self.checks[lineno].append( (range_, text, source_lines[lineno].strip())) except Exception as reason: logger.warning("Checker not finished: {}".format(reason)) self.checkerCompleted.emit() def message(self, lineno): if lineno in self.checks: return self.checks[lineno] return None @property def dirty(self): return self.checks != {} @property def dirty_text(self): return translations.TR_LINT_DIRTY_TEXT + str(len(self.checks)) def refresh_display(self): error_list = IDE.get_service('tab_errors') if error_list: error_list.refresh_error_list(self.checks) def remove_error_checker(): checker = ( ErrorsChecker, resources.COLOR_SCHEME.get('editor.checker'), 10 ) remove_checker(checker) if settings.FIND_ERRORS: register_checker( checker=ErrorsChecker, color=resources.COLOR_SCHEME.get("editor.checker"), priority=10 )
4,322
Python
.py
112
29.267857
82
0.612172
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,529
margin_line.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extensions/margin_line.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. """ Right margin """ from PyQt5.QtGui import ( QPainter, QColor, QFontMetricsF ) from PyQt5.QtCore import QRect from ninja_ide.gui.editor.extensions import base class RightMargin(base.Extension): """Displays a right margin at column the specified position""" @property def position(self): return self.__position @position.setter def position(self, new_pos): if new_pos != self.__position: self.__position = new_pos self.update() @property def color(self): return self.__color @color.setter def color(self, new_color): if new_color != self.__color: self.__color = new_color self.update() @property def background(self) -> bool: return self.__background @background.setter def background(self, value): if self.__background != value: self.__background = value self.update() def __init__(self): super().__init__() self.__position = 79 # Default position self.__color = QColor("gray") self.__color.setAlpha(50) self.__background_color = QColor("gray") self.__background_color.setAlpha(10) self.__background = False def update(self): self._neditor.viewport().update() def install(self): self._neditor.painted.connect(self.draw) self.update() def shutdown(self): self._neditor.painted.disconnect(self.draw) self.update() def draw(self): painter = QPainter(self._neditor.viewport()) painter.setPen(self.__color) metrics = QFontMetricsF(self._neditor.font()) doc_margin = self._neditor.document().documentMargin() offset = self._neditor.contentOffset().x() + doc_margin x = round(metrics.width(' ') * self.__position) + offset if self.__background: width = self._neditor.viewport().width() - x rect = QRect(x, 0, width, self._neditor.height()) painter.fillRect(rect, self.__background_color) painter.drawLine(x, 0, x, self._neditor.height())
2,841
Python
.py
78
30.102564
70
0.648108
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,530
line_highlighter.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extensions/line_highlighter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtGui import QColor from PyQt5.QtGui import QPainter from PyQt5.QtGui import QPen from ninja_ide.gui.editor.extensions import base from ninja_ide.gui.editor.extra_selection import ExtraSelection from ninja_ide import resources from ninja_ide.core import settings class CurrentLineHighlighter(base.Extension): """This extension highlight current line""" # Modes FULL = 0 SIMPLE = 1 @property def mode(self): return self.__mode @mode.setter def mode(self, value): if value != self.__mode: self.shutdown() self.__mode = value self.install() @property def background(self): return self.__background @background.setter def background(self, color): if isinstance(color, str): color = QColor(color) self.__background = color self._highlight() def __init__(self): super().__init__() self.__background = QColor(resources.COLOR_SCHEME.get('editor.line')) self.__background.setAlpha(20) self.__mode = settings.HIGHLIGHT_CURRENT_LINE_MODE def install(self): if self.__mode == self.SIMPLE: self._neditor.painted.connect(self.paint_simple_mode) self._neditor.cursorPositionChanged.connect( self._neditor.viewport().update) else: self._neditor.cursorPositionChanged.connect(self._highlight) self._highlight() def shutdown(self): if self.__mode == self.SIMPLE: self._neditor.painted.disconnect(self.paint_simple_mode) self._neditor.cursorPositionChanged.connect( self._neditor.viewport().update) else: self._neditor.cursorPositionChanged.disconnect(self._highlight) self._neditor.clear_extra_selections('current_line') def paint_simple_mode(self): block = self.text_cursor().block() layout = block.layout() line_count = layout.lineCount() line = layout.lineAt(line_count - 1) if line_count < 1: # Avoid segmentation fault return co = self._neditor.contentOffset() top = self._neditor.blockBoundingGeometry(block).translated(co).top() line_rect = line.naturalTextRect().translated(co.x(), top) painter = QPainter(self._neditor.viewport()) painter.setPen(QPen(self.__background, 1)) painter.drawLine(line_rect.x(), line_rect.y(), self._neditor.width(), line_rect.y()) height = self._neditor.fontMetrics().height() painter.drawLine(line_rect.x(), line_rect.y() + height, self._neditor.width(), line_rect.y() + height) def _highlight(self): self._neditor.extra_selections.remove("current_line") selection = ExtraSelection(self._neditor.textCursor()) selection.set_full_width() selection.set_background(self.__background) self._neditor.extra_selections.add("current_line", selection)
3,754
Python
.py
91
33.791209
77
0.659085
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,531
indentation_guides.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extensions/indentation_guides.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtGui import QPainter from PyQt5.QtGui import QColor from PyQt5.QtCore import Qt from ninja_ide.gui.editor.extensions import base class IndentationGuide(base.Extension): """Indentation guides extension for Ninja-IDE Editor""" def __init__(self): super().__init__() self.color = Qt.darkGray def install(self): self._indentation_width = self._neditor.indentation_width self._neditor.updateRequest.connect(self._neditor.viewport().update) self._neditor.painted.connect(self._draw) self._neditor.viewport().update() def shutdown(self): self._neditor.painted.disconnect(self._draw) self._neditor.updateRequest.connect(self._neditor.viewport().update) self._neditor.viewport().update() def _draw(self, event): doc = self._neditor.document() painter = QPainter(self._neditor.viewport()) color = QColor(self.color) color.setAlphaF(.3) painter.setPen(color) offset = doc.documentMargin() + self._neditor.contentOffset().x() previous = 0 for top, lineno, block in self._neditor.visible_blocks: bottom = top + self._neditor.blockBoundingRect(block).height() indentation = len(block.text()) - len(block.text().lstrip()) if not block.text().strip(): indentation = max(indentation, previous) previous = indentation for i in range(self._indentation_width, indentation, self._indentation_width): x = self._neditor.fontMetrics().width(i * '9') + offset painter.drawLine(x, top, x, bottom)
2,373
Python
.py
52
38.903846
76
0.675886
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,532
__init__.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extensions/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os import imp from ninja_ide import resources class ExtensionRegistry(type): extensions = [] def __new__(cls, classname, bases, attrs): klass = super().__new__(cls, classname, bases, attrs) if classname != 'Extension': extension_name = attrs.get('name', attrs['__module__']) klass.name = extension_name cls.extensions.append(klass) return klass class Extension(metaclass=ExtensionRegistry): """Base class for Editor extensions""" name = None version = None @property def enabled(self): """Tells if the extension is enabled""" return self.__enabled @enabled.setter def enabled(self, value): if value != self.__enabled: self.__enabled = value if value: self.install() else: self.shutdown() def __init__(self, neditor): self.__enabled = False # NINJA-IDE NEditor ref self._neditor = neditor def text_cursor(self): return self._neditor.textCursor() def install(self): """Turn on the extension on the NINJA-IDE editor This method is called when extension is enabled. You may override it if you need to connect editor's signals """ def shutdown(self): """Turn off the extension on the NINJA-IDE editor This method is called when extension is disabled. You may override it if you need to disconnect editor's signals """ def discover_all(extensions_dir='.'): extensions_dir = os.path.join(resources.PRJ_PATH, "gui", "editor", "extensions") for filename in os.listdir(extensions_dir): module_name, ext = os.path.splitext(filename) if ext == '.py' and not filename.startswith('__'): _file, path, descr = imp.find_module(module_name, [extensions_dir]) if _file: imp.load_module(module_name, _file, path, descr)
2,712
Python
.py
69
32.318841
79
0.646499
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,533
symbol_highlighter.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extensions/symbol_highlighter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtGui import QTextCursor from PyQt5.QtGui import QColor from ninja_ide import resources from ninja_ide.gui.editor.extensions import base from ninja_ide.gui.editor.extra_selection import ExtraSelection # TODO: change colors for all editor clones class SymbolHighlighter(base.Extension): """Symbol Matcher extension for Ninja-IDE Editor""" OPEN_SYMBOLS = "([{" CLOSED_SYMBOLS = ")]}" ALL_SYMBOLS = OPEN_SYMBOLS + CLOSED_SYMBOLS SYMBOLS_MAP = dict((k, v) for (k, v) in zip(OPEN_SYMBOLS, CLOSED_SYMBOLS)) REVERSED_SYMBOL_MAP = dict((k, v) for v, k in SYMBOLS_MAP.items()) @property def matched_background(self): """Background color of matching symbol""" return self.__matched_background @matched_background.setter def matched_background(self, color): if isinstance(color, str): color = QColor(color) self.__matched_background = color @property def unmatched_background(self): """Background color of unmatching symbol""" return self.__unmatched_background @unmatched_background.setter def unmatched_background(self, color): if isinstance(color, str): color = QColor(color) self.__unmatched_background = color def __init__(self): super().__init__() self.__matched_background = QColor( resources.COLOR_SCHEME.get("editor.brace.matched")) self.__unmatched_background = QColor( resources.COLOR_SCHEME.get('editor.brace.unmatched')) def install(self): self._neditor.cursorPositionChanged.connect(self._highlight) def shutdown(self): self._neditor.cursorPositionChanged.disconnect(self._highlight) def _highlight(self): self._neditor.extra_selections.remove("matcher") cursor = self._neditor.textCursor() current_block = cursor.block() if self._neditor.inside_string_or_comment(cursor): return column_index = cursor.positionInBlock() if column_index < len(current_block.text()) and \ current_block.text()[column_index] in self.ALL_SYMBOLS: char = current_block.text()[column_index] elif column_index > 0 and current_block.text()[column_index - 1] in \ self.ALL_SYMBOLS: char = current_block.text()[column_index - 1] column_index -= 1 else: return if char in self.OPEN_SYMBOLS: generator = self.__iterate_code_forward(current_block, column_index + 1) else: generator = self.__iterate_code_backward(current_block, column_index) matched_block, matched_index = self.__find_matching_symbol( char, generator) if matched_block is not None: selections = [ self._make_selection(current_block, column_index, True), self._make_selection(matched_block, matched_index, True) ] else: selections = [ self._make_selection(current_block, column_index, False) ] self._neditor.extra_selections.add("matcher", selections) def _make_selection(self, block, index, matched): cur = QTextCursor(block) cur.setPosition(block.position() + index) cur.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) selection = ExtraSelection(cur) background = self.matched_background if not matched: background = self.unmatched_background selection.set_background(background) return selection def __get_complementary_symbol(self, symbol): complementary = self.SYMBOLS_MAP.get(symbol, None) if complementary is None: # If the complementary symbol is not found, # look at the reverse of the dict complementary = self.REVERSED_SYMBOL_MAP[symbol] return complementary def __find_matching_symbol(self, symbol, generator): count = 1 complementary = self.__get_complementary_symbol(symbol) for block, column, char in generator: # Check if current position are inside a comment or string # Because positionInBlock() = cursor.position() - block.position() # and positionInBlock() = column, then "setPositionInBlock": # continue if char == complementary: count -= 1 if count == 0: return block, column elif char == symbol: count += 1 else: return None, None @staticmethod def __iterate_code_forward(block, index): for col, char in list(enumerate(block.text()))[index:]: yield block, col, char block = block.next() while block.isValid(): for col, char in list(enumerate(block.text())): yield block, col, char block = block.next() @staticmethod def __iterate_code_backward(block, index): for col, char in reversed(list(enumerate(block.text()[:index]))): yield block, col, char block = block.previous() while block.isValid(): for col, char in reversed(list(enumerate(block.text()))): yield block, col, char block = block.previous()
6,170
Python
.py
142
34.06338
78
0.629623
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,534
base.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extensions/base.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. class Extension(object): """Base class for Editor extensions""" name = None # Identifier @property def actived(self): """Tells if the extension is enabled""" @actived.setter def actived(self, value): if value != self.__actived: self.__actived = value if value: self.install() else: self.shutdown() def __init__(self): self.name = self.__class__.__name__ self._neditor = None self.__actived = False def initialize(self, neditor): """Initialize the extension""" self._neditor = neditor # NINJA-IDE Neditor ref self.actived = True def text_cursor(self): """Returns the current QTextCursor""" return self._neditor.textCursor() def install(self): """Turn on the extension on the NINJA-IDE editor This method is called when extension is enabled. You may override it if you need to connect editor's signals """ def shutdown(self): """Turn off the extension on the NINJA-IDE editor This method is called when extension is disabled. You may override it if you need to disconnect editor's signals """
1,953
Python
.py
51
32.039216
70
0.659259
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,535
braces.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extensions/braces.py
from PyQt5.QtCore import Qt from PyQt5.QtGui import QTextCursor from ninja_ide.gui.editor.extensions import base class AutocompleteBraces(base.Extension): """Automatically complete braces""" OPENED_BRACES = "[{(" CLOSED_BRACES = "]})" ALL_BRACES = { "(": ")", "[": "]", "{": "}" } def install(self): self._neditor.postKeyPressed.connect(self._on_post_key_pressed) self._neditor.keyPressed.connect(self._on_key_pressed) def shutdown(self): self._neditor.postKeyPressed.disconnect(self._on_post_key_pressed) self._neditor.keyPressed.disconnect(self._on_key_pressed) def _on_key_pressed(self, event): right = self._neditor.get_right_character() current_text = event.text() if current_text in self.CLOSED_BRACES and right == current_text: # Move cursor to right if same symbol is typing cursor = self.text_cursor() cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.MoveAnchor) self._neditor.setTextCursor(cursor) event.accept() elif event.key() == Qt.Key_Backspace: # Remove automatically closed symbol if opened symbol is removed cursor = self.text_cursor() cursor.movePosition(QTextCursor.Left) cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) to_remove = cursor.selectedText() if to_remove in self.ALL_BRACES.keys(): # Opened braces complementary = self.ALL_BRACES.get(to_remove) if complementary is not None and complementary == right: cursor.movePosition( QTextCursor.Right, QTextCursor.KeepAnchor) cursor.insertText('') event.accept() def _on_post_key_pressed(self, event): # Insert complementary symbol char = event.text() if not char: return right = self._neditor.get_right_character() cursor = self.text_cursor() if char in self.OPENED_BRACES: to_insert = self.ALL_BRACES[char] if not right or right in self.CLOSED_BRACES or right.isspace(): cursor.insertText(to_insert) cursor.movePosition(QTextCursor.PreviousCharacter) self._neditor.setTextCursor(cursor)
2,430
Python
.py
54
33.944444
76
0.615027
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,536
quotes.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extensions/quotes.py
from PyQt5.QtGui import QTextCursor from PyQt5.QtCore import Qt from ninja_ide.gui.editor.extensions import base class AutocompleteQuotes(base.Extension): QUOTES = { Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: "'" } def install(self): self._neditor.keyPressed.connect(self._on_key_pressed) def shutdown(self): self._neditor.keyPressed.disconnect(self._on_key_pressed) def _on_key_pressed(self, event): if event.isAccepted(): return key = event.key() if key in self.QUOTES.keys(): self._autocomplete_quotes(key) event.accept() def get_left_chars(self, nchars=1): cursor = self.text_cursor() chars = None for i in range(nchars): if not cursor.atBlockStart(): cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor) chars = cursor.selectedText() return chars def _autocomplete_quotes(self, key): char = self.QUOTES[key] cursor = self._neditor.textCursor() two = self.get_left_chars(2) three = self.get_left_chars(3) if self._neditor.has_selection(): text = self._neditor.selected_text() cursor.insertText("{0}{1}{0}".format(char, text)) # Keep selection cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor) cursor.movePosition( QTextCursor.Left, QTextCursor.KeepAnchor, len(text)) elif self._neditor.get_right_character() == char: cursor.movePosition( QTextCursor.NextCharacter, QTextCursor.KeepAnchor) cursor.clearSelection() elif three == char * 3: cursor.insertText(char * 3) cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, 3) elif two == char * 2: cursor.insertText(char) else: cursor.insertText(char * 2) cursor.movePosition(QTextCursor.PreviousCharacter) self._neditor.setTextCursor(cursor)
2,080
Python
.py
52
30.153846
77
0.619802
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,537
marker_widget.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/side_area/marker_widget.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import bisect from collections import defaultdict from PyQt5.QtWidgets import QToolTip from PyQt5.QtGui import QFontMetrics from PyQt5.QtGui import QPainter from PyQt5.QtCore import QSize from PyQt5.QtCore import QRect from ninja_ide.gui.ide import IDE from ninja_ide.gui.editor import side_area from ninja_ide.gui.main_panel.marks import Bookmark class MarkerWidget(side_area.SideWidget): def __init__(self): side_area.SideWidget.__init__(self) self.setMouseTracking(True) self.__bookmarks = defaultdict(list) self.__line_hovered = -1 self._bookmark_manager = IDE.get_service("bookmarks") self._bookmark_manager.dataChanged.connect( self._highlight_in_scrollbar) self.sidebarContextMenuRequested.connect(self._show_menu) def _highlight_in_scrollbar(self): self._neditor.scrollbar().remove_marker("bookmarks") for book in self._bookmark_manager.bookmarks(self._neditor.file_path): self._neditor.scrollbar().add_marker( "bookmarks", book.lineno, "#8080ff") def on_register(self): """Highlight markers on scrollbar""" bookmarks = self._bookmark_manager.bookmarks(self._neditor.file_path) for b in bookmarks: self._neditor.scrollbar().add_marker( "bookmarks", b.lineno, "#8080ff") def _show_menu(self, line, menu): # "Set Breakpoint at: {}".format(line + 1)) toggle_bookmark_action = menu.addAction("Toggle Bookmark") toggle_bookmark_action.triggered.connect( lambda: self._toggle_bookmark(line)) def _toggle_bookmark(self, line): filename = self._neditor.file_path if line <= 0 or filename is None: return bookmark = self._bookmark_manager.find_bookmark(filename, line) if bookmark is not None: self._bookmark_manager.remove_bookmark(bookmark) return bookmark = Bookmark(filename, line) self._bookmark_manager.add_bookmark(bookmark) def width(self): return self.sizeHint().width() def next_bookmark(self): bookmarks = self._bookmark_manager.bookmarks(self._neditor.file_path) if bookmarks: bookmarks = [bookmark.lineno for bookmark in bookmarks] current_line, col = self._neditor.cursor_position index = bisect.bisect(bookmarks, current_line) try: line = bookmarks[index] except IndexError: line = bookmarks[0] self._neditor.go_to_line(line, col, center=False) self._neditor.setFocus() def previous_bookmark(self): bookmarks = self._bookmark_manager.bookmarks(self._neditor.file_path) if bookmarks: bookmarks = [bookmark.lineno for bookmark in bookmarks] current_line, col = self._neditor.cursor_position index = bisect.bisect(bookmarks, current_line) line = bookmarks[index - 1] if line == current_line: line = bookmarks[index - 2] self._neditor.go_to_line(line, col, center=False) self._neditor.setFocus() def sizeHint(self): font_metrics = QFontMetrics(self._neditor.font()) size = QSize(font_metrics.height(), font_metrics.height()) return size def mouseMoveEvent(self, event): cursor = self._neditor.cursorForPosition(event.pos()) line = cursor.blockNumber() bookmarks = self._bookmark_manager.bookmarks(self._neditor.file_path) for book in bookmarks: if book.lineno == line and book.note: QToolTip.showText(self.mapToGlobal(event.pos()), book.note) # # Get line number from position # # Add marker # # Remove marker def leaveEvent(self, event): self.__line_hovered = -1 self.repaint() def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) r = self.width() - 10 marks = IDE.get_service("bookmarks").bookmarks(self._neditor.file_path) for top, block_number, block in self._neditor.visible_blocks: for mark in marks: if mark.lineno == block_number: r = QRect(0, top + 3, 16, 16) mark.linetext = block.text() mark.paint_icon(painter, r)
5,199
Python
.py
116
36.431034
79
0.649941
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,538
line_number_widget.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/side_area/line_number_widget.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtGui import ( QColor, QPainter, QPen, QFontMetrics ) from PyQt5.QtCore import Qt, QSize, QRect from ninja_ide.gui.editor import side_area from ninja_ide import resources class LineNumberWidget(side_area.SideWidget): """ Line number area Widget """ LEFT_MARGIN = 5 RIGHT_MARGIN = 3 def __init__(self): side_area.SideWidget.__init__(self) self.__selecting = False self._color_unselected = QColor( resources.COLOR_SCHEME.get('editor.sidebar.foreground')) self._color_selected = QColor( resources.COLOR_SCHEME.get("editor.line")) def sizeHint(self): return QSize(self.__calculate_width(), 0) def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self) width = self.width() - self.RIGHT_MARGIN - self.LEFT_MARGIN height = self._neditor.fontMetrics().height() font = self._neditor.font() font_bold = self._neditor.font() font_bold.setBold(True) pen = QPen(self._color_unselected) painter.setPen(pen) painter.setFont(font) sel_start, sel_end = self._neditor.selection_range() has_sel = sel_start != sel_end current_line, _ = self._neditor.cursor_position # Draw visible blocks for top, line, block in self._neditor.visible_blocks: # Set bold to current line and selected lines if ((has_sel and sel_start <= line <= sel_end) or (not has_sel and current_line == line)): painter.fillRect( QRect(0, top, self.width(), height), self._color_selected) else: painter.setPen(pen) painter.setFont(font) painter.drawText(self.LEFT_MARGIN, top, width, height, Qt.AlignRight, str(line + 1)) def __calculate_width(self): digits = len(str(max(1, self._neditor.blockCount()))) fmetrics_width = QFontMetrics( self._neditor.document().defaultFont()).width('9') return self.LEFT_MARGIN + fmetrics_width * digits + self.RIGHT_MARGIN def mousePressEvent(self, event): self.__selecting = True self.__selection_start_pos = event.pos().y() start = end = self._neditor.line_from_position( self.__selection_start_pos) self.__selection_start_line = start self._neditor.select_lines(start, end) def mouseMoveEvent(self, event): if self.__selecting: end_pos = event.pos().y() end_line = self._neditor.line_from_position(end_pos) if end_line == -1: return self._neditor.select_lines(self.__selection_start_line, end_line) def wheelEvent(self, event): self._neditor.wheelEvent(event)
3,562
Python
.py
87
33.137931
78
0.635681
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,539
text_change_widget.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/side_area/text_change_widget.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import difflib from PyQt5.QtGui import ( QPainter, QColor ) from PyQt5.QtCore import ( pyqtSlot, QSize, QTimer ) from ninja_ide.gui.editor.side_area import SideWidget from ninja_ide import resources class TextChangeWidget(SideWidget): @property def unsaved_color(self): return self.__unsaved_color @unsaved_color.setter def unsaved_color(self, color): if isinstance(color, str): color = QColor(color) self.__unsaved_color = color @property def saved_color(self): return self.__saved_color @saved_color.setter def saved_color(self, color): if isinstance(color, str): color = QColor(color) self.__saved_color = color @property def delay(self): return self.__delay @delay.setter def delay(self, ms): if ms != self.__delay: self.__delay = ms self._timer.setInterval(self.__delay) def __init__(self): SideWidget.__init__(self) self.__unsaved_markers = [] self.__saved_markers = [] self.__saved = False # Default properties self.__unsaved_color = QColor( resources.COLOR_SCHEME.get("editor.markarea.modified")) self.__saved_color = QColor( resources.COLOR_SCHEME.get("editor.markarea.saved")) self.__delay = 300 # Delay Timer self._timer = QTimer(self) self._timer.setInterval(self.__delay) self._timer.setSingleShot(True) self._timer.timeout.connect(self.__on_text_changed) def register(self, neditor): SideWidget.register(self, neditor) self.__text = neditor.toPlainText() self.__last_saved_text = neditor.toPlainText() # Connect textChanged signal to the timer # the __on_text_chaned slot is executed each '__delay' milliseconds neditor.textChanged.connect(self._timer.start) neditor.updateRequest.connect(self.update) neditor.neditable.fileSaved.connect(self.__on_file_saved) @pyqtSlot() def __on_file_saved(self): self.__saved = True self.__last_saved_text = self._neditor.toPlainText() self.__saved_markers += list(self.__unsaved_markers) @pyqtSlot() def __on_text_changed(self): if self.__saved: self.__saved = False return self.__unsaved_markers.clear() old_text = self.__last_saved_text actual_text = self._neditor.toPlainText() matcher = difflib.SequenceMatcher(None, old_text.splitlines(), actual_text.splitlines()) for tag, _, _, j1, j2 in matcher.get_opcodes(): if tag in ('insert', 'replace'): for lineno in range(j1, j2): if lineno not in self.__unsaved_markers: self.__unsaved_markers.append(lineno) if lineno in self.__saved_markers: self.__saved_markers.remove(lineno) def sizeHint(self): return QSize(2, 0) def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self) height = self._neditor.fontMetrics().height() width = self.sizeHint().width() for top, block_number, _ in self._neditor.visible_blocks: for lineno in self.__unsaved_markers: if block_number == lineno: painter.fillRect(0, top, width, height + 1, self.__unsaved_color) for lineno in self.__saved_markers: if block_number == lineno: painter.fillRect(0, top, width, height + 1, self.__saved_color)
4,519
Python
.py
117
29.649573
75
0.607021
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,540
manager.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/side_area/manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from collections import OrderedDict class SideWidgetManager(object): """Manages side widgets""" def __init__(self, neditor): self.__widgets = OrderedDict() self._neditor = neditor self.__width = 0 neditor.blockCountChanged.connect(self.update_viewport) neditor.updateRequest.connect(self._update) def add(self, Widget): """Installs a widget on left area of the editor""" widget_obj = Widget() self.__widgets[widget_obj.object_name] = widget_obj widget_obj.register(self._neditor) self.update_viewport() return widget_obj def get(self, object_name): """Returns a side widget instance""" return self.__widgets.get(object_name) def remove(self, object_name): widget = self.get(object_name) del self.__widgets[object_name] widget.setParent(None) widget.deleteLater() def _update(self): for widget in self: widget.update() def __iter__(self): return iter(self.__widgets.values()) def __len__(self): return len(self.__widgets.values()) def update_viewport(self): """Recalculates geometry for all the side widgets""" total_width = 0 for widget in self: if not widget.isVisible(): continue total_width += widget.sizeHint().width() self._neditor.setViewportMargins(total_width, 0, 0, 0) def resize(self): """Resize all side widgets""" cr = self._neditor.contentsRect() current_x = cr.left() top = cr.top() height = cr.height() left = 0 for widget in self: size_hint = widget.sizeHint() width = size_hint.width() widget.setGeometry(current_x + left, top, width, height) left += size_hint.width() self.__width = left @property def width(self): return self.__width
2,675
Python
.py
71
30.619718
70
0.640758
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,541
__init__.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/side_area/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QMenu from PyQt5.QtGui import QColor from PyQt5.QtGui import QPainter from PyQt5.QtCore import pyqtSignal from PyQt5.QtCore import QPoint from ninja_ide import resources class SideWidget(QWidget): """ Base class for editor side widgets """ sidebarContextMenuRequested = pyqtSignal(int, QMenu) def __init__(self): QWidget.__init__(self) self.object_name = self.__class__.__name__ self.order = -1 def register(self, neditor): """Set the NEditor instance as the parent widget When override this method, call super! """ self.setParent(neditor) self._neditor = neditor self.on_register() def on_register(self): pass def paintEvent(self, event): if self.isVisible(): background_color = QColor( resources.COLOR_SCHEME.get("editor.sidebar.background")) # resources.get_color('SidebarBackground')) painter = QPainter(self) painter.fillRect(event.rect(), background_color) def setVisible(self, value): """Show/Hide the widget""" QWidget.setVisible(self, value) self._neditor.side_widgets.update_viewport() def contextMenuEvent(self, event): cursor = self._neditor.cursorForPosition(QPoint(0, event.pos().y())) menu = QMenu(self) self.sidebarContextMenuRequested.emit(cursor.blockNumber(), menu) if not menu.isEmpty(): menu.exec_(event.globalPos()) menu.deleteLater() event.accept()
2,318
Python
.py
60
32.8
76
0.688057
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,542
code_folding.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/side_area/code_folding.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import re from PyQt5.QtWidgets import QStyleOptionViewItem from PyQt5.QtWidgets import QStyle from PyQt5.QtGui import QPainter from PyQt5.QtGui import QTextBlock from PyQt5.QtGui import QColor from PyQt5.QtCore import QSize from PyQt5.QtCore import QRect from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from ninja_ide import resources from ninja_ide.gui.editor import side_area from ninja_ide.tools.utils import get_inverted_color class BaseCodeFolding(object): def foldable_blocks(self): """Detects the blocks that are going to be folded""" return [] def is_foldable(self, text_or_block): """Returns True if the text if foldable. False otherwise""" raise NotImplementedError def block_indentation(self, block): """Return the indentation level of block""" block_text = block.text() return len(block_text) - len(block_text.strip()) class IndentationFolding(BaseCodeFolding): """Base blass for folding by indentation""" def foldable_blocks(self, block): block_indentation = self.block_indentation(block) block = block.next() last_block = None sub_blocks = [] append = sub_blocks.append while block and block.isValid(): text_stripped = block.text().strip() text_indent = self.block_indentation(block) if text_indent <= block_indentation: if text_stripped: break if text_stripped: last_block = block append(block) block = block.next() for block in sub_blocks: yield block if block == last_block: break class CharBaseFolding(BaseCodeFolding): @property def open_char(self): raise NotImplementedError @property def close_char(self): raise NotImplementedError def foldable_blocks(self, block): pass class PythonCodeFolding(IndentationFolding): pattern = re.compile( "\\s*(def|class|with|if|else|elif|for|while|async).*:") def is_foldable(self, text_or_block): if isinstance(text_or_block, QTextBlock): text_or_block = text_or_block.text() return self.pattern.match(text_or_block) IMPLEMENTATIONS = { "python": PythonCodeFolding() } class CodeFoldingWidget(side_area.SideWidget): """Code folding widget""" def __init__(self): super().__init__() self.code_folding = None self.setMouseTracking(True) self.__mouse_over = None self.__current_line_number = -1 self.__timer = QTimer(self) self.__timer.setSingleShot(True) self.__timer.setInterval(100) self.__timer.timeout.connect(self.update) reverse_color = get_inverted_color( resources.COLOR_SCHEME.get("editor.background")) self.__line_fold_color = QColor(reverse_color) def register(self, neditor): self.code_folding = IMPLEMENTATIONS.get(neditor.neditable.language()) if self.code_folding is None: neditor.side_widgets.remove(self.object_name) return super().register(neditor) self.user_data = neditor.user_data neditor.painted.connect(self.__draw_collapsed_line) def __draw_collapsed_line(self): viewport = self._neditor.viewport() painter = QPainter(viewport) painter.setPen(self.__line_fold_color) for top, _, block in self._neditor.visible_blocks: if not block.next().isVisible(): layout = block.layout() line = layout.lineAt(layout.lineCount() - 1) offset = self._neditor.contentOffset() line_rect = line.naturalTextRect().translated(offset.x(), top) bottom = line_rect.bottom() painter.drawLine( line_rect.x(), bottom, line_rect.width(), bottom) def __block_under_mouse(self, event): """Returns QTextBlock under mouse""" posy = event.pos().y() height = self._neditor.fontMetrics().height() for top, _, block in self._neditor.visible_blocks: if posy >= top and posy <= top + height: return block def is_foldable_block(self, block): return self.code_folding.is_foldable(block) or \ self.user_data(block).get("folded") def sizeHint(self): fm = self._neditor.fontMetrics() return QSize(fm.height(), fm.height()) def leaveEvent(self, event): self.__mouse_over = None self.update() def mouseMoveEvent(self, event): block = self.__block_under_mouse(event) if block is None: return self.__mouse_over = block if self.code_folding.is_foldable(block): if self.__current_line_number == block.blockNumber(): return self.setCursor(Qt.PointingHandCursor) self.__timer.start() else: self.setCursor(Qt.ArrowCursor) self.__timer.stop() self.__current_line_number = block.blockNumber() self.update() def mousePressEvent(self, event): block = self.__block_under_mouse(event) if block is not None: if self.user_data(block).get("folded", default=False): self.unfold(block) else: self.fold(block) def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self) for top, _, block in self._neditor.visible_blocks: if not self.is_foldable_block(block): continue branch_rect = QRect(0, top, self.sizeHint().width(), self.sizeHint().height()) opt = QStyleOptionViewItem() opt.rect = branch_rect opt.state = (QStyle.State_Active | QStyle.State_Item | QStyle.State_Children) folded = self.user_data(block).get("folded", default=False) if not folded: opt.state |= QStyle.State_Open # Draw item self.style().drawPrimitive(QStyle.PE_IndicatorBranch, opt, painter, self) # Draw folded region background if block == self.__mouse_over and not self.__timer.isActive(): fm_height = self._neditor.fontMetrics().height() rect_height = 0 color = self.palette().highlight().color() color.setAlpha(100) if not folded: foldable_blocks = self.code_folding.foldable_blocks(block) rect_height = (len(list(foldable_blocks))) * fm_height painter.fillRect(QRect( 0, top, self.sizeHint().width(), rect_height + fm_height), color) def fold(self, block): if not self.code_folding.is_foldable(block): return line, _ = self._neditor.cursor_position contains_cursor = False for _block in self.code_folding.foldable_blocks(block): if _block.blockNumber() == line: contains_cursor = True _block.setVisible(False) self.user_data(block)["folded"] = True self._neditor.document().markContentsDirty( block.position(), _block.position()) # If the cursor is inside a block to be hidden, # let's move the cursor to the end of the start block if contains_cursor: cursor = self._neditor.textCursor() cursor.setPosition(block.position()) cursor.movePosition(cursor.EndOfBlock) self._neditor.setTextCursor(cursor) self._neditor.repaint() def unfold(self, block): for _block in self.code_folding.foldable_blocks(block): _block.setVisible(True) self.user_data(block)["folded"] = False self._neditor.document().markContentsDirty( block.position(), _block.position()) self._neditor.repaint()
8,851
Python
.py
213
31.807512
78
0.614884
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,543
lint_area.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/side_area/lint_area.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import QToolTip from PyQt5.QtGui import ( QPainter, QColor ) from ninja_ide.gui.editor import side_area class LintArea(side_area.SideArea): """Shows markes with messages collected by checkers""" def __init__(self, editor): super().__init__(editor) self.setMouseTracking(True) self._editor = editor self.__checkers = None self._editor.highlight_checker_updated.connect(self.__update) self.__messages = {} def __update(self, checkers): self.__checkers = checkers def mouseMoveEvent(self, event): if not self.__checkers: return line = self._editor.line_from_position(event.pos().y()) for checker in self.__checkers: obj, _, _ = checker message = obj.message(line) if message is not None: # Formatting text text = "<div style='color: green'>Lint</div><hr>%s" % message QToolTip.showText(self.mapToGlobal(event.pos()), text, self) def width(self): return 15 def paintEvent(self, event): super().paintEvent(event) if self.__checkers is None: return painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) for checker in self.__checkers: checker_obj, color, _ = checker lines = checker_obj.checks.keys() painter.setPen(QColor(color)) painter.setBrush(QColor(color)) for top, block_number, _ in self._editor.visible_blocks: for marker in lines: if marker == block_number: r = self.width() - 9 painter.drawEllipse(5, top + 10, r, r) """ """ """ def paintEvent(self, event): super().paintEvent(event) if not self.__checks: return painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setPen(QColor("#ffd66c")) painter.setBrush(QColor("#ffd66c")) if self.__checks is not None: lines = self.__checks.keys() for top, block_number, _ in self._editor.visible_blocks: for marker in lines: if marker == block_number: r = self.width() - 9 painter.drawEllipse(5, top + 10, r, r) """
3,145
Python
.py
81
30.197531
77
0.607728
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,544
python_indenter.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/indenter/python_indenter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. # Based on https://github.com/DSpeckhals/python-indent from ninja_ide.gui.editor.indenter import base from ninja_ide.tools.logger import NinjaLogger # Logger logger = NinjaLogger(__name__) class PythonIndenter(base.BaseIndenter): """PEP8 indenter for Python""" LANG = 'python' def _compute_indent(self, cursor): # At this point, the new block has added block = cursor.block() line, _ = self._neditor.cursor_position # Source code at current position text = self._neditor.text[:cursor.position()] current_indent = self.block_indent(block.previous()) # Parse text results = self.__parse_text(text) # Get result of parsed text bracket_stack, last_closed_line, should_hang, last_colon_line = results logger.debug(results) if should_hang: cursor = self._neditor.textCursor() text = cursor.block().text() next_char = "" if (len(text) > 0): next_char = text[0] if len(next_char) > 0 and next_char in "}])": cursor.insertBlock() cursor.insertText(current_indent) cursor.movePosition(cursor.Up) self._neditor.setTextCursor(cursor) else: cursor.insertText(current_indent) cursor.insertText(current_indent + self.text()) return if not bracket_stack: if last_closed_line: if last_closed_line[1] == line - 1: indent_level = self.line_indent(last_closed_line[0]) if last_colon_line == line - 1: indent_level += self.width return indent_level * " " else: text_stripped = block.previous().text().strip() if text_stripped in ("break", "continue", "raise", "pass", "return") or \ text_stripped.startswith("raise ") or \ text_stripped.startswith("return "): return " " * (len(current_indent) - self.width) else: text_stripped = block.previous().text().strip() if text_stripped in ("break", "continue", "raise", "pass", "return") or \ text_stripped.startswith("raise ") or \ text_stripped.startswith("return "): return " " * (len(current_indent) - self.width) last_previous_char = block.previous().text()[-1] if last_previous_char == ":": return self.text() + current_indent return self.block_indent(block.previous()) last_open_bracket = bracket_stack.pop() have_closed_bracket = len(last_closed_line) > 0 just_opened_bracket = last_open_bracket[0] == line - 1 just_closed_bracket = have_closed_bracket and \ last_closed_line[1] == line - 1 v = have_closed_bracket and last_closed_line[0] > last_open_bracket[0] if not just_opened_bracket and not just_closed_bracket: return current_indent elif just_closed_bracket and v: previous_indent = self.line_indent(last_closed_line[0]) indent_col = previous_indent else: indent_col = last_open_bracket[1] + 1 return indent_col * " " def __parse_text(self, text): # [line, column] pairs describing where open brackets are open_bracket = [] # Describing the lines where the last bracket to be closed was # opened and closed last_close_line = [] # The last line a def/for/if/elif/else/try/except block started last_colon_line = None # Indicating wheter or not a hanging indent is needed should_hang = False for lineno, line in enumerate(text.splitlines()): last_last_colon_line = last_colon_line for col, char in enumerate(line): if char in '{[(': open_bracket.append([lineno, col]) should_hang = True else: should_hang = False last_colon_line = last_last_colon_line if char == ':': last_colon_line = lineno elif char in '}])' and open_bracket: opened_row = open_bracket.pop()[0] if lineno != opened_row: last_close_line = [opened_row, lineno] return (open_bracket, last_close_line, should_hang, last_colon_line)
5,437
Python
.py
116
34.551724
79
0.567848
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,545
__init__.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/indenter/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from ninja_ide.gui.editor.indenter import ( python_indenter, html_indenter, base ) INDENTER_MAP = { 'python': python_indenter.PythonIndenter, 'html': html_indenter.HtmlIndenter } def load_indenter(editor, lang=None): indenter_obj = INDENTER_MAP.get(lang, base.BasicIndenter) return indenter_obj(editor)
1,027
Python
.py
28
34.535714
70
0.753769
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,546
base_indenter.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/indenter/base_indenter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtGui import QTextCursor class Indenter(object): WIDTH = 4 USE_TABS = False def __init__(self, neditor): self._neditor = neditor self.width = self.WIDTH self.use_tabs = self.USE_TABS def text(self) -> str: """Returns indent text as \t or string of spaces""" if self.USE_TABS: return '\t' return ' ' * self.WIDTH def auto_indent(self): raise NotImplementedError def indent(self): cursor = self._neditor.textCursor() if self.USE_TABS: to_insert = self.text() else: text = cursor.block().text() text_before_cursor = text[:cursor.positionInBlock()] to_insert = self.WIDTH - (len(text_before_cursor)) % self.WIDTH to_insert *= " " cursor.insertText(to_insert) def indent_selection(self): def indent_block(block): cursor = QTextCursor(block) indentation = self.__block_indentation(block) cursor.setPosition(block.position() + len(indentation)) cursor.insertText(self.text()) cursor = self._neditor.textCursor() start_block = self._neditor.document().findBlock( cursor.selectionStart()) end_block = self._neditor.document().findBlock( cursor.selectionEnd()) with self._neditor: if start_block != end_block: stop_block = end_block.next() # Indent multiple lines block = start_block while block != stop_block: indent_block(block) block = block.next() new_cursor = QTextCursor(start_block) new_cursor.setPosition( end_block.position() + len(end_block.text()), QTextCursor.KeepAnchor) self._neditor.setTextCursor(new_cursor) else: # Indent one line indent_block(start_block) @staticmethod def __block_indentation(block): """Returns indentation level of block""" text = block.text() return text[:len(text) - len(text.lstrip())] def unindent(self): cursor = self._neditor.textCursor() start_block = self._neditor.document().findBlock( cursor.selectionStart()) end_block = self._neditor.document().findBlock( cursor.selectionEnd()) position = cursor.position() if position == 0: return if start_block != end_block: # Unindent multiple lines block = start_block stop_block = end_block.next() while block != stop_block: indentation = self.__block_indentation(block) if indentation.endswith(self.text()): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(indentation)) cursor.setPosition(cursor.position() - self.WIDTH, QTextCursor.KeepAnchor) cursor.removeSelectedText() block = block.next() else: # Unindent one line indentation = self.__block_indentation(start_block) cursor = QTextCursor(start_block) cursor.setPosition(start_block.position() + len(indentation)) cursor.setPosition(cursor.position() - self.WIDTH, QTextCursor.KeepAnchor) cursor.removeSelectedText() class BasicIndenter(Indenter): """Basic indenter""" def __init__(self, neditor): super().__init__(neditor) def auto_indent(self): cursor = self._neditor.textCursor() previous_block = cursor.block().previous() text = previous_block.text() indent = len(text) - len(text.lstrip()) cursor.insertText(" " * indent)
4,659
Python
.py
113
30.734513
75
0.591783
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,547
base.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/indenter/base.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtGui import QTextCursor from ninja_ide.core import settings class BaseIndenter(object): def __init__(self, neditor): self._neditor = neditor # Editor ref self.width = settings.INDENT self.use_tabs = settings.USE_TABS def text(self): """Get indent text as \t or string of spaces""" text = " " * self.width if self.use_tabs: text = "\t" return text def indent_block(self, cursor): """Indent block after enter pressed""" at_start_of_line = cursor.positionInBlock() == 0 with self._neditor: cursor.insertBlock() if not at_start_of_line: indent = self._compute_indent(cursor) if indent is not None: cursor.insertText(indent) return True return False self._neditor.ensureCursorVisible() def block_indent(self, block): block_text = block.text() space_at_start_len = len(block_text) - len(block_text.lstrip()) return block_text[:space_at_start_len] def indent(self): """Indent a single line after tab pressed""" cursor = self._neditor.textCursor() if self.use_tabs: to_insert = self.text() else: text = cursor.block().text() text_before_cursor = text[:cursor.positionInBlock()] to_insert = self.width - (len(text_before_cursor)) % self.width to_insert *= " " cursor.insertText(to_insert) def indent_selection(self): """Indent selection after tab pressed""" def indent_block(block): cursor = QTextCursor(block) indentation = self.block_indent(block) cursor.setPosition(block.position() + len(indentation)) cursor.insertText(self.text()) cursor = self._neditor.textCursor() start_block = self._neditor.document().findBlock( cursor.selectionStart()) end_block = self._neditor.document().findBlock( cursor.selectionEnd()) with self._neditor: if start_block != end_block: stop_block = end_block.next() # Indent multiple lines block = start_block while block != stop_block: indent_block(block) block = block.next() new_cursor = QTextCursor(start_block) new_cursor.setPosition( end_block.position() + len(end_block.text()), QTextCursor.KeepAnchor) self._neditor.setTextCursor(new_cursor) else: # Indent one line indent_block(start_block) def line_indent(self, line): """Returns the indentation level of `line`""" return self._neditor.line_indent(line) def _compute_indent(self, cursor): raise NotImplementedError class BasicIndenter(BaseIndenter): """Basic indenter""" def _compute_indent(self, cursor): # At this point, enter was pressed, so the block should be previous return self.block_indent(cursor.block().previous())
3,916
Python
.py
94
32.12766
75
0.611987
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,548
html_indenter.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/indenter/html_indenter.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import re from ninja_ide.gui.editor.indenter import base from ninja_ide.tools.logger import NinjaLogger from ninja_ide.core.settings import INDENT # Logger logger = NinjaLogger(__name__) class HtmlIndenter(base.BaseIndenter): """indenter for Html5""" LANG = 'html' hang = False exempted_set = ('<!doctype html>', '<html>', '<!doctype>') def _compute_indent(self, cursor): block = cursor.block() line, _ = self._neditor.cursor_position # Source code at current position text = self._neditor.text[:cursor.position()] current_indent = self.block_indent(block.previous()) indent_level = len(current_indent) # get last line text_splits = text.split('\n') last_line = text_splits[-2] self._parse_text(last_line) # if indent depth should increase if self.hang: indent_level += self.width indent = ' ' * indent_level # reset this so unindent and indent using tab will work properly self.width = INDENT return indent else: indent = ' ' * self.width # reset this so unindent and indent using tab will work properly self.width = INDENT return indent def _parse_text(self, last_line): # if it is a closing tag or a php if re.findall('[/|?]', last_line): self.hang = False else: # If it's not a closing tag or an exempted element. # this is normacy self.hang = True # if it is an exempted ele for ele in self.exempted_set: if re.findall(last_line, ele, 2): self.width = 0 self.hang = False
2,448
Python
.py
63
31.84127
76
0.639427
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,549
all_lexers.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/extended_lexers/all_lexers.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. # based on Python Syntax highlighting from: # http://diotavelli.net/PyQtWiki/Python%20syntax%20highlighting from __future__ import absolute_import import re from PyQt4.QtGui import QColor from ninja_ide import resources from ninja_ide.core import settings from PyQt4.Qsci import (QsciLexerBash, QsciLexerBatch, QsciLexerCMake, QsciLexerCPP, QsciLexerCSS, QsciLexerCSharp, QsciLexerD, QsciLexerDiff, QsciLexerFortran, QsciLexerFortran77, QsciLexerHTML, QsciLexerIDL, QsciLexerJava, QsciLexerJavaScript, QsciLexerLua, QsciLexerMakefile, QsciLexerMatlab, QsciLexerOctave, QsciLexerPOV, QsciLexerPascal, QsciLexerPerl, QsciLexerPostScript, QsciLexerProperties, QsciLexerPython, QsciLexerRuby, QsciLexerSQL, QsciLexerSpice, QsciLexerTCL, QsciLexerTeX, QsciLexerVHDL, QsciLexerVerilog, QsciLexerXML, QsciLexerYAML) from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.gui.editor.extended_lexers.all_lexers') pattern = re.compile(r'^([A-Z]).+$') class BaseNinjaLexer(object): """WARNING: Only use this as the first part of a Lexer mixin""" def __init__(self, *args, **kwargs): self._settings_colored = None super(BaseNinjaLexer, self).__init__(*args, **kwargs) def initialize_color_scheme(self): self.scheme = {} self.background_color = QColor(resources.COLOR_SCHEME["EditorBackground"]) detected_values = [] identifiers = [word for word in dir(self) if pattern.match(word)] logger.debug(identifiers) default_color = resources.COLOR_SCHEME["Default"] for key in identifiers: identifier = getattr(self, key) if identifier not in detected_values: color = resources.COLOR_SCHEME.get(key, default_color) if color != default_color: detected_values.append(identifier) self.scheme[identifier] = QColor(color) def defaultColor(self, style): if self._settings_colored is not None: default_color = QColor(resources.COLOR_SCHEME["Default"]) return self.scheme.get(style, default_color) parent_lexer = None not_lexers = [self.__class__.__name__, "BaseNinjaLexer"] for each_parent in self.__class__.__mro__: if each_parent.__name__ not in not_lexers: parent_lexer = each_parent break # FIXME This reverses colors while we find a way to do themes. c = parent_lexer.defaultColor(self, style).name() logger.debug(c) reverse_color = "#" + "".join((hex(255 - int(x, 16))) [2:].zfill(2) for x in (c[1:3], c[3:5], c[5:7])) return QColor(reverse_color) def defaultFont(self, style): return settings.FONT def defaultPaper(self, style): return self.background_color class PythonLexer(BaseNinjaLexer, QsciLexerPython): def __init__(self, *args, **kwargs): super(PythonLexer, self).__init__(*args, **kwargs) self._settings_colored = 1 self.setFoldComments(True) self.setFoldQuotes(True) def keywords(self, keyset): if keyset == 2: return ('self super all any basestring bin bool bytearray callable ' 'chr abs classmethod cmp compile complex delattr dict dir ' 'divmod enumerate eval execfile file filter float format ' 'frozenset getattr globals hasattr hash help hex id input ' 'int isinstance issubclass iter len list locals long map ' 'max memoryview min next object oct open ord pow property ' 'range raw_input reduce reload repr reversed round set ' 'setattr slice sorted staticmethod str sum tuple type ' 'unichr unicode vars xrange zip apply buffer coerce intern ' 'True False') return super(PythonLexer, self).keywords(keyset) try: from PyQt4.Qsci import QsciLexerAVS class AVSLexer(BaseNinjaLexer, QsciLexerAVS): def __init__(self, *args, **kwargs): self._settings_colored = None super(AVSLexer, self).__init__(*args, **kwargs) except ImportError: AVSLexer = None class BashLexer (BaseNinjaLexer, QsciLexerBash): def __init__(self, *args, **kwargs): self._settings_colored = None super(BashLexer, self).__init__(*args, **kwargs) class BatchLexer (BaseNinjaLexer, QsciLexerBatch): def __init__(self, *args, **kwargs): self._settings_colored = None super(BatchLexer, self).__init__(*args, **kwargs) class CMakeLexer (BaseNinjaLexer, QsciLexerCMake): def __init__(self, *args, **kwargs): self._settings_colored = None super(CMakeLexer, self).__init__(*args, **kwargs) class CPPLexer (BaseNinjaLexer, QsciLexerCPP): def __init__(self, *args, **kwargs): self._settings_colored = None super(CPPLexer, self).__init__(*args, **kwargs) class CSSLexer (BaseNinjaLexer, QsciLexerCSS): def __init__(self, *args, **kwargs): self._settings_colored = None super(CSSLexer, self).__init__(*args, **kwargs) class CSharpLexer (BaseNinjaLexer, QsciLexerCSharp): def __init__(self, *args, **kwargs): self._settings_colored = None super(CSharpLexer, self).__init__(*args, **kwargs) try: from PyQt4.Qsci import QsciLexerCoffeeScript class CoffeeScriptLexer (BaseNinjaLexer, QsciLexerCoffeeScript): def __init__(self, *args, **kwargs): self._settings_colored = None super(CoffeeScriptLexer, self).__init__(*args, **kwargs) except ImportError: CoffeeScriptLexer = None class DLexer (BaseNinjaLexer, QsciLexerD): def __init__(self, *args, **kwargs): self._settings_colored = None super(DLexer, self).__init__(*args, **kwargs) class DiffLexer (BaseNinjaLexer, QsciLexerDiff): def __init__(self, *args, **kwargs): self._settings_colored = None super(DiffLexer, self).__init__(*args, **kwargs) class FortranLexer (BaseNinjaLexer, QsciLexerFortran): def __init__(self, *args, **kwargs): self._settings_colored = None super(FortranLexer, self).__init__(*args, **kwargs) class Fortran77Lexer (BaseNinjaLexer, QsciLexerFortran77): def __init__(self, *args, **kwargs): self._settings_colored = None super(Fortran77Lexer, self).__init__(*args, **kwargs) class HTMLLexer (BaseNinjaLexer, QsciLexerHTML): def __init__(self, *args, **kwargs): self._settings_colored = None super(HTMLLexer, self).__init__(*args, **kwargs) class IDLLexer (BaseNinjaLexer, QsciLexerIDL): def __init__(self, *args, **kwargs): self._settings_colored = None super(IDLLexer, self).__init__(*args, **kwargs) class JavaLexer (BaseNinjaLexer, QsciLexerJava): def __init__(self, *args, **kwargs): self._settings_colored = None super(JavaLexer, self).__init__(*args, **kwargs) class JavaScriptLexer (BaseNinjaLexer, QsciLexerJavaScript): def __init__(self, *args, **kwargs): self._settings_colored = None super(JavaScriptLexer, self).__init__(*args, **kwargs) class LuaLexer (BaseNinjaLexer, QsciLexerLua): def __init__(self, *args, **kwargs): self._settings_colored = None super(LuaLexer, self).__init__(*args, **kwargs) class MakefileLexer (BaseNinjaLexer, QsciLexerMakefile): def __init__(self, *args, **kwargs): self._settings_colored = None super(MakefileLexer, self).__init__(*args, **kwargs) class MatlabLexer (BaseNinjaLexer, QsciLexerMatlab): def __init__(self, *args, **kwargs): self._settings_colored = None super(MatlabLexer, self).__init__(*args, **kwargs) class OctaveLexer (BaseNinjaLexer, QsciLexerOctave): def __init__(self, *args, **kwargs): self._settings_colored = None super(OctaveLexer, self).__init__(*args, **kwargs) try: from PyQt4.Qsci import QsciLexerPO class POLexer (BaseNinjaLexer, QsciLexerPO): def __init__(self, *args, **kwargs): self._settings_colored = None super(POLexer, self).__init__(*args, **kwargs) except ImportError: POLexer = None class POVLexer (BaseNinjaLexer, QsciLexerPOV): def __init__(self, *args, **kwargs): self._settings_colored = None super(POVLexer, self).__init__(*args, **kwargs) class PascalLexer (BaseNinjaLexer, QsciLexerPascal): def __init__(self, *args, **kwargs): self._settings_colored = None super(PascalLexer, self).__init__(*args, **kwargs) class PerlLexer (BaseNinjaLexer, QsciLexerPerl): def __init__(self, *args, **kwargs): self._settings_colored = None super(PerlLexer, self).__init__(*args, **kwargs) class PostScriptLexer (BaseNinjaLexer, QsciLexerPostScript): def __init__(self, *args, **kwargs): self._settings_colored = None super(PostScriptLexer, self).__init__(*args, **kwargs) class PropertiesLexer (BaseNinjaLexer, QsciLexerProperties): def __init__(self, *args, **kwargs): self._settings_colored = None super(PropertiesLexer, self).__init__(*args, **kwargs) class RubyLexer (BaseNinjaLexer, QsciLexerRuby): def __init__(self, *args, **kwargs): self._settings_colored = None super(RubyLexer, self).__init__(*args, **kwargs) class SQLLexer (BaseNinjaLexer, QsciLexerSQL): def __init__(self, *args, **kwargs): self._settings_colored = None super(SQLLexer, self).__init__(*args, **kwargs) class SpiceLexer (BaseNinjaLexer, QsciLexerSpice): def __init__(self, *args, **kwargs): self._settings_colored = None super(SpiceLexer, self).__init__(*args, **kwargs) class TCLLexer (BaseNinjaLexer, QsciLexerTCL): def __init__(self, *args, **kwargs): self._settings_colored = None super(TCLLexer, self).__init__(*args, **kwargs) class TeXLexer (BaseNinjaLexer, QsciLexerTeX): def __init__(self, *args, **kwargs): self._settings_colored = None super(TeXLexer, self).__init__(*args, **kwargs) class VHDLLexer (BaseNinjaLexer, QsciLexerVHDL): def __init__(self, *args, **kwargs): self._settings_colored = None super(VHDLLexer, self).__init__(*args, **kwargs) class VerilogLexer (BaseNinjaLexer, QsciLexerVerilog): def __init__(self, *args, **kwargs): self._settings_colored = None super(VerilogLexer, self).__init__(*args, **kwargs) class XMLLexer (BaseNinjaLexer, QsciLexerXML): def __init__(self, *args, **kwargs): self._settings_colored = None super(XMLLexer, self).__init__(*args, **kwargs) class YAMLLexer (BaseNinjaLexer, QsciLexerYAML): def __init__(self, *args, **kwargs): self._settings_colored = None super(YAMLLexer, self).__init__(*args, **kwargs)
11,937
Python
.py
249
39.7751
86
0.647576
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,550
python.py
ninja-ide_ninja-ide/ninja_ide/gui/editor/syntaxes/python.py
import builtins # FIXME: match complex number kwlist = ['and', 'as', 'assert', 'break', 'await', 'continue', 'del', 'def', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield', 'async'] syntax = { 'formats': { 'builtin': '%(syntax_builtin)s', 'comment': '%(syntax_comment)s', 'decorator': '%(syntax_decorator)s', 'keyword': '%(syntax_keyword)s', 'number': '%(syntax_number)s', 'hexnumber': '%(syntax_hexnumber)s', 'binnumber': '%(syntax_binnumber)s', 'octnumber': '%(syntax_octnumber)s', 'definition': '%(syntax_definition)s', 'proper_object': '%(syntax_proper_object)s', 'string': '%(syntax_string)s', 'rstring': '%(syntax_rstring)s', 'docstring': '%(syntax_docstring)s', 'operators': '%(syntax_operators)s', 'definitionname': '%(syntax_definitionname)s', 'function': '%(syntax_function)s', 'constant': '%(syntax_constant)s' }, 'partitions': [ ('comment', "#", '\n'), ("docstring", "[buBU]?'''", "'''", True), ("rstring", "[rR]'''", "'''", True), ("rstring", '[rR]"""', '"""', True), ("string", "[buBU]?'", "'"), ("docstring", '[buBU]?"""', '"""', True), ("string", '[buBU]?"', '"'), ], 'scanner': { # FIXME: Underscores in numeric literals None: [ ('constant', "\\b_*[A-Z][_\\d]*[A-Z][A-Z\\d]*(_\\w*)?\\b"), ('function', "\\w+(?=\\ *?\\()"), ('hexnumber', '0[xX]\\d+'), ('octnumber', '0[oO](_?[0-7])+'), ('binnumber', '0[bB][01]+'), ('number', '(?<!\\w)(\\.?)(_?\\d+)+(\\.\\d*)?[lL]?'), ('decorator', "@\\w+(\\.\\w+)?"), ('definition', ["(?<=def)\\ +?\\w+(?=\\ *?\\()", "(?<=class)\\ +?\\w+(?=\\ *?\\()"]), ('definitionname', 'class|def', '(^|[\x08\\W])', '[\x08\\W]'), ('proper_object', ['self'], '(^|[^\\.\\w])??(?<!\\w|\\.)', '[\\x08\\W]+?'), ('keyword', kwlist, '(^|[\x08\\W])', '[\x08\\W]'), ('builtin', dir(builtins), '(^|[^\\.\\w])??(?<!\\w|\\.)', '[\x08\\W]'), ('operators', ['\\+', '\\=', '\\-', '\\<', '\\>', '\\!=']) ] } }
2,475
Python
.py
60
31.783333
77
0.399254
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,551
from_import_dialog.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/from_import_dialog.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from sys import builtin_module_names from pkgutil import iter_modules from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QGridLayout from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QCompleter from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QSpinBox from PyQt5.QtCore import Qt from ninja_ide import translations from ninja_ide.tools import introspection LIST_OF_PY_CHECKERS_COMMENTS = ( 'flake8:noqa', 'isort:skip', 'isort:skip_file', 'lint:disable', 'lint:enable', 'lint:ok', 'noqa', 'pyflakes:ignore', 'pylint:disable', 'pylint:enable', 'pragma: no cover', 'silence pyflakes') def simple_python_completion(): """Return tuple of strings containing Python words for simple completion""" python_completion = [] python_completion += builtin_module_names python_completion += tuple(dir(__builtins__)) python_completion += [module_name[1] for module_name in iter_modules()] python_completion += tuple(__builtins__.keys()) python_completion = tuple(sorted(set(python_completion))) return python_completion class FromImportDialog(QDialog): """From Import dialog class.""" def __init__(self, editorWidget, parent=None): QDialog.__init__(self, parent, Qt.Dialog | Qt.FramelessWindowHint) self.setWindowTitle('from ... import ...') self._editorWidget = editorWidget source = self._editorWidget.text source = source.encode(self._editorWidget.encoding) self._imports = introspection.obtain_imports(source) self._imports_names = list(self._imports["imports"].keys()) self._imports_names += [imp for imp in self._imports['fromImports']] self._froms = [self._imports['fromImports'][imp]['module'] for imp in self._imports['fromImports']] self._froms += simple_python_completion() hbox = QGridLayout(self) hbox.addWidget(QLabel('from'), 0, 0) self._lineFrom, self._insertAt = QLineEdit(self), QSpinBox(self) self._completer = QCompleter(self._froms) self._lineFrom.setCompleter(self._completer) self._lineFrom.setPlaceholderText("module") self._insertAt.setRange(0, 999) line, _ = self._editorWidget.cursor_position self._insertAt.setValue(line) hbox.addWidget(self._lineFrom, 0, 1) hbox.addWidget(QLabel('import'), 0, 2) self._lineImport, self._asImport = QLineEdit(self), QLineEdit(self) self._completerImport = QCompleter(self._imports_names) self._lineImport.setCompleter(self._completerImport) self._lineImport.setPlaceholderText("object") self._asImport.setPlaceholderText("object_name") self._lineComment = QLineEdit(self) self._lineComment.setPlaceholderText("lint:ok") self._lineComment.setCompleter(QCompleter(LIST_OF_PY_CHECKERS_COMMENTS)) hbox.addWidget(self._lineImport, 0, 3) hbox.addWidget(QLabel('as'), 0, 4) hbox.addWidget(self._asImport, 0, 5) hbox.addWidget(QLabel(translations.TR_INSERT_AT_LINE), 1, 0) hbox.addWidget(self._insertAt, 1, 1) hbox.addWidget(QLabel(translations.TR_WITH_COMMENT), 1, 2) hbox.addWidget(self._lineComment, 1, 3) self._btnAdd = QPushButton(translations.TR_ADD, self) hbox.addWidget(self._btnAdd, 1, 5) self._lineImport.returnPressed.connect(self._add_import) self._btnAdd.clicked.connect(self._add_import) def _add_import(self): """Get From item and Import item and add the import on the code.""" fromItem = self._lineFrom.text().strip() # from FOO importItem = self._lineImport.text().strip() # import BAR asItem = self._asImport.text().strip() # as FOO_BAR importComment = self._lineComment.text().strip() if fromItem: importLine = 'from {0} import {1}'.format(fromItem, importItem) else: importLine = 'import {0}'.format(importItem) if asItem: importLine += " as " + asItem if importComment: importLine += " # " + importComment cursor = self._editorWidget.textCursor() cursor.movePosition(cursor.Start) cursor.movePosition(cursor.Down, cursor.MoveAnchor, self._insertAt.value() - 1) cursor.insertText(importLine + "\n") self.close()
5,155
Python
.py
105
42.32381
80
0.685748
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,552
traceback_widget.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/traceback_widget.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from PyQt4.QtGui import QDialog from PyQt4.QtGui import QTabWidget from PyQt4.QtGui import QPlainTextEdit from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QWidget from PyQt4.QtGui import QLabel from PyQt4.QtGui import QPushButton from PyQt4.QtCore import SIGNAL from ninja_ide import translations class PluginErrorDialog(QDialog): """ Dialog with tabs each tab is a python traceback """ def __init__(self): QDialog.__init__(self) self.setWindowTitle(translations.TR_PLUGIN_ERROR_REPORT) self.resize(600, 400) vbox = QVBoxLayout(self) label = QLabel(translations.TR_SOME_PLUGINS_REMOVED) vbox.addWidget(label) self._tabs = QTabWidget() vbox.addWidget(self._tabs) hbox = QHBoxLayout() btnAccept = QPushButton(translations.TR_ACCEPT) btnAccept.setMaximumWidth(100) hbox.addWidget(btnAccept) vbox.addLayout(hbox) # signals self.connect(btnAccept, SIGNAL("clicked()"), self.close) def add_traceback(self, plugin_name, traceback_msg): """Add a Traceback to the widget on a new tab""" traceback_widget = TracebackWidget(traceback_msg) self._tabs.addTab(traceback_widget, plugin_name) class TracebackWidget(QWidget): """ Represents a python traceback """ def __init__(self, traceback_msg): QWidget.__init__(self) vbox = QVBoxLayout(self) self._editor = QPlainTextEdit() vbox.addWidget(QLabel(translations.TR_TRACEBACK)) vbox.addWidget(self._editor) self._editor.setReadOnly(True) self._editor.setLineWrapMode(0) self._editor.insertPlainText(traceback_msg) self._editor.selectAll()
2,515
Python
.py
65
33.630769
70
0.716571
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,553
new_project_manager.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/new_project_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QDialog, QWizard, # QLineEdit, QVBoxLayout, QListWidget, QListWidgetItem, QHBoxLayout, QLabel, QTextBrowser, # QPushButton, # QSpacerItem, # QSizePolicy, QDialogButtonBox ) from PyQt5.QtCore import Qt from ninja_ide import translations from ninja_ide.gui.ide import IDE from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger(__name__) class NewProjectManager(QDialog): def __init__(self, parent=None): super(NewProjectManager, self).__init__(parent, Qt.Dialog) self.setWindowTitle(translations.TR_NEW_PROJECT) self.setMinimumHeight(500) vbox = QVBoxLayout(self) vbox.addWidget(QLabel(translations.TR_CHOOSE_TEMPLATE)) vbox.addWidget(QLabel(translations.TR_TAB_PROJECTS)) hbox = QHBoxLayout() self.list_projects = QListWidget() self.list_projects.setProperty("wizard", True) hbox.addWidget(self.list_projects) self.list_templates = QListWidget() self.list_templates.setProperty("wizard", True) hbox.addWidget(self.list_templates) self.text_info = QTextBrowser() self.text_info.setProperty("wizard", True) hbox.addWidget(self.text_info) vbox.addLayout(hbox) button_box = QDialogButtonBox( QDialogButtonBox.Cancel | QDialogButtonBox.Ok) choose_button = button_box.button(QDialogButtonBox.Ok) choose_button.setText(translations.TR_CHOOSE) # hbox2.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding, # QSizePolicy.Fixed)) vbox.addWidget(button_box) self.template_registry = IDE.get_service("template_registry") categories = self.template_registry.list_project_categories() for category in categories: self.list_projects.addItem(category) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject) self.list_projects.itemSelectionChanged.connect( self._project_selected) self.list_templates.itemSelectionChanged.connect( self._template_selected) self.list_projects.setCurrentRow(0) def accept(self): logger.debug("Accept...") self._start_wizard() super().accept() def _project_selected(self): self.list_templates.clear() item = self.list_projects.currentItem() category = item.text() for template in self.template_registry.list_templates_for_cateogory( category): item = QListWidgetItem(template.type_name) item.setData(Qt.UserRole, template) item = self.list_templates.addItem(item) self.list_templates.setCurrentRow(0) def _template_selected(self): item = self.list_templates.currentItem() ptype = item.data(Qt.UserRole) self.text_info.setText(ptype.description) def _start_wizard(self): item = self.list_templates.currentItem() if item is not None: project_type = item.data(Qt.UserRole) ninja = IDE.get_service("ide") wizard = WizardProject(project_type, ninja) wizard.show() class WizardProject(QWizard): def __init__(self, project_type, parent=None): super().__init__(parent) self.resize(700, 400) self._project_type = project_type self.setWindowTitle(project_type.type_name) for page in project_type.wizard_pages(): self.addPage(page) self.setTitleFormat(Qt.RichText) def done(self, result): if result == 1: path = self.field("path") name = self.field("name") license_txt = self.field("license") prj_obj = self._project_type(name, path, license_txt) prj_obj.create_layout(self) super().done(result)
4,605
Python
.py
115
32.730435
76
0.67256
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,554
plugins_manager.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/plugins_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import webbrowser from copy import copy from distutils import version import os from PyQt4.QtGui import QWidget from PyQt4.QtGui import QFormLayout from PyQt4.QtGui import QFileDialog from PyQt4.QtGui import QDialog from PyQt4.QtGui import QLabel from PyQt4.QtGui import QTextBrowser from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QTableWidget from PyQt4.QtGui import QTabWidget from PyQt4.QtGui import QPlainTextEdit from PyQt4.QtGui import QLineEdit from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QSpacerItem from PyQt4.QtGui import QSizePolicy from PyQt4.QtGui import QMessageBox from PyQt4.QtGui import QIcon from PyQt4.QtGui import QCompleter from PyQt4.QtGui import QDirModel from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from PyQt4.QtCore import QThread from PyQt4.QtCore import QDir from ninja_ide.core import plugin_manager from ninja_ide.core.file_handling import file_manager from ninja_ide.tools import ui_tools from ninja_ide import translations from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.gui.dialogs.plugin_manager') HTML_STYLE = """ <html> <body> <h2>{name}</h2> <p><i>Version: {version}</i></p> <h3>{description}</h3> <br><p><b>Author:</b> {author}</p> <p>More info about the Plugin: <a href='{link}'>Website</a></p> </body> </html> """ def _get_plugin(plugin_name, plugin_list): """Takes a plugin name and plugin list and return the Plugin object""" plugin = None for plug in plugin_list: if plug["name"] == plugin_name: plugin = plug break return plugin def _format_for_table(plugins): """Take a list of plugins and format it for the table on the UI""" return [[data["name"], data["version"], data["description"], data["authors"], data["home"]] for data in plugins] class PluginsManagerWidget(QDialog): """Plugin Manager widget""" def __init__(self, parent): QDialog.__init__(self, parent, Qt.Dialog) self.setWindowTitle(translations.TR_PLUGIN_MANAGER) self.resize(700, 600) vbox = QVBoxLayout(self) self._tabs = QTabWidget() vbox.addWidget(self._tabs) self._txt_data = QTextBrowser() self._txt_data.setOpenLinks(False) vbox.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION)) vbox.addWidget(self._txt_data) # Footer hbox = QHBoxLayout() btn_close = QPushButton(translations.TR_CLOSE) btnReload = QPushButton(translations.TR_RELOAD) hbox.addWidget(btn_close) hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox.addWidget(btnReload) vbox.addLayout(hbox) self.overlay = ui_tools.Overlay(self) self.overlay.hide() self._oficial_available = [] self._community_available = [] self._locals = [] self._updates = [] self._loading = True self._requirements = {} self.connect(btnReload, SIGNAL("clicked()"), self._reload_plugins) self.thread = ThreadLoadPlugins(self) self.connect(self.thread, SIGNAL("finished()"), self._load_plugins_data) self.connect(self.thread, SIGNAL("plugin_downloaded(PyQt_PyObject)"), self._after_download_plugin) self.connect(self.thread, SIGNAL("plugin_manually_installed(PyQt_PyObject)"), self._after_manual_install_plugin) self.connect(self.thread, SIGNAL("plugin_uninstalled(PyQt_PyObject)"), self._after_uninstall_plugin) self.connect(self._txt_data, SIGNAL("anchorClicked(const QUrl&)"), self._open_link) self.connect(btn_close, SIGNAL('clicked()'), self.close) self.overlay.show() self._reload_plugins() def show_plugin_info(self, data): """Takes data argument, format for HTML and display it""" plugin_description = data[2].replace('\n', '<br>') html = HTML_STYLE.format(name=data[0], version=data[1], description=plugin_description, author=data[3], link=data[4]) self._txt_data.setHtml(html) def _open_link(self, url): """Takes an url argument and open the link on web browser""" link = url.toString() if link.startswith('/plugins/'): link = 'http://ninja-ide.org' + link webbrowser.open(link) def _reload_plugins(self): """Reload all plugins""" self.overlay.show() self._loading = True self.thread.runnable = self.thread.collect_data_thread self.thread.start() def _after_manual_install_plugin(self, plugin): """After installing, take plugin and add it to installedWidget items""" data = {} data['name'] = plugin[0] data['version'] = plugin[1] data['description'] = '' data['authors'] = '' data['home'] = '' self._installedWidget.add_table_items([data]) def _after_download_plugin(self, plugin): """After installing, take plugin and add it to installedWidget items""" oficial_plugin = _get_plugin(plugin[0], self._oficial_available) community_plugin = _get_plugin(plugin[0], self._community_available) if oficial_plugin: self._installedWidget.add_table_items([oficial_plugin]) self._availableOficialWidget.remove_item(plugin[0]) elif community_plugin: self._installedWidget.add_table_items([community_plugin]) self._availableCommunityWidget.remove_item(plugin[0]) def _after_uninstall_plugin(self, plugin): """After uninstall plugin,make available plugin corresponding to type""" oficial_plugin = _get_plugin(plugin[0], self._oficial_available) community_plugin = _get_plugin(plugin[0], self._community_available) if oficial_plugin: self._availableOficialWidget.add_table_items([oficial_plugin]) self._installedWidget.remove_item(plugin[0]) elif community_plugin: self._availableCommunityWidget.add_table_items([community_plugin]) self._installedWidget.remove_item(plugin[0]) def _load_plugins_data(self): """Load all the plugins data""" if self._loading: self._tabs.clear() self._updatesWidget = UpdatesWidget(self, copy(self._updates)) self._availableOficialWidget = AvailableWidget(self, copy(self._oficial_available)) self._availableCommunityWidget = AvailableWidget(self, copy(self._community_available)) self._installedWidget = InstalledWidget(self, copy(self._locals)) self._tabs.addTab(self._availableOficialWidget, translations.TR_OFFICIAL_AVAILABLE) self._tabs.addTab(self._availableCommunityWidget, translations.TR_COMMUNITY_AVAILABLE) self._tabs.addTab(self._updatesWidget, translations.TR_UPDATE) self._tabs.addTab(self._installedWidget, translations.TR_INSTALLED) self._manualWidget = ManualInstallWidget(self) self._tabs.addTab(self._manualWidget, translations.TR_MANUAL_INSTALL) self._loading = False self.overlay.hide() self.thread.wait() def download_plugins(self, plugs): """ Install """ self.overlay.show() self.thread.plug = plugs # set the function to run in the thread self.thread.runnable = self.thread.download_plugins_thread self.thread.start() def install_plugins_manually(self, plug): """Install plugin from local zip.""" self.overlay.show() self.thread.plug = plug # set the function to run in the thread self.thread.runnable = self.thread.manual_install_plugins_thread self.thread.start() def mark_as_available(self, plugs): """ Uninstall """ self.overlay.show() self.thread.plug = plugs # set the function to run in the thread self.thread.runnable = self.thread.uninstall_plugins_thread self.thread.start() def update_plugin(self, plugs): """ Update """ self.overlay.show() self.thread.plug = plugs # set the function to run in the thread self.thread.runnable = self.thread.update_plugin_thread self.thread.start() def reset_installed_plugins(self): """Reset all the installed plugins""" local_plugins = plugin_manager.local_plugins() plugins = _format_for_table(local_plugins) self._installedWidget.reset_table(plugins) def resizeEvent(self, event): """Handle Resize events""" self.overlay.resize(event.size()) event.accept() class UpdatesWidget(QWidget): """ This widget show the availables plugins to update """ def __init__(self, parent, updates): QWidget.__init__(self, parent) self._parent = parent self._updates = updates vbox = QVBoxLayout(self) self._table = ui_tools.CheckableHeaderTable(1, 2) self._table.removeRow(0) self._table.setSelectionMode(QTableWidget.SingleSelection) self._table.setColumnWidth(0, 500) self._table.setSortingEnabled(True) self._table.setAlternatingRowColors(True) vbox.addWidget(self._table) ui_tools.load_table(self._table, (translations.TR_PROJECT_NAME, translations.TR_VERSION), _format_for_table(updates)) btnUpdate = QPushButton(translations.TR_UPDATE) btnUpdate.setMaximumWidth(100) vbox.addWidget(btnUpdate) self.connect(btnUpdate, SIGNAL("clicked()"), self._update_plugins) self.connect(self._table, SIGNAL("itemSelectionChanged()"), self._show_item_description) def _show_item_description(self): """Get current item if any and show plugin information""" item = self._table.currentItem() if item is not None: data = list(item.data(Qt.UserRole)) self._parent.show_plugin_info(data) def _update_plugins(self): """Iterate over the plugins list and update each one""" data = _format_for_table(self._updates) plugins = ui_tools.remove_get_selected_items(self._table, data) # get the download link of each plugin for p_row in plugins: # search the plugin for p_dict in self._updates: if p_dict["name"] == p_row[0]: p_data = p_dict break # append the downlod link p_row.append(p_data["download"]) self._parent.update_plugin(plugins) class AvailableWidget(QWidget): """Available plugins widget""" def __init__(self, parent, available): QWidget.__init__(self, parent) self._parent = parent self._available = available vbox = QVBoxLayout(self) self._table = ui_tools.CheckableHeaderTable(1, 2) self._table.setSelectionMode(QTableWidget.SingleSelection) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, (translations.TR_PROJECT_NAME, translations.TR_VERSION), _format_for_table(available)) self._table.setColumnWidth(0, 500) self._table.setSortingEnabled(True) self._table.setAlternatingRowColors(True) hbox = QHBoxLayout() btnInstall = QPushButton(translations.TR_INSTALL) btnInstall.setMaximumWidth(100) hbox.addWidget(btnInstall) hbox.addWidget(QLabel(translations.TR_NINJA_NEEDS_TO_BE_RESTARTED)) vbox.addLayout(hbox) self.connect(btnInstall, SIGNAL("clicked()"), self._install_plugins) self.connect(self._table, SIGNAL("itemSelectionChanged()"), self._show_item_description) def _show_item_description(self): """Get current item if any and show plugin information""" item = self._table.currentItem() if item is not None: data = list(item.data(Qt.UserRole)) self._parent.show_plugin_info(data) def _install_plugins(self): """Iterate over the plugins list and download each one""" data = _format_for_table(self._available) plugins = ui_tools.remove_get_selected_items(self._table, data) # get the download link of each plugin for p_row in plugins: # search the plugin for p_dict in self._available: if p_dict["name"] == p_row[0]: p_data = p_dict break # append the downlod link p_row.append(p_data["download"]) # download self._parent.download_plugins(plugins) def remove_item(self, plugin_name): """Take a plugin name as argument and remove it""" plugin = _get_plugin(plugin_name, self._available) self._available.remove(plugin) def _install_external(self): """Install external plugins""" if self._link.text().isEmpty(): QMessageBox.information(self, translations.TR_EXTERNAL_PLUGIN, translations.TR_URL_IS_MISSING + "...") return plug = [ file_manager.get_module_name(str(self._link.text())), 'External Plugin', '1.0', str(self._link.text())] self.parent().download_plugins(plug) self._link.setText('') def add_table_items(self, plugs): """Add list of plugins to table on the UI""" self._available += plugs data = _format_for_table(self._available) ui_tools.load_table(self._table, (translations.TR_PROJECT_NAME, translations.TR_VERSION), data) class InstalledWidget(QWidget): """ This widget show the installed plugins """ def __init__(self, parent, installed): QWidget.__init__(self, parent) self._parent = parent self._installed = installed vbox = QVBoxLayout(self) self._table = ui_tools.CheckableHeaderTable(1, 2) self._table.setSelectionMode(QTableWidget.SingleSelection) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, (translations.TR_PROJECT_NAME, translations.TR_VERSION), _format_for_table(installed)) self._table.setColumnWidth(0, 500) self._table.setSortingEnabled(True) self._table.setAlternatingRowColors(True) btnUninstall = QPushButton(translations.TR_UNINSTALL) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self.connect(btnUninstall, SIGNAL("clicked()"), self._uninstall_plugins) self.connect(self._table, SIGNAL("itemSelectionChanged()"), self._show_item_description) def _show_item_description(self): """Get current item if any and show plugin information""" item = self._table.currentItem() if item is not None: data = list(item.data(Qt.UserRole)) self._parent.show_plugin_info(data) def remove_item(self, plugin_name): """Take a plugin name as argument and remove it""" plugin = _get_plugin(plugin_name, self._installed) self._installed.remove(plugin) def add_table_items(self, plugs): """Add list of plugins to table on the UI""" self._installed += plugs data = _format_for_table(self._installed) ui_tools.load_table(self._table, (translations.TR_PROJECT_NAME, translations.TR_VERSION), data) def _uninstall_plugins(self): """Take a plugin name as argument and uninstall it""" data = _format_for_table(self._installed) plugins = ui_tools.remove_get_selected_items(self._table, data) self._parent.mark_as_available(plugins) def reset_table(self, installed): """Reset the list of plugins on the table on the UI""" self._installed = installed while self._table.rowCount() > 0: self._table.removeRow(0) ui_tools.load_table(self._table, (translations.TR_PROJECT_NAME, translations.TR_VERSION), self._installed) class ManualInstallWidget(QWidget): """Manually Installed plugins widget""" def __init__(self, parent): super(ManualInstallWidget, self).__init__() self._parent = parent vbox = QVBoxLayout(self) form = QFormLayout() self._txtName = QLineEdit() self._txtName.setPlaceholderText('my_plugin') self._txtVersion = QLineEdit() self._txtVersion.setPlaceholderText('0.1') form.addRow(translations.TR_PROJECT_NAME, self._txtName) form.addRow(translations.TR_VERSION, self._txtVersion) vbox.addLayout(form) hPath = QHBoxLayout() self._txtFilePath = QLineEdit() self._txtFilePath.setPlaceholderText(os.path.join( os.path.expanduser('~'), 'full', 'path', 'to', 'plugin.zip')) self._btnFilePath = QPushButton(QIcon(":img/open"), '') self.completer, self.dirs = QCompleter(self), QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self._txtFilePath.setCompleter(self.completer) hPath.addWidget(QLabel(translations.TR_FILENAME)) hPath.addWidget(self._txtFilePath) hPath.addWidget(self._btnFilePath) vbox.addLayout(hPath) vbox.addSpacerItem(QSpacerItem(0, 1, QSizePolicy.Expanding, QSizePolicy.Expanding)) hbox = QHBoxLayout() hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) self._btnInstall = QPushButton(translations.TR_INSTALL) hbox.addWidget(self._btnInstall) vbox.addLayout(hbox) # Signals self.connect(self._btnFilePath, SIGNAL("clicked()"), self._load_plugin_path) self.connect(self._btnInstall, SIGNAL("clicked()"), self.install_plugin) def _load_plugin_path(self): """Ask the user a plugin filename""" path = QFileDialog.getOpenFileName(self, translations.TR_SELECT_PLUGIN_PATH) if path: self._txtFilePath.setText(path) def install_plugin(self): """Install a plugin manually""" if self._txtFilePath.text() and self._txtName.text(): plug = [] plug.append(self._txtName.text()) plug.append(self._txtVersion.text()) plug.append('') plug.append('') plug.append('') plug.append(self._txtFilePath.text()) self._parent.install_plugins_manually([plug]) class ThreadLoadPlugins(QThread): """ This thread makes the HEAVY work! """ def __init__(self, manager): super(ThreadLoadPlugins, self).__init__() self._manager = manager # runnable hold a function to call! self.runnable = self.collect_data_thread # this attribute contains the plugins to download/update self.plug = None def run(self): """Start the Thread""" self.runnable() self.plug = None def collect_data_thread(self): """ Collects plugins info from NINJA-IDE webservice interface """ # get availables OFICIAL plugins oficial_available = plugin_manager.available_oficial_plugins() # get availables COMMUNITIES plugins community_available = plugin_manager.available_community_plugins() # get locals plugins local_plugins = plugin_manager.local_plugins() updates = [] # Check por update the already installed plugin for local_data in local_plugins: ava = None plug_oficial = _get_plugin(local_data["name"], oficial_available) plug_community = _get_plugin(local_data["name"], community_available) if plug_oficial: ava = plug_oficial oficial_available = [p for p in oficial_available if p["name"] != local_data["name"]] elif plug_community: ava = plug_community community_available = [p for p in community_available if p["name"] != local_data["name"]] # check versions if ava: available_version = version.LooseVersion(str(ava["version"])) else: available_version = version.LooseVersion('0.0') local_version = version.LooseVersion(str(local_data["version"])) if available_version > local_version: # this plugin has an update updates.append(ava) # set manager attributes self._manager._oficial_available = oficial_available self._manager._community_available = community_available self._manager._locals = local_plugins self._manager._updates = updates def download_plugins_thread(self): """ Downloads some plugins """ for p in self.plug: try: name = plugin_manager.download_plugin(p[5]) p.append(name) plugin_manager.update_local_plugin_descriptor((p, )) req_command = plugin_manager.has_dependencies(p) if req_command[0]: self._manager._requirements[p[0]] = req_command[1] self.emit(SIGNAL("plugin_downloaded(PyQt_PyObject)"), p) except Exception as e: logger.warning("Impossible to install (%s): %s", p[0], e) def manual_install_plugins_thread(self): """ Install a plugin from the a file. """ for p in self.plug: try: name = plugin_manager.manual_install(p[5]) p.append(name) plugin_manager.update_local_plugin_descriptor((p, )) req_command = plugin_manager.has_dependencies(p) if req_command[0]: self._manager._requirements[p[0]] = req_command[1] self.emit( SIGNAL("plugin_manually_installed(PyQt_PyObject)"), p) except Exception as e: logger.warning("Impossible to install (%s): %s", p[0], e) def uninstall_plugins_thread(self): """Uninstall a plugin""" for p in self.plug: try: plugin_manager.uninstall_plugin(p) self.emit(SIGNAL("plugin_uninstalled(PyQt_PyObject)"), p) except Exception as e: logger.warning("Impossible to uninstall (%s): %s", p[0], e) def update_plugin_thread(self): """ Updates some plugins """ for p in self.plug: try: plugin_manager.uninstall_plugin(p) name = plugin_manager.download_plugin(p[5]) p.append(name) plugin_manager.update_local_plugin_descriptor([p]) self._manager.reset_installed_plugins() except Exception as e: logger.warning("Impossible to update (%s): %s", p[0], e) class DependenciesHelpDialog(QDialog): """Help on Plugin Dependencies widget""" def __init__(self, requirements_dict): super(DependenciesHelpDialog, self).__init__() self.setWindowTitle(translations.TR_REQUIREMENTS) self.resize(525, 400) vbox = QVBoxLayout(self) label = QLabel(translations.TR_SOME_PLUGINS_NEED_DEPENDENCIES) vbox.addWidget(label) self._editor = QPlainTextEdit() self._editor.setReadOnly(True) vbox.addWidget(self._editor) hbox = QHBoxLayout() btnAccept = QPushButton(translations.TR_ACCEPT) btnAccept.setMaximumWidth(100) hbox.addWidget(btnAccept) vbox.addLayout(hbox) # signals self.connect(btnAccept, SIGNAL("clicked()"), self.close) command_tmpl = "<%s>:\n%s\n" for name, description in list(requirements_dict.items()): self._editor.insertPlainText(command_tmpl % (name, description))
25,749
Python
.py
586
33.74744
93
0.618343
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,555
plugins_store.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/plugins_store.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import collections import random from PyQt4.QtGui import QDialog from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QColor from PyQt4.QtDeclarative import QDeclarativeView from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from ninja_ide import translations from ninja_ide.tools import ui_tools from ninja_ide.core.encapsulated_env import nenvironment class PluginsStore(QDialog): def __init__(self, parent=None): super(PluginsStore, self).__init__(parent, Qt.Dialog) self.setWindowTitle(translations.TR_MANAGE_PLUGINS) vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) self.view = QDeclarativeView() self.view.setMinimumWidth(800) self.view.setMinimumHeight(600) self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView) self.view.setSource(ui_tools.get_qml_resource("PluginsStore.qml")) self.root = self.view.rootObject() vbox.addWidget(self.view) self._plugins = {} self._plugins_inflate = [] self._plugins_by_tag = collections.defaultdict(list) self._plugins_by_author = collections.defaultdict(list) self._base_color = QColor("white") self._counter = 0 self._counter_callback = None self._inflating_plugins = [] self._categoryTags = True self._search = [] self.status = None self.connect(self.root, SIGNAL("loadPluginsGrid()"), self._load_by_name) self.connect(self.root, SIGNAL("close()"), self.close) self.connect(self.root, SIGNAL("showPluginDetails(int)"), self.show_plugin_details) self.connect(self.root, SIGNAL("loadTagsGrid()"), self._load_tags_grid) self.connect(self.root, SIGNAL("loadAuthorGrid()"), self._load_author_grid) self.connect(self.root, SIGNAL("search(QString)"), self._load_search_results) self.connect(self.root, SIGNAL("loadPluginsForCategory(QString)"), self._load_plugins_for_category) self.connect(self, SIGNAL("processCompleted(PyQt_PyObject)"), self._process_complete) self.nenv = nenvironment.NenvEggSearcher() self.connect(self.nenv, SIGNAL("searchCompleted(PyQt_PyObject)"), self.callback) self.status = self.nenv.do_search() def _load_by_name(self): if self._plugins: self.root.showGridPlugins() for plugin in list(self._plugins.values()): self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) def _load_plugins_for_category(self, name): self.root.showGridPlugins() if self._categoryTags: for plugin in self._plugins_by_tag[name]: self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) else: for plugin in self._plugins_by_author[name]: self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) def callback(self, values): self.root.showGridPlugins() for i, plugin in enumerate(values): plugin.identifier = i + 1 self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) self._plugins[plugin.identifier] = plugin def show_plugin_details(self, identifier): plugin = self._plugins[identifier] self._counter = 1 self._counter_callback = self._show_details if plugin.shallow: self.connect(plugin, SIGNAL("pluginMetadataInflated(PyQt_PyObject)"), self._update_content) self._plugins_inflate.append(plugin.inflate()) else: self._update_content(plugin) def _load_tags_grid(self): self._categoryTags = True self._counter = len(self._plugins) self.root.updateCategoryCounter(self._counter) self._counter_callback = self._show_tags_grid self._inflating_plugins = list(self._plugins.values()) self._loading_function() def _load_author_grid(self): self._categoryTags = False self._counter = len(self._plugins) self.root.updateCategoryCounter(self._counter) self._counter_callback = self._show_author_grid self._inflating_plugins = list(self._plugins.values()) self._loading_function() def _load_search_results(self, search): self._search = search.lower().split() self._counter = len(self._plugins) self.root.updateCategoryCounter(self._counter) self._counter_callback = self._show_search_grid self._inflating_plugins = list(self._plugins.values()) self._loading_function() def _loading_function(self): plugin = self._inflating_plugins.pop() if plugin.shallow: self.connect(plugin, SIGNAL("pluginMetadataInflated(PyQt_PyObject)"), self._update_content) self._plugins_inflate.append(plugin.inflate()) else: self._process_complete(plugin) def _process_complete(self, plugin=None): self._counter -= 1 self.root.updateCategoryCounter(self._counter) if self._counter == 0: self._counter_callback(plugin) else: self._loading_function() def _show_search_grid(self, plugin=None): self.root.showGridPlugins() for plugin in list(self._plugins.values()): keywords = plugin.keywords.lower().split() + [plugin.name.lower()] for word in self._search: if word in keywords: self.root.addPlugin(plugin.identifier, plugin.name, plugin.summary, plugin.version) def _show_details(self, plugin): self.root.displayDetails(plugin.identifier) def _show_tags_grid(self, plugin=None): tags = sorted(self._plugins_by_tag.keys()) for tag in tags: color = self._get_random_color(self._base_color) self.root.addCategory(color.name(), tag) self.root.loadingComplete() def _show_author_grid(self, plugin=None): authors = sorted(self._plugins_by_author.keys()) for author in authors: color = self._get_random_color(self._base_color) self.root.addCategory(color.name(), author) self.root.loadingComplete() def _update_content(self, plugin): self.root.updatePlugin( plugin.identifier, plugin.author, plugin.author_email, plugin.description, plugin.download_url, plugin.home_page, plugin.license) keywords = plugin.keywords.split() for key in keywords: plugins = self._plugins_by_tag[key] if plugin not in plugins: plugins.append(plugin) self._plugins_by_tag[key] = plugins plugins = self._plugins_by_author[plugin.author] if plugin not in plugins: plugins.append(plugin) self._plugins_by_author[plugin.author] = plugins self.emit(SIGNAL("processCompleted(PyQt_PyObject)"), plugin) def _get_random_color(self, mix=None): red = random.randint(0, 256) green = random.randint(0, 256) blue = random.randint(0, 256) # mix the color if mix: red = (red + mix.red()) / 2 green = (green + mix.green()) / 2 blue = (blue + mix.blue()) / 2 color = QColor(red, green, blue) return color
8,624
Python
.py
193
34.336788
78
0.622011
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,556
add_to_project.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/add_to_project.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QListWidget from PyQt5.QtWidgets import QTreeView from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QAbstractItemView from PyQt5.QtWidgets import QFileSystemModel from PyQt5.QtWidgets import QHeaderView from PyQt5.QtCore import QDir from ninja_ide import translations class AddToProject(QDialog): """Dialog to let the user choose one of the folders from the opened proj""" def __init__(self, projects, parent=None): super(AddToProject, self).__init__(parent) # projects must be a list self._projects = projects self.setWindowTitle(translations.TR_ADD_FILE_TO_PROJECT) self.path_selected = '' vbox = QVBoxLayout(self) hbox = QHBoxLayout() self._list = QListWidget() for project in self._projects: self._list.addItem(project.name) self._list.setCurrentRow(0) self._tree = QTreeView() self._tree.setHeaderHidden(True) self._tree.setSelectionMode(QTreeView.SingleSelection) self._tree.setAnimated(True) self.load_tree(self._projects[0]) hbox.addWidget(self._list) hbox.addWidget(self._tree) vbox.addLayout(hbox) hbox2 = QHBoxLayout() btn_add = QPushButton(translations.TR_ADD_HERE) btn_cancel = QPushButton(translations.TR_CANCEL) hbox2.addWidget(btn_cancel) hbox2.addWidget(btn_add) vbox.addLayout(hbox2) btn_add.clicked.connect(self._select_path) btn_cancel.clicked.connect(self.close) self._list.currentItemChanged.connect(self._project_changed) def _project_changed(self, item, previous): # FIXME, this is not being called, at least in osx for each_project in self._projects: if each_project.name == item.text(): self.load_tree(each_project) def load_tree(self, project): """Load the tree view on the right based on the project selected.""" qfsm = QFileSystemModel() qfsm.setRootPath(project.path) load_index = qfsm.index(qfsm.rootPath()) qfsm.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) qfsm.setNameFilterDisables(False) pext = ["*{0}".format(x) for x in project.extensions] qfsm.setNameFilters(pext) self._tree.setModel(qfsm) self._tree.setRootIndex(load_index) t_header = self._tree.header() t_header.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel) t_header.setSectionResizeMode(0, QHeaderView.Stretch) t_header.setStretchLastSection(False) t_header.setSectionsClickable(True) self._tree.hideColumn(1) # Size self._tree.hideColumn(2) # Type self._tree.hideColumn(3) # Modification date # FIXME: Changing the name column's title requires some magic # Please look at the project tree def _select_path(self): """Set path_selected to the folder selected in the tree.""" path = self._tree.model().filePath(self._tree.currentIndex()) if path: self.path_selected = path self.close()
4,002
Python
.py
91
37.318681
79
0.697639
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,557
about_ninja.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/about_ninja.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import webbrowser from PyQt5.QtWidgets import ( QDialog, QVBoxLayout, QHBoxLayout, QSizePolicy, QSpacerItem, QPushButton, QLabel ) from PyQt5.QtGui import QPixmap from PyQt5.QtCore import ( Qt, QSize ) import ninja_ide from ninja_ide import translations class AboutNinja(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent, Qt.Dialog | Qt.FramelessWindowHint) self.setWindowTitle(self.tr("About NINJA-IDE")) self.setMaximumSize(QSize(0, 0)) vbox = QVBoxLayout(self) # Create an icon for the Dialog pixmap = QPixmap(":img/icon") self.lblIcon = QLabel() self.lblIcon.setPixmap(pixmap) hbox = QHBoxLayout() hbox.addWidget(self.lblIcon) lblTitle = QLabel( '<h1>NINJA-IDE</h1>\n<i>Ninja-IDE Is Not Just Another IDE<i>') lblTitle.setTextFormat(Qt.RichText) lblTitle.setAlignment(Qt.AlignLeft) hbox.addWidget(lblTitle) vbox.addLayout(hbox) # Add description vbox.addWidget(QLabel( self.tr("""NINJA-IDE (from: "Ninja Is Not Just Another IDE"), is a cross-platform integrated development environment specifically designed to build Python Applications. NINJA-IDE provides the tools necessary to simplify the Python software development process and handles all kinds of situations thanks to its rich extensibility."""))) vbox.addWidget(QLabel(self.tr("Version: %s") % ninja_ide.__version__)) link_ninja = QLabel( self.tr('Website: <a href="%s"><span style=" ' 'text-decoration: underline; color:#ff9e21;">' '%s</span></a>') % (ninja_ide.__url__, ninja_ide.__url__)) vbox.addWidget(link_ninja) link_source = QLabel( self.tr('Source Code: <a href="%s"><span style=" ' 'text-decoration: underline; color:#ff9e21;">%s</span></a>') % (ninja_ide.__source__, ninja_ide.__source__)) vbox.addWidget(link_source) hbox2 = QHBoxLayout() hbox2.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) btn_close = QPushButton(translations.TR_CLOSE) hbox2.addWidget(btn_close) vbox.addLayout(hbox2) # FIXME: setOpenExternalLinks on labels link_ninja.linkActivated['QString'].connect(self.link_activated) link_source.linkActivated['QString'].connect(self.link_activated) btn_close.clicked.connect(self.close) def link_activated(self, link): webbrowser.open(str(link))
3,339
Python
.py
83
33.843373
82
0.674175
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,558
schemes_manager.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/schemes_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os try: from urllib.request import urlopen from urllib.error import URLError except ImportError: from urllib2 import urlopen from urllib2 import URLError from PyQt4.QtGui import QWidget from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QSpacerItem from PyQt4.QtGui import QSizePolicy from PyQt4.QtGui import QTabWidget from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QDialog from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from ninja_ide import resources from ninja_ide import translations from ninja_ide.core.file_handling import file_manager from ninja_ide.tools import ui_tools from ninja_ide.tools import json_manager class SchemesManagerWidget(QDialog): def __init__(self, parent): super(SchemesManagerWidget, self).__init__(parent, Qt.Dialog) self.setWindowTitle(translations.TR_EDITOR_SCHEMES) self.resize(700, 500) vbox = QVBoxLayout(self) self._tabs = QTabWidget() vbox.addWidget(self._tabs) # Footer hbox = QHBoxLayout() btn_close = QPushButton(self.tr('Close')) btnReload = QPushButton(self.tr("Reload")) hbox.addWidget(btn_close) hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox.addWidget(btnReload) vbox.addLayout(hbox) self.overlay = ui_tools.Overlay(self) self.overlay.show() self._schemes = [] self._loading = True self.downloadItems = [] # Load Themes with Thread self.connect(btnReload, SIGNAL("clicked()"), self._reload_themes) self._thread = ui_tools.ThreadExecution(self.execute_thread) self.connect(self._thread, SIGNAL("finished()"), self.load_skins_data) self.connect(btn_close, SIGNAL('clicked()'), self.close) self._reload_themes() def _reload_themes(self): self.overlay.show() self._loading = True self._thread.execute = self.execute_thread self._thread.start() def load_skins_data(self): if self._loading: self._tabs.clear() self._schemeWidget = SchemeWidget(self, self._schemes) self._tabs.addTab(self._schemeWidget, self.tr("Editor Schemes")) self._loading = False self.overlay.hide() self._thread.wait() def download_scheme(self, scheme): self.overlay.show() self.downloadItems = scheme self._thread.execute = self._download_scheme_thread self._thread.start() def resizeEvent(self, event): self.overlay.resize(event.size()) event.accept() def execute_thread(self): try: descriptor_schemes = urlopen(resources.SCHEMES_URL) schemes = json_manager.parse(descriptor_schemes) schemes = [(d['name'], d['download']) for d in schemes] local_schemes = self.get_local_schemes() schemes = [schemes[i] for i in range(len(schemes)) if os.path.basename(schemes[i][1]) not in local_schemes] self._schemes = schemes except URLError: self._schemes = [] def get_local_schemes(self): if not file_manager.folder_exists(resources.EDITOR_SKINS): file_manager.create_tree_folders(resources.EDITOR_SKINS) schemes = os.listdir(resources.EDITOR_SKINS) schemes = [s for s in schemes if s.lower().endswith('.color')] return schemes def _download_scheme_thread(self): for d in self.downloadItems: self.download(d[1], resources.EDITOR_SKINS) def download(self, url, folder): fileName = os.path.join(folder, os.path.basename(url)) try: content = urlopen(url) with open(fileName, 'w') as f: f.write(content.read()) except URLError: return class SchemeWidget(QWidget): def __init__(self, parent, schemes): QWidget.__init__(self, parent) self._parent = parent self._schemes = schemes vbox = QVBoxLayout(self) self._table = ui_tools.CheckableHeaderTable(1, 2) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, [self.tr('Name'), self.tr('URL')], self._schemes) btnUninstall = QPushButton(self.tr('Download')) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self._table.setColumnWidth(0, 200) self._table.setSortingEnabled(True) self._table.setAlternatingRowColors(True) self.connect(btnUninstall, SIGNAL("clicked()"), self._download_scheme) def _download_scheme(self): schemes = ui_tools.remove_get_selected_items(self._table, self._schemes) self._parent.download_scheme(schemes)
5,572
Python
.py
135
33.903704
80
0.668205
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,559
session_manager.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/session_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QFrame from PyQt5.QtWidgets import QLayout from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QTreeWidget from PyQt5.QtWidgets import QTreeWidgetItem from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QInputDialog from PyQt5.QtWidgets import QMessageBox from PyQt5.QtCore import Qt from PyQt5.QtCore import QObject from PyQt5.QtCore import pyqtSignal from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger(__name__) class _SessionManager(QObject): aboutToSaveSession = pyqtSignal() sessionChanged = pyqtSignal() def __init__(self, ninjaide): QObject.__init__(self) self._ide = ninjaide self.__sessions = {} self.__session = None self._ide.goingDown.connect(self.save) self.sessionChanged.connect(self._ide.change_window_title) @property def sessions(self): return self.__sessions def get_session(self, session_name): return self.__sessions.get(session_name) def current_session(self): return self.__session def set_current_session(self, session_name): if session_name != self.__session: self.__session = session_name self.sessionChanged.emit() def delete_session(self, session_name): if session_name in self.__sessions: del self.__sessions[session_name] data_settings = self._ide.data_settings() data_settings.setValue("ide/sessions", self.__sessions) def load_sessions(self): data_settings = self._ide.data_settings() sessions = data_settings.value("ide/sessions") if sessions: self.__sessions = sessions def load_session(self, session_name): """Activate the selected session, closing the current files/projects""" main_container = self._ide.get_service("main_container") projects_explorer = self._ide.get_service("projects_explorer") if projects_explorer and main_container: projects_explorer.close_opened_projects() for file_data in self.__sessions[session_name][0]: path, (line, col), stat_value = file_data if file_manager.file_exists(path): mtime = os.stat(path).st_mtime ignore_checkers = (mtime == stat_value) main_container.open_file(path, line, col, ignore_checkers=ignore_checkers) if projects_explorer: projects_explorer.load_session_projects( self.__sessions[session_name][1]) def __len__(self): return len(self.__sessions) def save_session_data(self, session_name): self.aboutToSaveSession.emit() opened_files = self._ide.filesystem.get_files() files_info = [] for path in opened_files: editable = self._ide.get_or_create_editable(path) if editable.is_dirty: stat_value = 0 else: stat_value = os.stat(path).st_mtime files_info.append( [path, editable.editor.cursor_position, stat_value]) projects_obj = self._ide.filesystem.get_projects() projects = [projects_obj[proj].path for proj in projects_obj] self.__sessions[session_name] = (files_info, projects) def save(self): logger.debug("Saving {} sessions...".format(len(self))) for session_name in self.__sessions.keys(): self.save_session_data(session_name) data_settings = self._ide.data_settings() data_settings.setValue("ide/sessions", self.__sessions) class SessionsManager(QDialog): """Session Manager, to load different configurations of ninja.""" def __init__(self, parent=None): super(SessionsManager, self).__init__(parent, Qt.Dialog) self._ninja = parent self.setModal(True) self.setWindowTitle(translations.TR_SESSIONS_TITLE) self.setMinimumWidth(550) self.setMinimumHeight(450) self._manager = _SessionManager(parent) self._load_ui() def install(self): self._manager.load_sessions() def _load_ui(self): main_layout = QVBoxLayout(self) main_layout.addWidget(QLabel(translations.TR_SESSIONS_DIALOG_BODY)) main_hbox = QHBoxLayout() # Session list session_layout = QVBoxLayout() self._session_list = QTreeWidget() self._session_list.setHeaderLabels(["Session", "Last Modified"]) session_layout.addWidget(self._session_list) # Content frame content_frame = QFrame() content_frame.hide() frame_layout = QVBoxLayout(content_frame) content_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) session_layout.addWidget(content_frame) frame_layout.setContentsMargins(0, 0, 0, 0) self._content_list = QTreeWidget() self._content_list.setHeaderHidden(True) frame_layout.addWidget(self._content_list) # Separator line line_frame = QFrame() line_frame.setFrameStyle(QFrame.VLine | QFrame.Sunken) # Buttons btn_layout = QVBoxLayout() btn_create = QPushButton(translations.TR_SESSIONS_BTN_CREATE) btn_activate = QPushButton(translations.TR_SESSIONS_BTN_ACTIVATE) btn_update = QPushButton(translations.TR_SESSIONS_BTN_UPDATE) btn_delete = QPushButton(translations.TR_SESSIONS_BTN_DELETE) btn_details = QPushButton(translations.TR_SESSIONS_BTN_DETAILS) btn_details.setCheckable(True) # Add buttons to layout btn_layout.addWidget(btn_create) btn_layout.addWidget(btn_activate) btn_layout.addWidget(btn_update) btn_layout.addWidget(btn_delete) btn_layout.addStretch() btn_layout.addWidget(btn_details) # Add widgets and layouts to the main layout main_layout.addLayout(main_hbox) main_hbox.addLayout(session_layout) main_hbox.addWidget(line_frame) main_hbox.addLayout(btn_layout) main_hbox.setSizeConstraint(QLayout.SetFixedSize) btn_details.toggled[bool].connect(content_frame.setVisible) # Connections self._session_list.itemSelectionChanged.connect( self.load_session_content) btn_activate.clicked.connect(self.open_session) btn_update.clicked.connect(self.save_session) btn_create.clicked.connect(self.create_session) btn_delete.clicked.connect(self.delete_session) def __load_sessions(self): for session_name in self._manager.sessions: item = QTreeWidgetItem() item.setText(0, session_name) item.setText(1, "FIXME: manage this!") self._session_list.addTopLevelItem(item) self._session_list.setCurrentItem( self._session_list.topLevelItem(0)) def load_session_content(self): """Load the selected session, replacing the current session.""" item = self._session_list.currentItem() self._content_list.clear() if item is not None: key = item.text(0) files, projects = self._manager.get_session(key) files_parent = QTreeWidgetItem( self._content_list, [translations.TR_FILES]) for ffile in files: QTreeWidgetItem(files_parent, [ffile[0]]) projects_parent = QTreeWidgetItem( self._content_list, [translations.TR_PROJECT]) for project in projects: QTreeWidgetItem(projects_parent, [project]) files_parent.setExpanded(True) projects_parent.setExpanded(True) def create_session(self): """Create a new Session.""" session_info = QInputDialog.getText( None, translations.TR_SESSIONS_CREATE_TITLE, translations.TR_SESSIONS_CREATE_BODY) if session_info[1]: session_name = session_info[0] if not session_name or session_name in settings.SESSIONS: QMessageBox.information( self, translations.TR_SESSIONS_MESSAGE_TITLE, translations.TR_SESSIONS_MESSAGE_BODY) return self._manager.save_session_data(session_name) self.close() def save_session(self): """Save current session""" if self._session_list.currentItem(): session_name = self._session_list.currentItem().text(0) self._manager.save_session_data(session_name) self._ninja.show_message( translations.TR_SESSIONS_UPDATED_NOTIF.format(session_name)) self.load_session_content() def open_session(self): """Open a saved session""" if self._session_list.currentItem(): session_name = self._session_list.currentItem().text(0) self._manager.load_session(session_name) self._manager.set_current_session(session_name) self.close() def delete_session(self): """Delete a session""" if self._session_list.currentItem(): key = self._session_list.currentItem().text(0) self._manager.delete_session(key) self._session_list.takeTopLevelItem( self._session_list.currentIndex().row()) @property def current_session(self): return self._manager.current_session() def showEvent(self, event): super().showEvent(event) self.__load_sessions() def hideEvent(self, event): super().hideEvent(event) self._session_list.clear()
10,673
Python
.py
241
35.157676
79
0.653646
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,560
python_detect_dialog.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/python_detect_dialog.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt4.QtGui import QDialog from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QLabel from PyQt4.QtGui import QListWidget from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QSpacerItem from PyQt4.QtGui import QSizePolicy from PyQt4.QtCore import QSettings from PyQt4.QtCore import Qt from PyQt4.QtCore import QSize from PyQt4.QtCore import SIGNAL from ninja_ide import resources from ninja_ide.core import settings class PythonDetectDialog(QDialog): def __init__(self, suggested, parent=None): super(PythonDetectDialog, self).__init__(parent, Qt.Dialog) self.setMaximumSize(QSize(0, 0)) self.setWindowTitle("Configure Python Path") vbox = QVBoxLayout(self) msg_str = ("We have detected that you are using " "Windows,\nplease choose the proper " "Python application for you:") lblMessage = QLabel(self.tr(msg_str)) vbox.addWidget(lblMessage) self.listPaths = QListWidget() self.listPaths.setSelectionMode(QListWidget.SingleSelection) vbox.addWidget(self.listPaths) hbox = QHBoxLayout() hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) btnCancel = QPushButton(self.tr("Cancel")) btnAccept = QPushButton(self.tr("Accept")) hbox.addWidget(btnCancel) hbox.addWidget(btnAccept) vbox.addLayout(hbox) self.connect(btnAccept, SIGNAL("clicked()"), self._set_python_path) self.connect(btnCancel, SIGNAL("clicked()"), self.close) for path in suggested: self.listPaths.addItem(path) self.listPaths.setCurrentRow(0) def _set_python_path(self): python_path = self.listPaths.currentItem().text() qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) settings.PYTHON_PATH = python_path settings.PYTHON_EXEC = python_path settings.PYTHON_EXEC_CONFIGURED_BY_USER = True qsettings.setValue('preferences/execution/pythonExec', python_path) qsettings.setValue('preferences/execution/pythonExecConfigured', True) self.close()
2,882
Python
.py
65
38.676923
78
0.724679
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,561
project_properties_widget.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/project_properties_widget.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import os import sys from getpass import getuser from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QAction from PyQt5.QtWidgets import QTabWidget from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QDialogButtonBox from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QGridLayout from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QCompleter from PyQt5.QtWidgets import QDirModel from PyQt5.QtWidgets import QPlainTextEdit from PyQt5.QtWidgets import QComboBox from PyQt5.QtWidgets import QFileDialog from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QSpinBox from PyQt5.QtCore import Qt from ninja_ide import translations from ninja_ide.core.file_handling import file_manager from ninja_ide.tools import utils from ninja_ide.gui.ide import IDE from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.gui.dialogs.project_properties_widget') DEBUG = logger.debug # http://opensource.org/licenses/alphabetical LICENSES = ( 'Academic Free License', 'Apache License 2.0', 'Apple Public Source License', 'Artistic License', 'Artistic license', 'Common Development and Distribution License', 'Common Public Attribution License', 'Eclipse Public License', 'Educational Community License', 'European Union Public License', 'GNU Affero General Public License', 'GNU General Public License v2', 'GNU General Public License v3', 'GNU Lesser General Public License 2.1', 'GNU Lesser General Public License 3.0', 'MIT license', 'Microsoft Public License', 'Microsoft Reciprocal License', 'Mozilla Public License 1.1', 'Mozilla Public License 2.0', 'NASA Open Source Agreement', 'New BSD License 3-Clause', 'Non-Profit Open Software License', 'Old BSD License 2-Clause', 'Open Software License', 'Other', 'Other Open Source', 'PHP License', 'PostgreSQL License', 'Proprietary', 'Python Software License', 'Simple Public License', 'W3C License', 'Zope Public License', 'zlib license') class ProjectProperties(QDialog): """Project Properties widget class""" def __init__(self, project, parent=None): super(ProjectProperties, self).__init__(parent, Qt.Dialog) self.parent = parent self.project = project self.setWindowTitle(translations.TR_PROJECT_PROPERTIES) self.resize(600, 500) vbox = QVBoxLayout(self) self.tab_widget = QTabWidget() self.project_data = ProjectData(self) self.project_execution = ProjectExecution(self) self.projectMetadata = ProjectMetadata(self) self.tab_widget.addTab(self.project_data, translations.TR_PROJECT_DATA) self.tab_widget.addTab(self.project_execution, translations.TR_PROJECT_EXECUTION) self.tab_widget.addTab(self.projectMetadata, translations.TR_PROJECT_METADATA) vbox.addWidget(self.tab_widget) button_box = QDialogButtonBox( QDialogButtonBox.Save | QDialogButtonBox.Cancel) vbox.addWidget(button_box) button_box.rejected.connect(self.close) button_box.accepted.connect(self.save_properties) def save_properties(self): self.project.name = self.project_data.name self.project.project_type = self.project_data.project_type self.project.description = self.project_data.description self.project.url = self.project_data.url self.project.license = self.project_data.license self.project.extensions = self.project_data.extensions self.project.indentation = self.project_data.indentation self.project.use_tabs = self.project_data.use_tabs self.project.main_file = self.project_execution.main_file self.project.python_exec = self.project_execution.interpreter self.project.pre_exec_script = self.project_execution.pre_script self.project.post_exec_script = self.project_execution.post_script self.project.program_params = self.project_execution.params # Save NProject self.project.save_project_properties() self.parent.refresh_file_filters() self.close() '''def save_properties(self): """Show warning message if Project Name is empty""" if not len(self.projectData.name.text().strip()): QMessageBox.critical(self, translations.TR_PROJECT_SAVE_INVALID, translations.TR_PROJECT_INVALID_MESSAGE) return self.project.name = self.projectData.name.text() self.project.description = self.projectData.description.toPlainText() self.project.license = self.projectData._combo_license.currentText() self.project.main_file = self.projectExecution.path.text() self.project.url = self.projectData.url.text() self.project.project_type = self.projectData.line_type.text() # FIXME self.project.python_exec = \ self.projectExecution.line_interpreter.text() self.project.python_path = \ self.projectExecution.txt_python_path.toPlainText() self.project.additional_builtins = [ e for e in self.projectExecution.additional_builtins.text().split(' ') if e] self.project.pre_exec_script = self.projectExecution._line_pre_exec.text() self.project.post_exec_script = self.projectExecution._line_post_exec.text() self.project.program_params = self.projectExecution._line_params.text() self.project.venv = self.projectExecution.txtVenvPath.text() extensions = self.projectData._line_extensions.text().split(', ') self.project.extensions = tuple(extensions) self.project.indentation = self.projectData._spin_indentation.value() self.project.use_tabs = bool( self.projectData._combo_tabs_or_spaces.currentIndex()) related = self.projectMetadata.txt_projects.toPlainText() related = [_path for _path in related.split('\n') if len(_path.strip())] self.project.related_projects = related self.project.save_project_properties() self.parent.refresh_file_filters() self.close()''' class ProjectData(QWidget): """Project Data widget class""" def __init__(self, parent): super(ProjectData, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0) self._line_name = QLineEdit() if not len(self._parent.project.name): self._line_name.setText(file_manager.get_basename( self._parent.project.path)) else: self._line_name.setText(self._parent.project.name) grid.addWidget(self._line_name, 0, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0) self.line_path = QLineEdit() self.line_path.setReadOnly(True) self.line_path.setText(self._parent.project.path) grid.addWidget(self.line_path, 1, 1) grid.addWidget(QLabel(translations.TR_PROJECT_TYPE), 2, 0) self.line_type = QLineEdit() template_registry = IDE.get_service("template_registry") completer = QCompleter(template_registry.list_project_categories()) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.line_type.setCompleter(completer) self.line_type.setPlaceholderText("python") self.line_type.setText(self._parent.project.project_type) grid.addWidget(self.line_type, 2, 1) grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0) self._line_description = QPlainTextEdit() self._line_description.setPlainText(self._parent.project.description) grid.addWidget(self._line_description, 3, 1) grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0) self._line_url = QLineEdit() self._line_url.setText(self._parent.project.url) self._line_url.setPlaceholderText( 'https://www.{}.com'.format(getuser())) grid.addWidget(self._line_url, 4, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0) self._combo_license = QComboBox() self._combo_license.addItems(LICENSES) self._combo_license.setCurrentIndex(12) index = self._combo_license.findText(self._parent.project.license) self._combo_license.setCurrentIndex(index) grid.addWidget(self._combo_license, 5, 1) self._line_extensions = QLineEdit() self._line_extensions.setText( ', '.join(self._parent.project.extensions)) self._line_extensions.setToolTip( translations.TR_PROJECT_EXTENSIONS_TOOLTIP) grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0) grid.addWidget(self._line_extensions, 6, 1) labelTooltip = QLabel(translations.TR_PROJECT_EXTENSIONS_INSTRUCTIONS) grid.addWidget(labelTooltip, 7, 1) grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 8, 0) self._spin_indentation = QSpinBox() self._spin_indentation.setValue(self._parent.project.indentation) self._spin_indentation.setRange(2, 10) self._spin_indentation.setValue(4) self._spin_indentation.setSingleStep(2) grid.addWidget(self._spin_indentation, 8, 1) self._combo_tabs_or_spaces = QComboBox() self._combo_tabs_or_spaces.addItems([ translations.TR_PREFERENCES_EDITOR_CONFIG_SPACES.capitalize(), translations.TR_PREFERENCES_EDITOR_CONFIG_TABS.capitalize()]) self._combo_tabs_or_spaces.setCurrentIndex( int(self._parent.project.use_tabs)) grid.addWidget(self._combo_tabs_or_spaces, 9, 1) @property def name(self): return self._line_name.text() @property def path(self): return self.line_path.text() @property def project_type(self): return self.line_type.text() @property def description(self): return self._line_description.toPlainText() @property def url(self): return self._line_url.text() @property def license(self): return self._combo_license.currentText() @property def extensions(self): return list(map(str.strip, self._line_extensions.text().split(','))) @property def indentation(self): return self._spin_indentation.value() @property def use_tabs(self): return bool(self._combo_tabs_or_spaces.currentIndex()) class ProjectExecution(QWidget): """Project Execution widget class""" def __init__(self, parent): super(ProjectExecution, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(translations.TR_PROJECT_MAIN_FILE), 0, 0) # Main file self.path = QLineEdit() choose_main_file_action = QAction(self) choose_main_file_action.setIcon( self.style().standardIcon(self.style().SP_FileIcon)) choose_main_file_action.setToolTip( translations.TR_PROJECT_SELECT_MAIN_FILE) self.path.addAction( choose_main_file_action, QLineEdit.TrailingPosition) clear_main_file_action = self.path.addAction( self.style().standardIcon(self.style().SP_LineEditClearButton), QLineEdit.TrailingPosition) clear_main_file_action.triggered.connect(self.path.clear) self.path.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'main.py')) self.path.setText(self._parent.project.main_file) grid.addWidget(self.path, 0, 1) # this should be changed, and ALL pythonPath names to # python_custom_interpreter or something like that. this is NOT the # PYTHONPATH self.line_interpreter = QLineEdit() choose_interpreter = self.line_interpreter.addAction( self.style().standardIcon(self.style().SP_DirIcon), QLineEdit.TrailingPosition) self.line_interpreter.setText(self._parent.project.python_exec) completer = QCompleter(utils.get_python()) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setFilterMode(Qt.MatchContains) self.line_interpreter.setCompleter(completer) self.line_interpreter.setPlaceholderText("python") grid.addWidget(QLabel( translations.TR_PROJECT_PYTHON_INTERPRETER), 1, 0) grid.addWidget(self.line_interpreter, 1, 1) # PYTHONPATH grid.addWidget(QLabel(translations.TR_PROJECT_PYTHON_PATH), 2, 0) self.txt_python_path = QPlainTextEdit() # TODO : better widget self.txt_python_path.setPlainText(self._parent.project.python_path) self.txt_python_path.setToolTip(translations.TR_PROJECT_PATH_PER_LINE) grid.addWidget(self.txt_python_path, 2, 1) # Additional builtins/globals for pyflakes grid.addWidget(QLabel(translations.TR_PROJECT_BUILTINS), 3, 0) self.additional_builtins = QLineEdit() self.additional_builtins.setText( ' '.join(self._parent.project.additional_builtins)) self.additional_builtins.setToolTip( translations.TR_PROJECT_BUILTINS_TOOLTIP) grid.addWidget(self.additional_builtins, 3, 1) # Pre script self._line_pre_exec = QLineEdit() choose_pre_exec = QAction(self) choose_pre_exec.setToolTip( "Choose Script to execute before run project") choose_pre_exec.setIcon( self.style().standardIcon(self.style().SP_FileIcon)) self._line_pre_exec.addAction( choose_pre_exec, QLineEdit.TrailingPosition) clear_pre_action = self._line_pre_exec.addAction( self.style().standardIcon(self.style().SP_LineEditClearButton), QLineEdit.TrailingPosition) clear_pre_action.triggered.connect(self._line_pre_exec.clear) self._line_pre_exec.setReadOnly(True) self._line_pre_exec.setText(self._parent.project.pre_exec_script) self._line_pre_exec.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'script.sh')) grid.addWidget(QLabel(translations.TR_PROJECT_PRE_EXEC), 4, 0) grid.addWidget(self._line_pre_exec, 4, 1) # Post script self._line_post_exec = QLineEdit() choose_post_exec = QAction(self) choose_post_exec.setToolTip( "Choose script to execute after run project") choose_post_exec.setIcon( self.style().standardIcon(self.style().SP_FileIcon)) self._line_post_exec.addAction( choose_post_exec, QLineEdit.TrailingPosition) clear_post_action = self._line_post_exec.addAction( self.style().standardIcon(self.style().SP_LineEditClearButton), QLineEdit.TrailingPosition) clear_post_action.triggered.connect(self._line_post_exec.clear) self._line_post_exec.setReadOnly(True) self._line_post_exec.setText(self._parent.project.post_exec_script) self._line_post_exec.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'script.sh')) grid.addWidget(QLabel(translations.TR_PROJECT_POST_EXEC), 5, 0) grid.addWidget(self._line_post_exec, 5, 1) # grid.addItem(QSpacerItem(5, 10, QSizePolicy.Expanding, # QSizePolicy.Expanding), 6, 0) # Properties grid.addWidget(QLabel(translations.TR_PROJECT_PROPERTIES), 7, 0) self._line_params = QLineEdit() self._line_params.setToolTip(translations.TR_PROJECT_PARAMS_TOOLTIP) self._line_params.setText(self._parent.project.program_params) self._line_params.setPlaceholderText('verbose, debug, force') grid.addWidget(QLabel(translations.TR_PROJECT_PARAMS), 8, 0) grid.addWidget(self._line_params, 8, 1) # Widgets for virtualenv properties self.txtVenvPath = QLineEdit() # ui_tools.LineEditButton( # self.txtVenvPath, self.txtVenvPath.clear, # self.style().standardPixmap(self.style().SP_TrashIcon)) self.txtVenvPath.setText(self._parent.project.venv) self._dir_completer = QCompleter() self._dir_completer.setModel(QDirModel(self._dir_completer)) self.txtVenvPath.setCompleter(self._dir_completer) self.txtVenvPath.setPlaceholderText( os.path.join(os.path.expanduser("~"), 'path', 'to', 'virtualenv')) grid.addWidget(QLabel(translations.TR_PROJECT_VIRTUALENV), 9, 0) grid.addWidget(self.txtVenvPath, 9, 1) choose_main_file_action.triggered.connect(self.select_file) choose_interpreter.triggered.connect(self._load_python_path) choose_pre_exec.triggered.connect(self.select_pre_exec_script) choose_post_exec.triggered.connect(self.select_post_exec_script) # self.connect(self.btnPythonPath, SIGNAL("clicked()"), # self._load_python_path) # self.connect(self.btnVenvPath, SIGNAL("clicked()"), # self._load_python_venv) # self.connect(self.btnPreExec, SIGNAL("clicked()"), # self.select_pre_exec_script) # self.connect(self.btnPostExec, SIGNAL("clicked()"), # self.select_post_exec_script) @property def main_file(self): return self.path.text() @property def interpreter(self): return self.line_interpreter.text() @property def pre_script(self): return self._line_pre_exec.text() @property def post_script(self): return self._line_post_exec.text() @property def params(self): return self._line_params.text() def _load_python_path(self): """Ask the user a python path and set its value""" path_interpreter = QFileDialog.getOpenFileName( self, translations.TR_PROJECT_SELECT_PYTHON_PATH)[0] if path_interpreter: self.line_interpreter.setText(path_interpreter) def _load_python_venv(self): """Ask the user a python venv and set its value""" venv = QFileDialog.getExistingDirectory( self, translations.TR_PROJECT_SELECT_VIRTUALENV) if sys.platform == 'win32': venv = os.path.join(venv, 'Scripts', 'python.exe') else: venv = os.path.join(venv, 'bin', 'python') # check if venv folder exists if not os.path.exists(venv): QMessageBox.information( self, translations.TR_PROJECT_SELECT_VIRTUALENV_MESSAGE_TITLE, translations.TR_PROJECT_SELECT_VIRTUALENV_MESSAGE_BODY) self.txtVenvPath.setText("") else: self.txtVenvPath.setText(venv) def select_file(self): """Ask the user a python main file and set its value""" filename, _ = QFileDialog.getOpenFileName( self, translations.TR_PROJECT_SELECT_MAIN_FILE, self._parent.project.path, 'Python Files (*.py);;Python Bytecode (*.py[codw]);;All Files(*)') if filename: filename = file_manager.convert_to_relative( self._parent.project.path, filename) self.path.setText(filename) def select_pre_exec_script(self): """Ask the user a python pre-exec script and set its value""" filename = QFileDialog.getOpenFileName( self, translations.TR_PROJECT_SELECT_PRE_SCRIPT, self._parent.project.path, '*(*.*);;Bash(*.sh);;Python PY(*.py);;Python Bytecode(*.py[codw]);;' 'Bat(*.bat);;Cmd(*.cmd);;Exe(*.exe);;Bin(*.bin);;App(*.app)')[0] if filename: filename = file_manager.convert_to_relative( self._parent.project.path, filename) self._line_pre_exec.setText(filename) def select_post_exec_script(self): """Ask the user a python post-exec script and set its value""" filename = QFileDialog.getOpenFileName( self, translations.TR_PROJECT_SELECT_POST_SCRIPT, self._parent.project.path, '*(*.*);;Bash(*.sh);;Python PY(*.py);;Python Bytecode(*.py[codw]);;' 'Bat(*.bat);;Cmd(*.cmd);;Exe(*.exe);;Bin(*.bin);;App(*.app)')[0] if filename: filename = file_manager.convert_to_relative( self._parent.project.path, filename) self._line_post_exec.setText(filename) class ProjectMetadata(QWidget): """Project Metadata widget class""" def __init__(self, parent): super(ProjectMetadata, self).__init__() self._parent = parent vbox = QVBoxLayout(self) vbox.addWidget(QLabel(translations.TR_PROJECT_METADATA_RELATED)) self.txt_projects = QPlainTextEdit() vbox.addWidget(self.txt_projects) vbox.addWidget(QLabel(translations.TR_PROJECT_METADATA_TIP)) paths = '\n'.join(self._parent.project.related_projects) self.txt_projects.setPlainText(paths) self.txt_projects.setToolTip(translations.TR_PROJECT_PATH_PER_LINE)
21,995
Python
.py
444
40.968468
84
0.67394
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,562
__init__.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
692
Python
.py
16
42.25
70
0.760355
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,563
unsaved_files.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/unsaved_files.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QListWidget from PyQt5.QtWidgets import QListWidgetItem from PyQt5.QtWidgets import QDialogButtonBox from PyQt5.QtWidgets import QLabel from PyQt5.QtCore import Qt from ninja_ide import translations from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger(__name__) class UnsavedFilesDialog(QDialog): def __init__(self, unsaved_files, parent=None): super().__init__(parent) self._ninja = parent self.setWindowTitle(translations.TR_IDE_CONFIRM_EXIT_TITLE) vbox = QVBoxLayout(self) self._unsave_files_list = QListWidget() self._unsave_files_list.setSelectionMode(QListWidget.ExtendedSelection) vbox.addWidget(QLabel(translations.TR_IDE_CONFIRM_EXIT_BODY)) vbox.addWidget(self._unsave_files_list) button_box = QDialogButtonBox(self) standard_icon = self.style().standardIcon btn = button_box.addButton( translations.TR_CANCEL, QDialogButtonBox.RejectRole) btn.setIcon(standard_icon(self.style().SP_DialogCloseButton)) self._btn_save_selected = button_box.addButton( translations.TR_SAVE_SELECTED, QDialogButtonBox.AcceptRole) self._btn_save_selected.setIcon( standard_icon(self.style().SP_DialogSaveButton)) btn_save_all = button_box.addButton( translations.TR_SAVE_ALL, QDialogButtonBox.AcceptRole) btn_save_all.setIcon(standard_icon(self.style().SP_DialogApplyButton)) btn_donot_save = button_box.addButton( translations.TR_DONOT_SAVE, QDialogButtonBox.DestructiveRole) btn_donot_save.setIcon(standard_icon(self.style().SP_DialogNoButton)) vbox.addWidget(button_box) for nfile in unsaved_files: item = QListWidgetItem(nfile.display_name) item.setData(Qt.UserRole, nfile) item.setToolTip(nfile.file_path) self._unsave_files_list.addItem(item) # Connections button_box.rejected.connect(self.reject) button_box.accepted.connect(self._save_selected) btn_donot_save.clicked.connect(self._discard) btn_save_all.clicked.connect(self._save_all) self._unsave_files_list.itemSelectionChanged.connect( self._on_selection_changed) self._unsave_files_list.selectAll() def _on_selection_changed(self): value = True if not self._unsave_files_list.selectedItems(): value = False self._btn_save_selected.setEnabled(value) def _save_selected(self): logger.debug("Saving selected unsaved files") self.__save() def __save(self): """Collect all selected items and save""" items_to_save = [] for item in self._unsave_files_list.selectedItems(): nfile = item.data(Qt.UserRole) items_to_save.append(nfile) self._ninja._save_unsaved_files(items_to_save) self.accept() def _save_all(self): """Select all items in the list and save""" logger.debug("Saving all unsaved files") for index in range(self._unsave_files_list.count()): item = self._unsave_files_list.item(index) item.setSelected(True) self.__save() def _discard(self): logger.debug("Discarding all unsaved files") self.accept()
4,135
Python
.py
91
38.197802
79
0.694334
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,564
wizard_new_project.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/wizard_new_project.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. # Get project types # Project type is language # Should have subtype, which is pyqt, ninja plugin, pytk, etc... # We provide the first window of the wizard, to do this everyone will inherit # from us from PyQt4.QtGui import QDialog from PyQt4.QtCore import Qt class NewProjectTypeChooser(QDialog): def __init__(self, parent=None): super(NewProjectTypeChooser, self).__init__(parent, Qt.Dialog) pass
1,117
Python
.py
27
39.407407
77
0.755535
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,565
language_manager.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/language_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os try: from urllib.request import urlopen from urllib.error import URLError except ImportError: from urllib2 import urlopen from urllib2 import URLError from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QSpacerItem from PyQt5.QtWidgets import QSizePolicy from PyQt5.QtWidgets import QTabWidget from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QDialog from PyQt5.QtCore import Qt from PyQt5.QtCore import QObject from ninja_ide import resources from ninja_ide.core.file_handling import file_manager from ninja_ide.tools import ui_tools from ninja_ide.tools import json_manager class LanguagesManagerWidget(QDialog): def __init__(self, parent): QDialog.__init__(self, parent, Qt.Dialog) self.setWindowTitle(self.tr("Language Manager")) self.resize(700, 500) vbox = QVBoxLayout(self) self._tabs = QTabWidget() vbox.addWidget(self._tabs) # Footer hbox = QHBoxLayout() btn_close = QPushButton(self.tr('Close')) btnReload = QPushButton(self.tr("Reload")) hbox.addWidget(btn_close) hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox.addWidget(btnReload) vbox.addLayout(hbox) self.overlay = ui_tools.Overlay(self) self.overlay.show() self._languages = [] self._loading = True self.downloadItems = [] # Load Themes with Thread btnReload.clicked.connect(self._reload_languages) self._thread = ui_tools.ThreadExecution(self.execute_thread) self._thread.finished.connect(self.load_languages_data) btn_close.clicked.connect(self.close) self._reload_languages() def _reload_languages(self): self.overlay.show() self._loading = True self._thread.execute = self.execute_thread self._thread.start() def load_languages_data(self): if self._loading: self._tabs.clear() self._languageWidget = LanguageWidget(self, self._languages) self._tabs.addTab(self._languageWidget, self.tr("Languages")) self._loading = False self.overlay.hide() self._thread.wait() def download_language(self, language): self.overlay.show() self.downloadItems = language self._thread.execute = self._download_language_thread self._thread.start() def resizeEvent(self, event): self.overlay.resize(event.size()) event.accept() def execute_thread(self): try: descriptor_languages = urlopen(resources.LANGUAGES_URL) languages = json_manager.parse(descriptor_languages) languages = [[name, languages[name]] for name in languages] local_languages = self.get_local_languages() languages = [languages[i] for i in range(len(languages)) if os.path.basename(languages[i][1]) not in local_languages] self._languages = languages except URLError: self._languages = [] def get_local_languages(self): if not file_manager.folder_exists(resources.LANGS_DOWNLOAD): file_manager.create_tree_folders(resources.LANGS_DOWNLOAD) languages = os.listdir(resources.LANGS_DOWNLOAD) + \ os.listdir(resources.LANGS) languages = [s for s in languages if s.lower().endswith('.qm')] return languages def _download_language_thread(self): for d in self.downloadItems: self.download(d[1], resources.LANGS_DOWNLOAD) def download(self, url, folder): fileName = os.path.join(folder, os.path.basename(url)) try: content = urlopen(url) with open(fileName, 'wb') as f: f.write(content.read()) except URLError: return class LanguageWidget(QWidget): def __init__(self, parent, languages): QWidget.__init__(self, parent) self._parent = parent self._languages = languages vbox = QVBoxLayout(self) self._table = ui_tools.CheckableHeaderTable(1, 2) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, [self.tr('Language'), self.tr('URL')], self._languages) btnUninstall = QPushButton(self.tr('Download')) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self._table.setColumnWidth(0, 200) self._table.setSortingEnabled(True) self._table.setAlternatingRowColors(True) btnUninstall.clicked.connect(self._download_language) def _download_language(self): languages = ui_tools.remove_get_selected_items(self._table, self._languages) self._parent.download_language(languages)
5,710
Python
.py
137
33.678832
83
0.665706
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,566
preferences_execution.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_execution.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os import sys from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QSizePolicy, QSpacerItem, QFileDialog, QGroupBox, QLabel, QCheckBox, QLineEdit, QCompleter, QRadioButton, QButtonGroup, QPushButton, QDirModel, QCompleter, QComboBox ) from PyQt5.QtCore import ( QDir, pyqtSlot ) from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.tools import utils class GeneralExecution(QWidget): """General Execution widget class""" def __init__(self, parent): super().__init__() self._preferences = parent box = QVBoxLayout(self) group_python_path = QGroupBox(translations.TR_WORKSPACE_PROJECTS) group_python_opt = QGroupBox(translations.TR_PYTHON_OPTIONS) vbox = QVBoxLayout(group_python_path) box_path = QVBoxLayout() # Line python path hbox_path = QHBoxLayout() self._combo_python_path = QComboBox() self._combo_python_path.setEditable(True) self._combo_python_path.addItems(utils.get_python()) hbox_path.addWidget(self._combo_python_path) self._combo_python_path.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed) btn_choose_path = QPushButton( self.style().standardIcon(self.style().SP_DirIcon), '') box_path.addWidget( QLabel( translations.TR_PREFERENCES_EXECUTION_PYTHON_INTERPRETER_LBL)) hbox_path.addWidget(btn_choose_path) box_path.addLayout(hbox_path) vbox.addLayout(box_path) # Python Miscellaneous Execution options vbox_opts = QVBoxLayout(group_python_opt) self._check_B = QCheckBox(translations.TR_SELECT_EXEC_OPTION_B) self._check_d = QCheckBox(translations.TR_SELECT_EXEC_OPTION_D) self._check_E = QCheckBox(translations.TR_SELECT_EXEC_OPTION_E) self._check_O = QCheckBox(translations.TR_SELECT_EXEC_OPTION_O) self._check_OO = QCheckBox(translations.TR_SELECT_EXEC_OPTION_OO) self._check_s = QCheckBox(translations.TR_SELECT_EXEC_OPTION_s) self._check_S = QCheckBox(translations.TR_SELECT_EXEC_OPTION_S) self._check_v = QCheckBox(translations.TR_SELECT_EXEC_OPTION_V) hbox = QHBoxLayout() self._check_W = QCheckBox(translations.TR_SELECT_EXEC_OPTION_W) self._combo_warning = QComboBox() self._combo_warning.addItems([ "default", "ignore", "all", "module", "once", "error" ]) self._check_W.stateChanged.connect( lambda state: self._combo_warning.setEnabled(bool(state))) vbox_opts.addWidget(self._check_B) vbox_opts.addWidget(self._check_d) vbox_opts.addWidget(self._check_E) vbox_opts.addWidget(self._check_O) vbox_opts.addWidget(self._check_OO) vbox_opts.addWidget(self._check_s) vbox_opts.addWidget(self._check_S) vbox_opts.addWidget(self._check_v) hbox.addWidget(self._check_W) hbox.addWidget(self._combo_warning) vbox_opts.addLayout(hbox) """ completer = QCompleter(self) dirs = QDirModel(self) dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) completer.setModel(dirs) self._txt_python_path.setCompleter(completer) box_path.addWidget(default_interpreter_radio) box_path.addWidget(custom_interpreter_radio) """ box.addWidget(group_python_path) box.addWidget(group_python_opt) box.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Settings self._combo_python_path.setCurrentText(settings.PYTHON_EXEC) options = settings.EXECUTION_OPTIONS.split() if "-B" in options: self._check_B.setChecked(True) if "-d" in options: self._check_d.setChecked(True) if "-E" in options: self._check_E.setChecked(True) if "-O" in options: self._check_O.setChecked(True) if "-OO" in options: self._check_OO.setChecked(True) if "-S" in options: self._check_S.setChecked(True) if "-s" in options: self._check_s.setChecked(True) if "-v" in options: self._check_v.setChecked(True) if settings.EXECUTION_OPTIONS.find("-W") > -1: self._check_W.setChecked(True) index = settings.EXECUTION_OPTIONS.find("-W") opt = settings.EXECUTION_OPTIONS[index + 2:].strip() index = self._combo_warning.findText(opt) self._combo_warning.setCurrentIndex(index) # Connections self._preferences.savePreferences.connect(self.save) btn_choose_path.clicked.connect(self._load_python_path) @pyqtSlot() def _load_python_path(self): """Ask the user for a Python Path""" path = QFileDialog.getOpenFileName( self, translations.TR_SELECT_SELECT_PYTHON_EXEC)[0] if path: self._combo_python_path.setEditText(path) def save(self): """Save all Execution Preferences""" qsettings = IDE.ninja_settings() qsettings.beginGroup("execution") # Python executable settings.PYTHON_EXEC = self._combo_python_path.currentText() qsettings.setValue("pythonExec", settings.PYTHON_EXEC) # Execution options options = "" if self._check_B.isChecked(): options += " -B" if self._check_d.isChecked(): options += " -d" if self._check_E.isChecked(): options += " -E" if self._check_O.isChecked(): options += " -O" if self._check_OO.isChecked(): options += " -OO" if self._check_s.isChecked(): options += " -s" if self._check_S.isChecked(): options += " -S" if self._check_v.isChecked(): options += " -v" if self._check_W.isChecked(): options += " -W" + self._combo_warning.currentText() settings.EXECUTION_OPTIONS = options qsettings.setValue("executionOptions", options) qsettings.endGroup() preferences.Preferences.register_configuration( 'GENERAL', GeneralExecution, translations.TR_PREFERENCES_EXECUTION, weight=1, subsection='EXECUTION' ) """ from __future__ import absolute_import from __future__ import unicode_literals from PyQt4.QtGui import QWidget from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QGroupBox from PyQt4.QtGui import QCheckBox from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QFileDialog from PyQt4.QtGui import QLineEdit from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QLabel from PyQt4.QtGui import QComboBox from PyQt4.QtGui import QIcon from PyQt4.QtGui import QCompleter from PyQt4.QtGui import QDirModel from PyQt4.QtCore import SIGNAL from PyQt4.QtCore import QDir from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences class GeneralExecution(QWidget): # General Execution widget class def __init__(self, parent): super(GeneralExecution, self).__init__() self._preferences = parent vbox = QVBoxLayout(self) groupExecution = QGroupBox(translations.TR_WORKSPACE_PROJECTS) grid = QVBoxLayout(groupExecution) #Python Path hPath = QHBoxLayout() self._txtPythonPath = QLineEdit() self._btnPythonPath = QPushButton(QIcon(':img/open'), '') self.completer, self.dirs = QCompleter(self), QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self._txtPythonPath.setCompleter(self.completer) hPath.addWidget(QLabel(translations.TR_SELECT_PYTHON_EXEC)) hPath.addWidget(self._txtPythonPath) hPath.addWidget(self._btnPythonPath) grid.addLayout(hPath) #Python Miscellaneous Execution options self.check_B = QCheckBox(translations.TR_SELECT_EXEC_OPTION_B) self.check_d = QCheckBox(translations.TR_SELECT_EXEC_OPTION_D) self.check_E = QCheckBox(translations.TR_SELECT_EXEC_OPTION_E) self.check_O = QCheckBox(translations.TR_SELECT_EXEC_OPTION_O) self.check_OO = QCheckBox(translations.TR_SELECT_EXEC_OPTION_OO) self.check_Q = QCheckBox(translations.TR_SELECT_EXEC_OPTION_Q) self.comboDivision = QComboBox() self.comboDivision.addItems(['old', 'new', 'warn', 'warnall']) self.check_s = QCheckBox(translations.TR_SELECT_EXEC_OPTION_s) self.check_S = QCheckBox(translations.TR_SELECT_EXEC_OPTION_S) self.check_t = QCheckBox(translations.TR_SELECT_EXEC_OPTION_T) self.check_tt = QCheckBox(translations.TR_SELECT_EXEC_OPTION_TT) self.check_v = QCheckBox(translations.TR_SELECT_EXEC_OPTION_V) self.check_W = QCheckBox(translations.TR_SELECT_EXEC_OPTION_W) self.comboWarning = QComboBox() self.comboWarning.addItems( ['default', 'ignore', 'all', 'module', 'once', 'error']) self.check_x = QCheckBox(translations.TR_SELECT_EXEC_OPTION_X) self.check_3 = QCheckBox(translations.TR_SELECT_EXEC_OPTION_3) grid.addWidget(self.check_B) grid.addWidget(self.check_d) grid.addWidget(self.check_E) grid.addWidget(self.check_O) grid.addWidget(self.check_OO) hDiv = QHBoxLayout() hDiv.addWidget(self.check_Q) hDiv.addWidget(self.comboDivision) grid.addLayout(hDiv) grid.addWidget(self.check_s) grid.addWidget(self.check_S) grid.addWidget(self.check_t) grid.addWidget(self.check_tt) grid.addWidget(self.check_v) hWarn = QHBoxLayout() hWarn.addWidget(self.check_W) hWarn.addWidget(self.comboWarning) grid.addLayout(hWarn) grid.addWidget(self.check_x) grid.addWidget(self.check_3) #Settings self._txtPythonPath.setText(settings.PYTHON_EXEC) options = settings.EXECUTION_OPTIONS.split() if '-B' in options: self.check_B.setChecked(True) if '-d' in options: self.check_d.setChecked(True) if '-E' in options: self.check_E.setChecked(True) if '-O' in options: self.check_O.setChecked(True) if '-OO' in options: self.check_OO.setChecked(True) if settings.EXECUTION_OPTIONS.find('-Q') > -1: self.check_Q.setChecked(True) index = settings.EXECUTION_OPTIONS.find('-Q') opt = settings.EXECUTION_OPTIONS[index + 2:].split(' ', 1)[0] index = self.comboDivision.findText(opt) self.comboDivision.setCurrentIndex(index) if '-s' in options: self.check_s.setChecked(True) if '-S' in options: self.check_S.setChecked(True) if '-t' in options: self.check_t.setChecked(True) if '-tt' in options: self.check_tt.setChecked(True) if '-v' in options: self.check_v.setChecked(True) if settings.EXECUTION_OPTIONS.find('-W') > -1: self.check_W.setChecked(True) index = settings.EXECUTION_OPTIONS.find('-W') opt = settings.EXECUTION_OPTIONS[index + 2:].split(' ', 1)[0] index = self.comboWarning.findText(opt) self.comboWarning.setCurrentIndex(index) if '-x' in options: self.check_x.setChecked(True) if '-3' in options: self.check_3.setChecked(True) vbox.addWidget(groupExecution) #Signals self.connect(self._btnPythonPath, SIGNAL("clicked()"), self._load_python_path) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def _load_python_path(self): # Ask the user for a Python Path path = QFileDialog.getOpenFileName(self, translations.TR_SELECT_SELECT_PYTHON_EXEC) if path: self._txtPythonPath.setText(path) def save(self): # Save all the Execution Preferences qsettings = IDE.ninja_settings() qsettings.beginGroup('preferences') qsettings.beginGroup('execution') qsettings.setValue('pythonPath', self._txtPythonPath.text()) settings.PYTHON_PATH = self._txtPythonPath.text() options = '' if self.check_B.isChecked(): options += ' -B' if self.check_d.isChecked(): options += ' -d' if self.check_E.isChecked(): options += ' -E' if self.check_O.isChecked(): options += ' -O' if self.check_OO.isChecked(): options += ' -OO' if self.check_Q.isChecked(): options += ' -Q' + self.comboDivision.currentText() if self.check_s.isChecked(): options += ' -s' if self.check_S.isChecked(): options += ' -S' if self.check_t.isChecked(): options += ' -t' if self.check_tt.isChecked(): options += ' -tt' if self.check_v.isChecked(): options += ' -v' if self.check_W.isChecked(): options += ' -W' + self.comboWarning.currentText() if self.check_x.isChecked(): options += ' -x' if self.check_3.isChecked(): options += ' -3' settings.EXECUTION_OPTIONS = options qsettings.setValue('executionOptions', options) qsettings.endGroup() qsettings.endGroup() preferences.Preferences.register_configuration('GENERAL', GeneralExecution, translations.TR_PREFERENCES_EXECUTION, weight=1, subsection='EXECUTION') """
14,718
Python
.py
362
32.348066
79
0.64565
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,567
preferences_plugins.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_plugins.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from PyQt4.QtGui import QWidget from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QLabel from PyQt4.QtCore import SIGNAL from ninja_ide import translations from ninja_ide.gui.dialogs.preferences import preferences class Plugins(QWidget): """Plugins widget class.""" def __init__(self, parent): super(Plugins, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) label = QLabel(translations.TR_PREFERENCES_PLUGINS_MAIN) vbox.addWidget(label) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def save(self): pass preferences.Preferences.register_configuration( 'PLUGINS', Plugins, translations.TR_PREFERENCES_PLUGINS, preferences.SECTIONS['PLUGINS'])
1,556
Python
.py
39
36.666667
79
0.750332
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,568
preferences_shortcuts.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_shortcuts.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QTreeWidget from PyQt4.QtGui import QTreeWidgetItem from PyQt4.QtGui import QDialog from PyQt4.QtGui import QWidget from PyQt4.QtGui import QLabel from PyQt4.QtGui import QLineEdit from PyQt4.QtGui import QKeySequence from PyQt4.QtGui import QMessageBox from PyQt4.QtCore import SIGNAL from PyQt4.QtCore import Qt from PyQt4.QtCore import QEvent from ninja_ide import resources from ninja_ide.gui import actions from ninja_ide import translations from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences class TreeResult(QTreeWidget): """Tree Results widget Class""" def __init__(self): QTreeWidget.__init__(self) self.setHeaderLabels((translations.TR_PROJECT_DESCRIPTION, translations.TR_SHORTCUT)) # columns width self.setColumnWidth(0, 175) self.header().setStretchLastSection(True) self.setSortingEnabled(True) self.sortByColumn(0, Qt.AscendingOrder) class ShortcutDialog(QDialog): """ Dialog to set a shortcut for an action this class emit the follow signals: shortcutChanged(QKeySequence) """ def __init__(self, parent): super(ShortcutDialog, self).__init__() self.keys = 0 # Keyword modifiers! self.keyword_modifiers = (Qt.Key_Control, Qt.Key_Meta, Qt.Key_Shift, Qt.Key_Alt, Qt.Key_Menu) # main layout main_vbox = QVBoxLayout(self) self.line_edit = QLineEdit() self.line_edit.setReadOnly(True) # layout for buttons buttons_layout = QHBoxLayout() ok_button = QPushButton(translations.TR_ACCEPT) cancel_button = QPushButton(translations.TR_CANCEL) # add widgets main_vbox.addWidget(self.line_edit) buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) main_vbox.addLayout(buttons_layout) self.line_edit.installEventFilter(self) # buttons signals self.connect(ok_button, SIGNAL("clicked()"), self.save_shortcut) self.connect(cancel_button, SIGNAL("clicked()"), self.close) def save_shortcut(self): """Save a new Shortcut""" self.hide() shortcut = QKeySequence(self.line_edit.text()) self.emit(SIGNAL('shortcutChanged'), shortcut) def set_shortcut(self, txt): """Setup a shortcut""" self.line_edit.setText(txt) def eventFilter(self, watched, event): """Event Filter handling""" if event.type() == QEvent.KeyPress: self.keyPressEvent(event) return True return False def keyPressEvent(self, evt): """Key Press handling""" # modifier can not be used as shortcut if evt.key() in self.keyword_modifiers: return # save the key if evt.key() == Qt.Key_Backtab and evt.modifiers() & Qt.ShiftModifier: self.keys = Qt.Key_Tab else: self.keys = evt.key() if evt.modifiers() & Qt.ShiftModifier: self.keys += Qt.SHIFT if evt.modifiers() & Qt.ControlModifier: self.keys += Qt.CTRL if evt.modifiers() & Qt.AltModifier: self.keys += Qt.ALT if evt.modifiers() & Qt.MetaModifier: self.keys += Qt.META # set the keys self.set_shortcut(QKeySequence(self.keys).toString()) class ShortcutConfiguration(QWidget): """ Dialog to manage ALL shortcuts """ def __init__(self, parent): super(ShortcutConfiguration, self).__init__() self._preferences = parent self.shortcuts_text = { "Show-Selector": translations.TR_SHOW_SELECTOR, "cut": translations.TR_CUT, "Indent-more": translations.TR_INDENT_MORE, "expand-file-combo": translations.TR_EXPAND_FILE_COMBO, "expand-symbol-combo": translations.TR_EXPAND_SYMBOL_COMBO, "undo": translations.TR_UNDO, "Close-Split": translations.TR_CLOSE_SPLIT, "Split-assistance": translations.TR_SHOW_SPLIT_ASSISTANCE, "copy": translations.TR_COPY, "paste": translations.TR_PASTE, "Duplicate": translations.TR_DUPLICATE_SELECTION, "Remove-line": translations.TR_REMOVE_LINE_SELECTION, "Move-up": translations.TR_MOVE_LINE_SELECTION_UP, "Move-down": translations.TR_MOVE_LINE_SELECTION_DOWN, "Close-file": translations.TR_CLOSE_CURRENT_TAB, "New-file": translations.TR_NEW_TAB, "New-project": translations.TR_NEW_PROJECT, "Open-file": translations.TR_OPEN_A_FILE, "Open-project": translations.TR_OPEN_PROJECT, "Save-file": translations.TR_SAVE_FILE, "Save-project": translations.TR_SAVE_OPENED_FILES, "Print-file": translations.TR_PRINT_FILE, "Redo": translations.TR_REDO, "Comment": translations.TR_COMMENT_SELECTION, "Uncomment": translations.TR_UNCOMMENT_SELECTION, "Horizontal-line": translations.TR_INSERT_HORIZONTAL_LINE, "Title-comment": translations.TR_INSERT_TITLE_COMMENT, "Indent-less": translations.TR_INDENT_LESS, "Hide-misc": translations.TR_HIDE_MISC, "Hide-editor": translations.TR_HIDE_EDITOR, "Hide-explorer": translations.TR_HIDE_EXPLORER, "Toggle-tabs-spaces": translations.TR_TOGGLE_TABS, "Run-file": translations.TR_RUN_FILE, "Run-project": translations.TR_RUN_PROJECT, "Debug": translations.TR_DEBUG, "Switch-Focus": translations.TR_SWITCH_FOCUS, "Stop-execution": translations.TR_STOP_EXECUTION, "Hide-all": translations.TR_HIDE_ALL, "Full-screen": translations.TR_FULLSCREEN, "Find": translations.TR_FIND, "Find-replace": translations.TR_FIND_REPLACE, "Find-with-word": translations.TR_FIND_WORD_UNDER_CURSOR, "Find-next": translations.TR_FIND_NEXT, "Find-previous": translations.TR_FIND_PREVIOUS, "Help": translations.TR_SHOW_PYTHON_HELP, "Split-vertical": translations.TR_SPLIT_TABS_VERTICAL, "Split-horizontal": translations.TR_SPLIT_TABS_HORIZONTAL, "Follow-mode": translations.TR_ACTIVATE_FOLLOW_MODE, "Reload-file": translations.TR_RELOAD_FILE, "Jump": translations.TR_JUMP_TO_LINE, "Find-in-files": translations.TR_FIND_IN_FILES, "Import": translations.TR_IMPORT_FROM_EVERYWHERE, "Go-to-definition": translations.TR_GO_TO_DEFINITION, "Complete-Declarations": translations.TR_COMPLETE_DECLARATIONS, "Code-locator": translations.TR_SHOW_CODE_LOCATOR, "File-Opener": translations.TR_SHOW_FILE_OPENER, "Navigate-back": translations.TR_NAVIGATE_BACK, "Navigate-forward": translations.TR_NAVIGATE_FORWARD, "Open-recent-closed": translations.TR_OPEN_RECENT_CLOSED_FILE, "Change-Tab": translations.TR_CHANGE_TO_NEXT_TAB, "Change-Tab-Reverse": translations.TR_CHANGE_TO_PREVIOUS_TAB, "Move-Tab-to-right": translations.TR_MOVE_TAB_TO_RIGHT, "Move-Tab-to-left": translations.TR_MOVE_TAB_TO_LEFT, "Show-Code-Nav": translations.TR_ACTIVATE_HISTORY_NAVIGATION, "Show-Bookmarks-Nav": translations.TR_ACTIVATE_BOOKMARKS_NAVIGATION, "Show-Breakpoints-Nav": translations.TR_ACTIVATE_BREAKPOINTS_NAVIGATION, "Show-Paste-History": translations.TR_SHOW_COPYPASTE_HISTORY, "History-Copy": translations.TR_COPY_TO_HISTORY, "History-Paste": translations.TR_PASTE_FROM_HISTORY, # "change-split-focus": # translations.TR_CHANGE_KEYBOARD_FOCUS_BETWEEN_SPLITS, "Add-Bookmark-or-Breakpoint": translations.TR_INSERT_BREAKPOINT, "move-tab-to-next-split": translations.TR_MOVE_TAB_TO_NEXT_SPLIT, "change-tab-visibility": translations.TR_SHOW_TABS_IN_EDITOR, "Highlight-Word": translations.TR_HIGHLIGHT_OCCURRENCES } self.shortcut_dialog = ShortcutDialog(self) # main layout main_vbox = QVBoxLayout(self) # layout for buttons buttons_layout = QVBoxLayout() # widgets self.result_widget = TreeResult() load_defaults_button = QPushButton(translations.TR_LOAD_DEFAULTS) # add widgets main_vbox.addWidget(self.result_widget) buttons_layout.addWidget(load_defaults_button) main_vbox.addLayout(buttons_layout) main_vbox.addWidget(QLabel( translations.TR_SHORTCUTS_ARE_GOING_TO_BE_REFRESH)) # load data! self.result_widget.setColumnWidth(0, 400) self._load_shortcuts() # signals # open the set shortcut dialog self.connect(self.result_widget, SIGNAL("itemDoubleClicked(QTreeWidgetItem*, int)"), self._open_shortcut_dialog) # load defaults shortcuts self.connect(load_defaults_button, SIGNAL("clicked()"), self._load_defaults_shortcuts) # one shortcut has changed self.connect(self.shortcut_dialog, SIGNAL('shortcutChanged'), self._shortcut_changed) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def _shortcut_changed(self, keysequence): """ Validate and set a new shortcut """ if self.__validate_shortcut(keysequence): self.result_widget.currentItem().setText(1, keysequence.toString()) def __validate_shortcut(self, keysequence): """ Validate a shortcut """ if keysequence.isEmpty(): return True keyname = self.result_widget.currentItem().text(0) keystr = keysequence for top_index in range(self.result_widget.topLevelItemCount()): top_item = self.result_widget.topLevelItem(top_index) if top_item.text(0) != keyname: itmseq = top_item.text(1) if keystr == itmseq: val = QMessageBox.warning(self, translations.TR_SHORTCUT_ALREADY_ON_USE, translations.TR_DO_YOU_WANT_TO_REMOVE, QMessageBox.Yes, QMessageBox.No) if val == QMessageBox.Yes: top_item.setText(1, "") return True else: return False if not itmseq: continue return True def _open_shortcut_dialog(self, item, column): """ Open the dialog to set a shortcut """ if item.childCount(): return self.shortcut_dialog.set_shortcut( QKeySequence(item.text(1)).toString()) self.shortcut_dialog.exec_() def save(self): """ Save all shortcuts to settings """ settings = IDE.ninja_settings() settings.beginGroup("shortcuts") for index in range(self.result_widget.topLevelItemCount()): item = self.result_widget.topLevelItem(index) shortcut_keys = item.text(1) shortcut_name = item.text(2) settings.setValue(shortcut_name, shortcut_keys) settings.endGroup() def _load_shortcuts(self): """Method to load all custom shortcuts""" for action in resources.CUSTOM_SHORTCUTS: shortcut_action = resources.get_shortcut(action) # populate the tree widget tree_data = [self.shortcuts_text[action], shortcut_action.toString(QKeySequence.NativeText), action] item = QTreeWidgetItem(self.result_widget, tree_data) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) def _load_defaults_shortcuts(self): """Method to load the default builtin shortcuts""" # clean custom shortcuts and UI widget resources.clean_custom_shortcuts() self.result_widget.clear() for name, action in list(resources.SHORTCUTS.items()): shortcut_action = action # populate the tree widget tree_data = [self.shortcuts_text[name], shortcut_action.toString(QKeySequence.NativeText), name] item = QTreeWidgetItem(self.result_widget, tree_data) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) preferences.Preferences.register_configuration('GENERAL', ShortcutConfiguration, translations.TR_PREFERENCES_SHORTCUTS, weight=2, subsection='SHORTCUTS')
13,905
Python
.py
300
35.65
86
0.629965
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,569
preferences_theme.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_theme.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from PyQt4.QtGui import QWidget from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QApplication from PyQt4.QtGui import QListWidget from PyQt4.QtGui import QLabel from PyQt4.QtGui import QSizePolicy from PyQt4.QtGui import QSpacerItem from PyQt4.QtGui import QPushButton from PyQt4.QtCore import SIGNAL from ninja_ide import resources from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences from ninja_ide.gui.dialogs.preferences import preferences_theme_editor class Theme(QWidget): """Theme widget class.""" def __init__(self, parent): super(Theme, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) vbox.addWidget(QLabel(self.tr("<b>Select Theme:</b>"))) self.list_skins = QListWidget() self.list_skins.setSelectionMode(QListWidget.SingleSelection) vbox.addWidget(self.list_skins) self.btn_delete = QPushButton(self.tr("Delete Theme")) self.btn_preview = QPushButton(self.tr("Preview Theme")) self.btn_create = QPushButton(self.tr("Create Theme")) hbox = QHBoxLayout() hbox.addWidget(self.btn_delete) hbox.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding, QSizePolicy.Fixed)) hbox.addWidget(self.btn_preview) hbox.addWidget(self.btn_create) vbox.addLayout(hbox) self._refresh_list() self.connect(self.btn_preview, SIGNAL("clicked()"), self.preview_theme) self.connect(self.btn_delete, SIGNAL("clicked()"), self.delete_theme) self.connect(self.btn_create, SIGNAL("clicked()"), self.create_theme) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def delete_theme(self): if self.list_skins.currentRow() != 0: file_name = ("%s.qss" % self.list_skins.currentItem().text()) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) file_manager.delete_file(qss_file) self._refresh_list() def create_theme(self): designer = preferences_theme_editor.ThemeEditor(self) designer.exec_() self._refresh_list() def showEvent(self, event): self._refresh_list() super(Theme, self).showEvent(event) def _refresh_list(self): self.list_skins.clear() self.list_skins.addItem("Default") files = sorted([file_manager.get_file_name(filename) for filename in file_manager.get_files_from_folder( resources.NINJA_THEME_DOWNLOAD, "qss")]) self.list_skins.addItems(files) if settings.NINJA_SKIN in files: index = files.index(settings.NINJA_SKIN) self.list_skins.setCurrentRow(index + 1) else: self.list_skins.setCurrentRow(0) def save(self): qsettings = IDE.ninja_settings() settings.NINJA_SKIN = self.list_skins.currentItem().text() qsettings.setValue("preferences/theme/skin", settings.NINJA_SKIN) self.preview_theme() def preview_theme(self): if self.list_skins.currentRow() == 0: qss_file = resources.NINJA_THEME else: file_name = ("%s.qss" % self.list_skins.currentItem().text()) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) with open(qss_file) as f: qss = f.read() QApplication.instance().setStyleSheet(qss) preferences.Preferences.register_configuration( 'THEME', Theme, translations.TR_PREFERENCES_THEME, preferences.SECTIONS['THEME'])
4,677
Python
.py
105
37.085714
79
0.678673
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,570
preferences_editor_completion.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_editor_completion.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from PyQt4.QtGui import QWidget from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QGroupBox from PyQt4.QtGui import QCheckBox from PyQt4.QtGui import QGridLayout from PyQt4.QtGui import QSpacerItem from PyQt4.QtGui import QSizePolicy from PyQt4.QtGui import QKeySequence from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from ninja_ide import translations from ninja_ide import resources from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences class EditorCompletion(QWidget): def __init__(self, parent): super(EditorCompletion, self).__init__() self._preferences = parent vbox = QVBoxLayout(self) groupBoxClose = QGroupBox(translations.TR_PREF_EDITOR_COMPLETE) formClose = QGridLayout(groupBoxClose) formClose.setContentsMargins(5, 15, 5, 5) self._checkParentheses = QCheckBox( translations.TR_PREF_EDITOR_PARENTHESES + " ()") self._checkParentheses.setChecked('(' in settings.BRACES) self._checkKeys = QCheckBox(translations.TR_PREF_EDITOR_KEYS + " {}") self._checkKeys.setChecked('{' in settings.BRACES) self._checkBrackets = QCheckBox( translations.TR_PREF_EDITOR_BRACKETS + " []") self._checkBrackets.setChecked('[' in settings.BRACES) self._checkSimpleQuotes = QCheckBox( translations.TR_PREF_EDITOR_SIMPLE_QUOTES) self._checkSimpleQuotes.setChecked("'" in settings.QUOTES) self._checkDoubleQuotes = QCheckBox( translations.TR_PREF_EDITOR_DOUBLE_QUOTES) self._checkDoubleQuotes.setChecked('"' in settings.QUOTES) self._checkCompleteDeclarations = QCheckBox( translations.TR_PREF_EDITOR_COMPLETE_DECLARATIONS.format( resources.get_shortcut("Complete-Declarations").toString( QKeySequence.NativeText))) self._checkCompleteDeclarations.setChecked( settings.COMPLETE_DECLARATIONS) formClose.addWidget(self._checkParentheses, 1, 1, alignment=Qt.AlignTop) formClose.addWidget(self._checkKeys, 1, 2, alignment=Qt.AlignTop) formClose.addWidget(self._checkBrackets, 2, 1, alignment=Qt.AlignTop) formClose.addWidget(self._checkSimpleQuotes, 2, 2, alignment=Qt.AlignTop) formClose.addWidget(self._checkDoubleQuotes, 3, 1, alignment=Qt.AlignTop) vbox.addWidget(groupBoxClose) groupBoxCode = QGroupBox(translations.TR_PREF_EDITOR_CODE_COMPLETION) formCode = QGridLayout(groupBoxCode) formCode.setContentsMargins(5, 15, 5, 5) self._checkCodeDot = QCheckBox( translations.TR_PREF_EDITOR_ACTIVATE_COMPLETION) self._checkCodeDot.setChecked(settings.CODE_COMPLETION) formCode.addWidget(self._checkCompleteDeclarations, 5, 1, alignment=Qt.AlignTop) formCode.addWidget(self._checkCodeDot, 6, 1, alignment=Qt.AlignTop) vbox.addWidget(groupBoxCode) vbox.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding)) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def save(self): qsettings = IDE.ninja_settings() if self._checkParentheses.isChecked(): settings.BRACES['('] = ')' elif ('(') in settings.BRACES: del settings.BRACES['('] qsettings.setValue('preferences/editor/parentheses', self._checkParentheses.isChecked()) if self._checkBrackets.isChecked(): settings.BRACES['['] = ']' elif ('[') in settings.BRACES: del settings.BRACES['['] qsettings.setValue('preferences/editor/brackets', self._checkBrackets.isChecked()) if self._checkKeys.isChecked(): settings.BRACES['{'] = '}' elif ('{') in settings.BRACES: del settings.BRACES['{'] qsettings.setValue('preferences/editor/keys', self._checkKeys.isChecked()) if self._checkSimpleQuotes.isChecked(): settings.QUOTES["'"] = "'" elif ("'") in settings.QUOTES: del settings.QUOTES["'"] qsettings.setValue('preferences/editor/simpleQuotes', self._checkSimpleQuotes.isChecked()) if self._checkDoubleQuotes.isChecked(): settings.QUOTES['"'] = '"' elif ('"') in settings.QUOTES: del settings.QUOTES['"'] qsettings.setValue('preferences/editor/doubleQuotes', self._checkDoubleQuotes.isChecked()) settings.CODE_COMPLETION = self._checkCodeDot.isChecked() qsettings.setValue('preferences/editor/codeCompletion', self._checkCodeDot .isChecked()) settings.COMPLETE_DECLARATIONS = \ self._checkCompleteDeclarations.isChecked() qsettings.setValue("preferences/editor/completeDeclarations", settings.COMPLETE_DECLARATIONS) preferences.Preferences.register_configuration( 'EDITOR', EditorCompletion, translations.TR_PREFERENCES_EDITOR_COMPLETION, weight=1, subsection='COMPLETION')
6,155
Python
.py
126
39.515873
79
0.668551
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,571
preferences_editor_general.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_editor_general.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import copy from PyQt5.QtWidgets import ( QWidget, QComboBox, QVBoxLayout, QHBoxLayout, QGroupBox, QCheckBox, QGridLayout, QMessageBox, QListWidget, QListView, QLabel, QSizePolicy, QSpacerItem, QSpinBox, QFontDialog, QFontComboBox, QPushButton ) from PyQt5.QtGui import QIcon, QColor from PyQt5.QtCore import ( QAbstractListModel, Qt, QSize ) from ninja_ide import resources from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences from ninja_ide.tools import json_manager class ListModelScheme(QAbstractListModel): def __init__(self, schemes): super().__init__() self.__schemes = schemes self._font = None def rowCount(self, index): return len(self.__schemes) def data(self, index, role): if role == Qt.DisplayRole: return self.__schemes[index.row()].name elif role == Qt.BackgroundColorRole: return QColor(self.__schemes[index.row()].color) elif role == Qt.ForegroundRole: return QColor(self.__schemes[0].color) elif role == Qt.FontRole: return self._font def set_font(self, font): self._font = font class EditorGeneral(QWidget): def __init__(self, parent): super().__init__(parent) self._preferences = parent vbox = QVBoxLayout(self) self._font = settings.FONT # Group widgets group_typo = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_TYPOGRAPHY) group_scheme = QGroupBox("Editor Color Scheme") # Font settings grid_typo = QGridLayout(group_typo) self._btn_editor_font = QPushButton('') grid_typo.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_EDITOR_FONT), 0, 0) grid_typo.addWidget(self._btn_editor_font, 0, 1) self._check_font_antialiasing = QCheckBox("Antialiasing") grid_typo.addWidget(self._check_font_antialiasing, 1, 0) # Scheme settings box = QVBoxLayout(group_scheme) self._combo_themes = QComboBox() box.addWidget(self._combo_themes) schemes = json_manager.load_editor_schemes() for scheme_name, colors in schemes.items(): self._combo_themes.addItem(scheme_name, colors) self.__current_scheme = settings.EDITOR_SCHEME # category_name, # Add group widgets vbox.addWidget(group_typo) vbox.addWidget(group_scheme) vbox.addItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Initial Settings btn_text = ', '.join(self._font.toString().split(',')[0:2]) self._btn_editor_font.setText(btn_text) self._check_font_antialiasing.setChecked(settings.FONT_ANTIALIASING) self._combo_themes.setCurrentText(settings.EDITOR_SCHEME) # Connections self._btn_editor_font.clicked.connect(self._load_editor_font) self._preferences.savePreferences.connect(self._save) def _load_editor_font(self): font, ok = QFontDialog.getFont(self._font, self) if ok: self._font = font btn_text = ', '.join(self._font.toString().split(',')[0:2]) self._btn_editor_font.setText(btn_text) def _save(self): qsettings = IDE.editor_settings() settings.FONT = self._font qsettings.setValue("editor/general/default_font", settings.FONT) settings.FONT_ANTIALIASING = self._check_font_antialiasing.isChecked() qsettings.setValue("editor/general/font_antialiasing", settings.FONT_ANTIALIASING) settings.EDITOR_SCHEME = self._combo_themes.currentText() qsettings.setValue("editor/general/scheme", settings.EDITOR_SCHEME) scheme = self._combo_themes.currentText() if scheme != self.__current_scheme: index = self._combo_themes.currentIndex() colors = self._combo_themes.itemData(index) resources.COLOR_SCHEME = colors main = IDE.get_service("main_container") main.restyle_editor() '''class EditorGeneral(QWidget): """EditorGeneral widget class.""" def __init__(self, parent): super(EditorGeneral, self).__init__() self._preferences, vbox = parent, QVBoxclass EditorGeneral(QWidget): """EditorGeneral widget class.""" def __init__(self, parent): super(EditorGeneral, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) self.original_style = copy.copy(resources.CUSTOM_SCHEME) self.current_scheme, self._modified_editors = 'default', [] self._font = settings.FONT groupBoxMini = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_MINIMAP) groupBoxDocMap = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP) groupBoxTypo = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_TYPOGRAPHY) groupBoxScheme = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_SCHEME) boxMiniAndDocMap = QHBoxLayout() # Minimap formMini = QGridLayout(groupBoxMini) formMini.setContentsMargins(5, 15, 5, 5) self._checkShowMinimap = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_ENABLE_MINIMAP) self._spinMaxOpacity = QSpinBox() self._spinMaxOpacity.setRange(0, 100) self._spinMaxOpacity.setSuffix("% Max.") self._spinMinOpacity = QSpinBox() self._spinMinOpacity.setRange(0, 100) self._spinMinOpacity.setSuffix("% Min.") self._spinSize = QSpinBox() self._spinSize.setMaximum(100) self._spinSize.setMinimum(0) self._spinSize.setSuffix( translations.TR_PREFERENCES_EDITOR_GENERAL_AREA_MINIMAP) formMini.addWidget(self._checkShowMinimap, 0, 1) formMini.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_SIZE_MINIMAP), 1, 0, Qt.AlignRight) formMini.addWidget(self._spinSize, 1, 1) formMini.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_OPACITY), 2, 0, Qt.AlignRight) formMini.addWidget(self._spinMinOpacity, 2, 1) formMini.addWidget(self._spinMaxOpacity, 2, 2) boxMiniAndDocMap.addWidget(groupBoxMini) # Document Map formDocMap = QGridLayout(groupBoxDocMap) self._checkShowDocMap = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_ENABLE_DOCMAP) self._checkShowSlider = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP_SLIDER) self._checkOriginalScroll = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_ORIGINAL_SCROLLBAR) self._checkCurrentLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP_CURRENT_LINE) self._checkSearchLines = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP_SEARCH_LINES) self._spinWidth = QSpinBox() self._spinWidth.setRange(5, 40) formDocMap.addWidget(self._checkShowDocMap, 0, 0) formDocMap.addWidget(self._checkShowSlider, 0, 1) formDocMap.addWidget(self._checkOriginalScroll, 0, 2) formDocMap.addWidget(self._checkCurrentLine, 1, 0) formDocMap.addWidget(self._checkSearchLines, 1, 1) formDocMap.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP_WIDTH), 2, 0) formDocMap.addWidget(self._spinWidth, 2, 1) boxMiniAndDocMap.addWidget(groupBoxDocMap) # Typo gridTypo = QGridLayout(groupBoxTypo) gridTypo.setContentsMargins(5, 15, 5, 5) self._btnEditorFont = QPushButton('') gridTypo.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_EDITOR_FONT), 0, 0, Qt.AlignRight) gridTypo.addWidget(self._btnEditorFont, 0, 1) # Scheme vboxScheme = QVBoxLayout(groupBoxScheme) vboxScheme.setContentsMargins(5, 15, 5, 5) self._listScheme = QListWidget() vboxScheme.addWidget(self._listScheme) hbox = QHBoxLayout() btnDownload = QPushButton( translations.TR_PREFERENCES_EDITOR_DOWNLOAD_SCHEME) btnDownload.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) btnDownload.clicked.connect(self._open_schemes_manager) hbox.addWidget(btnDownload) btnAdd = QPushButton(QIcon(":img/add"), translations.TR_EDITOR_CREATE_SCHEME) btnAdd.setIconSize(QSize(16, 16)) btnAdd.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) btnAdd.clicked.connect(self._open_schemes_designer) btnRemove = QPushButton(QIcon(":img/delete"), translations.TR_EDITOR_REMOVE_SCHEME) btnRemove.setIconSize(QSize(16, 16)) btnRemove.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) btnRemove.clicked.connect(self._remove_scheme) hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox.addWidget(btnAdd) hbox.addWidget(btnRemove) vboxScheme.addLayout(hbox) vbox.addLayout(boxMiniAndDocMap) vbox.addWidget(groupBoxTypo) vbox.addWidget(groupBoxScheme) # Settings qsettings = IDE.ninja_settings() qsettings.beginGroup('preferences') qsettings.beginGroup('editor') self._checkShowMinimap.setChecked(settings.SHOW_MINIMAP) if settings.IS_MAC_OS: self._spinMinOpacity.setValue(100) self._spinMaxOpacity.setValue(100) self._spinMinOpacity.setDisabled(True) self._spinMaxOpacity.setDisabled(True) else: self._spinMinOpacity.setValue(settings.MINIMAP_MIN_OPACITY * 100) self._spinMaxOpacity.setValue(settings.MINIMAP_MAX_OPACITY * 100) self._checkShowDocMap.setChecked(settings.SHOW_DOCMAP) self._checkShowSlider.setChecked(settings.DOCMAP_SLIDER) self._checkOriginalScroll.setChecked(settings.EDITOR_SCROLLBAR) self._checkCurrentLine.setChecked(settings.DOCMAP_CURRENT_LINE) self._checkSearchLines.setChecked(settings.DOCMAP_SEARCH_LINES) self._spinWidth.setValue(settings.DOCMAP_WIDTH) self._spinSize.setValue(settings.SIZE_PROPORTION * 100) btnText = ', '.join(self._font.toString().split(',')[0:2]) self._btnEditorFont.setText(btnText) self._listScheme.clear() self._listScheme.addItem('default') # self._schemes = json_manager.load_editor_skins() self._schemes = [] for item in self._schemes: self._listScheme.addItem(item) items = self._listScheme.findItems( qsettings.value('scheme', defaultValue='', type='QString'), Qt.MatchExactly) if items: self._listScheme.setCurrentItem(items[0]) else: self._listScheme.setCurrentRow(0) qsettings.endGroup() qsettings.endGroup() # Signals self._btnEditorFont.clicked.connect(self._load_editor_font) self._listScheme.itemSelectionChanged.connect(self._preview_style) self._preferences.savePreferences.connect(self.save) def _open_schemes_manager(self): ninjaide = IDE.get_service("ide") ninjaide.show_schemes() # refresh schemes def _open_schemes_designer(self): name = self._listScheme.currentItem().text() scheme = self._schemes.get(name, resources.COLOR_SCHEME) designer = preferences_editor_scheme_designer.EditorSchemeDesigner( scheme, self) designer.exec_() if designer.saved: scheme_name = designer.line_name.text() scheme = designer.original_style self._schemes[scheme_name] = scheme result = self._listScheme.findItems(scheme_name, Qt.MatchExactly) if not result: self._listScheme.addItem(scheme_name) def _remove_scheme(self): name = self._listScheme.currentItem().text() fileName = ('{0}.color'.format( file_manager.create_path(resources.EDITOR_SKINS, name))) file_manager.delete_file(fileName) item = self._listScheme.takeItem(self._listScheme.currentRow()) del item def hideEvent(self, event): super(EditorGeneral, self).hideEvent(event) resources.CUSTOM_SCHEME = self.original_style for editorWidget in self._modified_editors: try: editorWidget.restyle(editorWidget.lang) except RuntimeError: print('the editor has been removed') def _preview_style(self): scheme = self._listScheme.currentItem().text() if scheme == self.current_scheme: return main_container = IDE.get_service('main_container') if not main_container: return editorWidget = main_container.get_current_editor() if editorWidget is not None: resources.CUSTOM_SCHEME = self._schemes.get( scheme, resources.COLOR_SCHEME) editorWidget.restyle(editorWidget.lang) self._modified_editors.append(editorWidget) self.current_scheme = scheme def _load_editor_font(self): try: font, ok = QFontDialog.getFont(self._font, self) if ok: self._font = font btnText = ', '.join(self._font.toString().split(',')[0:2]) self._btnEditorFont.setText(btnText) except: QMessageBox.warning( self, translations.TR_PREFERENCES_EDITOR_GENERAL_FONT_MESSAGE_TITLE, translations.TR_PREFERENCES_EDITOR_GENERAL_FONT_MESSAGE_BODY) def save(self): qsettings = IDE.ninja_settings() settings.FONT = self._font qsettings.setValue('preferences/editor/font', settings.FONT) settings.SHOW_MINIMAP = self._checkShowMinimap.isChecked() settings.MINIMAP_MAX_OPACITY = self._spinMaxOpacity.value() / 100.0 settings.MINIMAP_MIN_OPACITY = self._spinMinOpacity.value() / 100.0 settings.SIZE_PROPORTION = self._spinSize.value() / 100.0 qsettings.setValue('preferences/editor/minimapMaxOpacity', settings.MINIMAP_MAX_OPACITY) qsettings.setValue('preferences/editor/minimapMinOpacity', settings.MINIMAP_MIN_OPACITY) qsettings.setValue('preferences/editor/minimapSizeProportion', settings.SIZE_PROPORTION) qsettings.setValue('preferences/editor/minimapShow', settings.SHOW_MINIMAP) settings.SHOW_DOCMAP = self._checkShowDocMap.isChecked() settings.DOCMAP_SLIDER = self._checkShowSlider.isChecked() settings.EDITOR_SCROLLBAR = self._checkOriginalScroll.isChecked() settings.DOCMAP_CURRENT_LINE = self._checkCurrentLine.isChecked() settings.DOCMAP_SEARCH_LINES = self._checkSearchLines.isChecked() settings.DOCMAP_WIDTH = self._spinWidth.value() qsettings.setValue('preferences/editor/docmapShow', settings.SHOW_DOCMAP) qsettings.setValue('preferences/editor/docmapSlider', settings.DOCMAP_SLIDER) qsettings.setValue('preferences/editor/editorScrollBar', settings.EDITOR_SCROLLBAR) qsettings.setValue('preferences/editor/docmapCurrentLine', settings.DOCMAP_CURRENT_LINE) qsettings.setValue('preferences/editor/docmapSearchLines', settings.DOCMAP_SEARCH_LINES) qsettings.setValue('preferences/editor/docmapWidth', settings.DOCMAP_WIDTH) scheme = self._listScheme.currentItem().text() resources.CUSTOM_SCHEME = self._schemes.get(scheme, resources.COLOR_SCHEME) qsettings.setValue('preferences/editor/scheme', scheme) Layout(self) self.original_style = copy.copy(resources.CUSTOM_SCHEME) self.current_scheme, self._modified_editors = 'default', [] self._font = settings.FONT groupBoxMini = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_MINIMAP) groupBoxDocMap = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP) groupBoxTypo = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_TYPOGRAPHY) groupBoxScheme = QGroupBox( translations.TR_PREFERENCES_EDITOR_GENERAL_SCHEME) boxMiniAndDocMap = QHBoxLayout() # Minimap formMini = QGridLayout(groupBoxMini) formMini.setContentsMargins(5, 15, 5, 5) self._checkShowMinimap = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_ENABLE_MINIMAP) self._spinMaxOpacity = QSpinBox() self._spinMaxOpacity.setRange(0, 100) self._spinMaxOpacity.setSuffix("% Max.") self._spinMinOpacity = QSpinBox() self._spinMinOpacity.setRange(0, 100) self._spinMinOpacity.setSuffix("% Min.") self._spinSize = QSpinBox() self._spinSize.setMaximum(100) self._spinSize.setMinimum(0) self._spinSize.setSuffix( translations.TR_PREFERENCES_EDITOR_GENERAL_AREA_MINIMAP) formMini.addWidget(self._checkShowMinimap, 0, 1) formMini.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_SIZE_MINIMAP), 1, 0, Qt.AlignRight) formMini.addWidget(self._spinSize, 1, 1) formMini.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_OPACITY), 2, 0, Qt.AlignRight) formMini.addWidget(self._spinMinOpacity, 2, 1) formMini.addWidget(self._spinMaxOpacity, 2, 2) boxMiniAndDocMap.addWidget(groupBoxMini) # Document Map formDocMap = QGridLayout(groupBoxDocMap) self._checkShowDocMap = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_ENABLE_DOCMAP) self._checkShowSlider = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP_SLIDER) self._checkOriginalScroll = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_ORIGINAL_SCROLLBAR) self._checkCurrentLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP_CURRENT_LINE) self._checkSearchLines = QCheckBox( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP_SEARCH_LINES) self._spinWidth = QSpinBox() self._spinWidth.setRange(5, 40) formDocMap.addWidget(self._checkShowDocMap, 0, 0) formDocMap.addWidget(self._checkShowSlider, 0, 1) formDocMap.addWidget(self._checkOriginalScroll, 0, 2) formDocMap.addWidget(self._checkCurrentLine, 1, 0) formDocMap.addWidget(self._checkSearchLines, 1, 1) formDocMap.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_DOCMAP_WIDTH), 2, 0) formDocMap.addWidget(self._spinWidth, 2, 1) boxMiniAndDocMap.addWidget(groupBoxDocMap) # Typo gridTypo = QGridLayout(groupBoxTypo) gridTypo.setContentsMargins(5, 15, 5, 5) self._btnEditorFont = QPushButton('') gridTypo.addWidget(QLabel( translations.TR_PREFERENCES_EDITOR_GENERAL_EDITOR_FONT), 0, 0, Qt.AlignRight) gridTypo.addWidget(self._btnEditorFont, 0, 1) # Scheme vboxScheme = QVBoxLayout(groupBoxScheme) vboxScheme.setContentsMargins(5, 15, 5, 5) self._listScheme = QListWidget() vboxScheme.addWidget(self._listScheme) hbox = QHBoxLayout() btnDownload = QPushButton( translations.TR_PREFERENCES_EDITOR_DOWNLOAD_SCHEME) btnDownload.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) btnDownload.clicked.connect(self._open_schemes_manager) hbox.addWidget(btnDownload) btnAdd = QPushButton(QIcon(":img/add"), translations.TR_EDITOR_CREATE_SCHEME) btnAdd.setIconSize(QSize(16, 16)) btnAdd.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) btnAdd.clicked.connect(self._open_schemes_designer) btnRemove = QPushButton(QIcon(":img/delete"), translations.TR_EDITOR_REMOVE_SCHEME) btnRemove.setIconSize(QSize(16, 16)) btnRemove.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) btnRemove.clicked.connect(self._remove_scheme) hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox.addWidget(btnAdd) hbox.addWidget(btnRemove) vboxScheme.addLayout(hbox) vbox.addLayout(boxMiniAndDocMap) vbox.addWidget(groupBoxTypo) vbox.addWidget(groupBoxScheme) # Settings qsettings = IDE.ninja_settings() qsettings.beginGroup('preferences') qsettings.beginGroup('editor') self._checkShowMinimap.setChecked(settings.SHOW_MINIMAP) if settings.IS_MAC_OS: self._spinMinOpacity.setValue(100) self._spinMaxOpacity.setValue(100) self._spinMinOpacity.setDisabled(True) self._spinMaxOpacity.setDisabled(True) else: self._spinMinOpacity.setValue(settings.MINIMAP_MIN_OPACITY * 100) self._spinMaxOpacity.setValue(settings.MINIMAP_MAX_OPACITY * 100) self._checkShowDocMap.setChecked(settings.SHOW_DOCMAP) self._checkShowSlider.setChecked(settings.DOCMAP_SLIDER) self._checkOriginalScroll.setChecked(settings.EDITOR_SCROLLBAR) self._checkCurrentLine.setChecked(settings.DOCMAP_CURRENT_LINE) self._checkSearchLines.setChecked(settings.DOCMAP_SEARCH_LINES) self._spinWidth.setValue(settings.DOCMAP_WIDTH) self._spinSize.setValue(settings.SIZE_PROPORTION * 100) btnText = ', '.join(self._font.toString().split(',')[0:2]) self._btnEditorFont.setText(btnText) self._listScheme.clear() self._listScheme.addItem('default') # self._schemes = json_manager.load_editor_skins() self._schemes = [] for item in self._schemes: self._listScheme.addItem(item) items = self._listScheme.findItems( qsettings.value('scheme', defaultValue='', type='QString'), Qt.MatchExactly) if items: self._listScheme.setCurrentItem(items[0]) else: self._listScheme.setCurrentRow(0) qsettings.endGroup() qsettings.endGroup() # Signals self._btnEditorFont.clicked.connect(self._load_editor_font) self._listScheme.itemSelectionChanged.connect(self._preview_style) self._preferences.savePreferences.connect(self.save) def _open_schemes_manager(self): ninjaide = IDE.get_service("ide") ninjaide.show_schemes() # refresh schemes def _open_schemes_designer(self): name = self._listScheme.currentItem().text() scheme = self._schemes.get(name, resources.COLOR_SCHEME) designer = preferences_editor_scheme_designer.EditorSchemeDesigner( scheme, self) designer.exec_() if designer.saved: scheme_name = designer.line_name.text() scheme = designer.original_style self._schemes[scheme_name] = scheme result = self._listScheme.findItems(scheme_name, Qt.MatchExactly) if not result: self._listScheme.addItem(scheme_name) def _remove_scheme(self): name = self._listScheme.currentItem().text() fileName = ('{0}.color'.format( file_manager.create_path(resources.EDITOR_SKINS, name))) file_manager.delete_file(fileName) item = self._listScheme.takeItem(self._listScheme.currentRow()) del item def hideEvent(self, event): super(EditorGeneral, self).hideEvent(event) resources.CUSTOM_SCHEME = self.original_style for editorWidget in self._modified_editors: try: editorWidget.restyle(editorWidget.lang) except RuntimeError: print('the editor has been removed') def _preview_style(self): scheme = self._listScheme.currentItem().text() if scheme == self.current_scheme: return main_container = IDE.get_service('main_container') if not main_container: return editorWidget = main_container.get_current_editor() if editorWidget is not None: resources.CUSTOM_SCHEME = self._schemes.get( scheme, resources.COLOR_SCHEME) editorWidget.restyle(editorWidget.lang) self._modified_editors.append(editorWidget) self.current_scheme = scheme def _load_editor_font(self): try: font, ok = QFontDialog.getFont(self._font, self) if ok: self._font = font btnText = ', '.join(self._font.toString().split(',')[0:2]) self._btnEditorFont.setText(btnText) except: QMessageBox.warning( self, translations.TR_PREFERENCES_EDITOR_GENERAL_FONT_MESSAGE_TITLE, translations.TR_PREFERENCES_EDITOR_GENERAL_FONT_MESSAGE_BODY) def save(self): qsettings = IDE.ninja_settings() settings.FONT = self._font qsettings.setValue('preferences/editor/font', settings.FONT) settings.SHOW_MINIMAP = self._checkShowMinimap.isChecked() settings.MINIMAP_MAX_OPACITY = self._spinMaxOpacity.value() / 100.0 settings.MINIMAP_MIN_OPACITY = self._spinMinOpacity.value() / 100.0 settings.SIZE_PROPORTION = self._spinSize.value() / 100.0 qsettings.setValue('preferences/editor/minimapMaxOpacity', settings.MINIMAP_MAX_OPACITY) qsettings.setValue('preferences/editor/minimapMinOpacity', settings.MINIMAP_MIN_OPACITY) qsettings.setValue('preferences/editor/minimapSizeProportion', settings.SIZE_PROPORTION) qsettings.setValue('preferences/editor/minimapShow', settings.SHOW_MINIMAP) settings.SHOW_DOCMAP = self._checkShowDocMap.isChecked() settings.DOCMAP_SLIDER = self._checkShowSlider.isChecked() settings.EDITOR_SCROLLBAR = self._checkOriginalScroll.isChecked() settings.DOCMAP_CURRENT_LINE = self._checkCurrentLine.isChecked() settings.DOCMAP_SEARCH_LINES = self._checkSearchLines.isChecked() settings.DOCMAP_WIDTH = self._spinWidth.value() qsettings.setValue('preferences/editor/docmapShow', settings.SHOW_DOCMAP) qsettings.setValue('preferences/editor/docmapSlider', settings.DOCMAP_SLIDER) qsettings.setValue('preferences/editor/editorScrollBar', settings.EDITOR_SCROLLBAR) qsettings.setValue('preferences/editor/docmapCurrentLine', settings.DOCMAP_CURRENT_LINE) qsettings.setValue('preferences/editor/docmapSearchLines', settings.DOCMAP_SEARCH_LINES) qsettings.setValue('preferences/editor/docmapWidth', settings.DOCMAP_WIDTH) scheme = self._listScheme.currentItem().text() resources.CUSTOM_SCHEME = self._schemes.get(scheme, resources.COLOR_SCHEME) qsettings.setValue('preferences/editor/scheme', scheme) ''' preferences.Preferences.register_configuration( 'EDITOR', EditorGeneral, translations.TR_PREFERENCES_EDITOR_GENERAL, preferences.SECTIONS['EDITOR'])
29,097
Python
.py
620
36.633871
78
0.654494
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,572
preferences_editor_behavior.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_editor_behavior.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QWidget, QCheckBox, QVBoxLayout, QHBoxLayout, QLabel, QComboBox, QSizePolicy, QSpinBox, QGroupBox, ) from ninja_ide.core import settings from ninja_ide import translations from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences class Behavior(QWidget): """Behavior widget class""" def __init__(self, parent=None): super().__init__() self._preferences = parent container = QVBoxLayout(self) # Groups group_box_onsaving = QGroupBox( translations.TR_PREFERENCES_EDITOR_BEHAVIOR_ONSAVING) group_box_indentation = QGroupBox( translations.TR_PREFERENCES_EDITOR_BEHAVIOR_INDENTATION) group_box_mouse_kbr = QGroupBox( translations.TR_PREFERENCES_EDITOR_BEHAVIOR_MOUSE_KEYBOARD) # On saving vbox = QVBoxLayout(group_box_onsaving) self._check_remove_spaces = QCheckBox( translations.TR_PREFERENCES_EDITOR_BEHAVIOR_CLEAN_WHITESPACES) vbox.addWidget(self._check_remove_spaces) self._check_add_new_line = QCheckBox( translations.TR_PREFERENCES_EDITOR_BEHAVIOR_ADD_NEW_LINE) vbox.addWidget(self._check_add_new_line) # Indentation hbox = QHBoxLayout(group_box_indentation) self._combo_tab_policy = QComboBox() self._combo_tab_policy.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed) self._combo_tab_policy.addItems([ translations.TR_PREFERENCES_EDITOR_BEHAVIOR_SPACES_ONLY, translations.TR_PREFERENCES_EDITOR_BEHAVIOR_TABS_ONLY ]) hbox.addWidget(self._combo_tab_policy) hbox.addWidget( QLabel(translations.TR_PREFERENCES_EDITOR_BEHAVIOR_INDENT_SIZE)) self._spin_indent_size = QSpinBox() hbox.addWidget(self._spin_indent_size) # Mouse and keyboard vbox = QVBoxLayout(group_box_mouse_kbr) self._check_scroll_wheel = QCheckBox( translations.TR_PREFERENCES_EDITOR_BEHAVIOR_SCROLL_WHEEL) vbox.addWidget(self._check_scroll_wheel) self._check_hide_cursor = QCheckBox( translations.TR_PREFERENCES_EDITOR_BEHAVIOR_HIDE_CURSOR) vbox.addWidget(self._check_hide_cursor) hbox = QHBoxLayout() hbox.addWidget( QLabel(translations.TR_PREFERENCES_EDITOR_BEHAVIOR_SHOW_TOOLTIPS)) self._combo_tooltips = QComboBox() self._combo_tooltips.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed) self._combo_tooltips.addItems([ translations.TR_PREFERENCES_EDITOR_BEHAVIOR_TOOLTIPS_MOUSE_OVER, translations.TR_PREFERENCES_EDITOR_BEHAVIOR_TOOLTIPS_SHIFT ]) hbox.addWidget(self._combo_tooltips) vbox.addLayout(hbox) container.addWidget(group_box_onsaving) container.addWidget(group_box_indentation) container.addWidget(group_box_mouse_kbr) container.addStretch(1) # Settings self._check_remove_spaces.setChecked(settings.REMOVE_TRAILING_SPACES) self._check_add_new_line.setChecked(settings.ADD_NEW_LINE_AT_EOF) self._check_hide_cursor.setChecked(settings.HIDE_MOUSE_CURSOR) self._check_scroll_wheel.setChecked(settings.SCROLL_WHEEL_ZOMMING) self._combo_tab_policy.setCurrentIndex(bool(settings.USE_TABS)) self._spin_indent_size.setValue(settings.INDENT) self._preferences.savePreferences.connect(self._save) def _save(self): qsettings = IDE.ninja_settings() editor_settings = IDE.editor_settings() qsettings.beginGroup("editor") editor_settings.beginGroup("editor") qsettings.beginGroup("behavior") editor_settings.beginGroup("behavior") settings.REMOVE_TRAILING_SPACES = self._check_remove_spaces.isChecked() qsettings.setValue("removeTrailingSpaces", settings.REMOVE_TRAILING_SPACES) settings.ADD_NEW_LINE_AT_EOF = self._check_add_new_line.isChecked() qsettings.setValue("addNewLineAtEnd", settings.ADD_NEW_LINE_AT_EOF) settings.HIDE_MOUSE_CURSOR = self._check_hide_cursor.isChecked() qsettings.setValue("hideMouseCursor", settings.HIDE_MOUSE_CURSOR) settings.SCROLL_WHEEL_ZOMMING = self._check_scroll_wheel.isChecked() qsettings.setValue("scrollWheelZomming", settings.SCROLL_WHEEL_ZOMMING) settings.USE_TABS = bool(self._combo_tab_policy.currentIndex()) editor_settings.setValue("use_tabs", settings.USE_TABS) settings.INDENT = self._spin_indent_size.value() editor_settings.setValue("indentation_width", settings.INDENT) qsettings.endGroup() qsettings.endGroup() editor_settings.endGroup() editor_settings.endGroup() preferences.Preferences.register_configuration( "EDITOR", Behavior, translations.TR_PREFERENCES_EDITOR_BEHAVIOR, weight=0, subsection="BEHAVIOR" )
5,756
Python
.py
129
36.945736
79
0.697807
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,573
preferences_appearance.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_appearance.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QLabel ) from ninja_ide.gui.dialogs.preferences import preferences class Appearance(QWidget): def __init__(self, parent=None): super().__init__(parent) # preferences.Preferences.register_configuration( # 'APPEARANCE', # Appearance, # "Appearance",
1,048
Python
.py
30
32.8
70
0.745059
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,574
preferences_general.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_general.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QSizePolicy, QSpacerItem, QGroupBox, QSpinBox, QCheckBox, QFileDialog, QLineEdit, QGridLayout, QComboBox, QMessageBox, QStyle ) from PyQt5.QtCore import ( Qt, pyqtSignal ) from ninja_ide.gui.dialogs.preferences import preferences from ninja_ide import translations from ninja_ide.tools import ui_tools from ninja_ide.core import settings from ninja_ide.gui.ide import IDE class GeneralConfiguration(QWidget): """General configuration class""" def __init__(self, parent): super().__init__() self._preferences = parent vbox = QVBoxLayout(self) # Groups group_box_start = QGroupBox(translations.TR_PREFERENCES_GENERAL_START) group_box_close = QGroupBox(translations.TR_PREFERENCES_GENERAL_CLOSE) group_box_workspace = QGroupBox( translations.TR_PREFERENCES_GENERAL_WORKSPACE) group_box_reset = QGroupBox(translations.TR_PREFERENCES_GENERAL_RESET) group_box_swap = QGroupBox( translations.TR_PREFERENCES_GENERAL_SWAPFILE) group_box_modification = QGroupBox( translations.TR_PREFERENCES_GENERAL_EXTERNALLY_MOD) # Group start box_start = QVBoxLayout(group_box_start) self._check_last_session = QCheckBox( translations.TR_PREFERENCES_GENERAL_LOAD_LAST_SESSION) self._check_notify_updates = QCheckBox( translations.TR_PREFERENCES_GENERAL_NOTIFY_UPDATES) box_start.addWidget(self._check_last_session) box_start.addWidget(self._check_notify_updates) # Group close box_close = QVBoxLayout(group_box_close) self._check_confirm_exit = QCheckBox( translations.TR_PREFERENCES_GENERAL_CONFIRM_EXIT) box_close.addWidget(self._check_confirm_exit) # Workspace and Project grid_workspace = QGridLayout(group_box_workspace) self._text_workspace = QLineEdit() choose_workspace_action = self._text_workspace.addAction( self.style().standardIcon(self.style().SP_DirIcon), QLineEdit.TrailingPosition) clear_workspace_action = self._text_workspace.addAction( self.style().standardIcon(self.style().SP_LineEditClearButton), QLineEdit.TrailingPosition) self._text_workspace.setReadOnly(True) grid_workspace.addWidget( QLabel(translations.TR_PREFERENCES_GENERAL_WORKSPACE), 0, 0) grid_workspace.addWidget(self._text_workspace, 0, 1) # Resetting prefences box_reset = QVBoxLayout(group_box_reset) btn_reset = QPushButton( translations.TR_PREFERENCES_GENERAL_RESET_PREFERENCES) box_reset.addWidget(btn_reset) # Swap File box_swap = QGridLayout(group_box_swap) box_swap.addWidget(QLabel( translations.TR_PREFERENCES_GENERAL_SWAPFILE_LBL), 0, 0) self._combo_swap_file = QComboBox() self._combo_swap_file.addItems([ translations.TR_PREFERENCES_GENERAL_SWAPFILE_DISABLE, translations.TR_PREFERENCES_GENERAL_SWAPFILE_ENABLE ]) self._combo_swap_file.currentIndexChanged.connect( self._change_swap_widgets_state) box_swap.addWidget(self._combo_swap_file, 0, 1) box_swap.addWidget(QLabel( translations.TR_PREFERENCES_GENERAL_SWAPFILE_SYNC_INTERVAL), 1, 0) self._spin_swap = QSpinBox() self._spin_swap.setSuffix("s") self._spin_swap.setRange(5, 600) self._spin_swap.setSingleStep(5) box_swap.addWidget(self._spin_swap, 1, 1) # Externally modification box_mod = QHBoxLayout(group_box_modification) box_mod.addWidget( QLabel(translations.TR_PREFERENCES_GENERAL_EXTERNALLY_MOD_LABEL)) self._combo_mod = QComboBox() self._combo_mod.addItems(["Ask", "Reload", "Ignore"]) box_mod.addWidget(self._combo_mod) # Add groups to main layout vbox.addWidget(group_box_start) vbox.addWidget(group_box_close) vbox.addWidget(group_box_workspace) vbox.addWidget(group_box_swap) vbox.addWidget(group_box_modification) vbox.addWidget(group_box_reset, alignment=Qt.AlignLeft) vbox.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Settings qsettings = IDE.ninja_settings() qsettings.beginGroup("ide") self._check_last_session.setChecked( qsettings.value("loadFiles", defaultValue=True, type=bool)) self._check_notify_updates.setChecked( qsettings.value("notifyUpdates", defaultValue=True, type=bool)) qsettings.endGroup() self._combo_swap_file.setCurrentIndex(settings.SWAP_FILE) self._spin_swap.setValue(settings.SWAP_FILE_INTERVAL) self._text_workspace.setText(settings.WORKSPACE) self._combo_mod.setCurrentIndex(settings.RELOAD_FILE) self._check_confirm_exit.setChecked(settings.CONFIRM_EXIT) # Connections btn_reset.clicked.connect(self._reset_preferences) choose_workspace_action.triggered.connect(self._load_workspace) clear_workspace_action.triggered.connect(self._text_workspace.clear) self._preferences.savePreferences.connect(self.save) def _change_swap_widgets_state(self, index): if index == 0: self._spin_swap.setEnabled(False) else: self._spin_swap.setEnabled(True) def _reset_preferences(self): """Reset all preferences to default values""" result = QMessageBox.question( self, translations.TR_PREFERENCES_GENERAL_RESET_TITLE, translations.TR_PREFERENCES_GENERAL_RESET_BODY, buttons=QMessageBox.Yes | QMessageBox.No ) if result == QMessageBox.Yes: qsettings = IDE.ninja_settings() qsettings.clear() self._preferences.close() def _load_workspace(self): """Ask the user for a Workspace path""" path = QFileDialog.getExistingDirectory( self, translations.TR_PREFERENCES_GENERAL_SELECT_WORKSPACE) self._text_workspace.setText(path) def save(self): """Save all preferences values""" qsettings = IDE.ninja_settings() qsettings.beginGroup("ide") settings.CONFIRM_EXIT = self._check_confirm_exit.isChecked() qsettings.setValue("confirmExit", settings.CONFIRM_EXIT) qsettings.setValue("loadFiles", self._check_last_session.isChecked()) qsettings.setValue("notifyUpdates", self._check_notify_updates.isChecked()) settings.WORKSPACE = self._text_workspace.text() qsettings.setValue("workspace", settings.WORKSPACE) settings.RELOAD_FILE = self._combo_mod.currentIndex() qsettings.setValue("reloadSetting", settings.RELOAD_FILE) settings.SWAP_FILE = self._combo_swap_file.currentIndex() qsettings.setValue("swapFile", settings.SWAP_FILE) settings.SWAP_FILE_INTERVAL = self._spin_swap.value() qsettings.setValue("swapFileInterval", settings.SWAP_FILE_INTERVAL) qsettings.endGroup() preferences.Preferences.register_configuration( 'GENERAL', GeneralConfiguration, translations.TR_PREFERENCES_GENERAL, preferences.SECTIONS['GENERAL'] ) """ from __future__ import absolute_import from __future__ import unicode_literals from PyQt4.QtGui import QWidget from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QGroupBox from PyQt4.QtGui import QCheckBox from PyQt4.QtGui import QComboBox from PyQt4.QtGui import QGridLayout from PyQt4.QtGui import QLineEdit from PyQt4.QtGui import QMessageBox from PyQt4.QtGui import QIcon from PyQt4.QtGui import QLabel from PyQt4.QtGui import QFileDialog from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QColorDialog from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences from ninja_ide.tools import ui_tools class GeneralConfiguration(QWidget): # General Configuration class def __init__(self, parent): super(GeneralConfiguration, self).__init__() self._preferences = parent vbox = QVBoxLayout(self) groupBoxStart = QGroupBox(translations.TR_PREFERENCES_GENERAL_START) groupBoxClose = QGroupBox(translations.TR_PREFERENCES_GENERAL_CLOSE) groupBoxWorkspace = QGroupBox( translations.TR_PREFERENCES_GENERAL_WORKSPACE) groupBoxNoti = QGroupBox(translations.TR_NOTIFICATION) groupBoxReset = QGroupBox(translations.TR_PREFERENCES_GENERAL_RESET) #Start vboxStart = QVBoxLayout(groupBoxStart) self._checkLastSession = QCheckBox( translations.TR_PREFERENCES_GENERAL_LOAD_LAST_SESSION) self._checkActivatePlugins = QCheckBox( translations.TR_PREFERENCES_GENERAL_ACTIVATE_PLUGINS) self._checkNotifyUpdates = QCheckBox( translations.TR_PREFERENCES_GENERAL_NOTIFY_UPDATES) self._checkShowStartPage = QCheckBox( translations.TR_PREFERENCES_GENERAL_SHOW_START_PAGE) vboxStart.addWidget(self._checkLastSession) vboxStart.addWidget(self._checkActivatePlugins) vboxStart.addWidget(self._checkNotifyUpdates) vboxStart.addWidget(self._checkShowStartPage) #Close vboxClose = QVBoxLayout(groupBoxClose) self._checkConfirmExit = QCheckBox( translations.TR_PREFERENCES_GENERAL_CONFIRM_EXIT) vboxClose.addWidget(self._checkConfirmExit) #Workspace and Project gridWorkspace = QGridLayout(groupBoxWorkspace) self._txtWorkspace = QLineEdit() ui_tools.LineEditButton( self._txtWorkspace, self._txtWorkspace.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self._txtWorkspace.setReadOnly(True) self._btnWorkspace = QPushButton(QIcon(':img/openFolder'), '') gridWorkspace.addWidget( QLabel(translations.TR_PREFERENCES_GENERAL_WORKSPACE), 0, 0, Qt.AlignRight) gridWorkspace.addWidget(self._txtWorkspace, 0, 1) gridWorkspace.addWidget(self._btnWorkspace, 0, 2) self._txtExtensions = QLineEdit() self._txtExtensions.setToolTip( translations.TR_PROJECT_EXTENSIONS_TOOLTIP) gridWorkspace.addWidget(QLabel( translations.TR_PREFERENCES_GENERAL_SUPPORTED_EXT), 1, 0, Qt.AlignRight) gridWorkspace.addWidget(self._txtExtensions, 1, 1) labelTooltip = QLabel(translations.TR_PROJECT_EXTENSIONS_INSTRUCTIONS) gridWorkspace.addWidget(labelTooltip, 2, 1) # Notification hboxNoti, self._notify_position = QHBoxLayout(groupBoxNoti), QComboBox() self._notify_position.addItems( [translations.TR_BOTTOM + "-" + translations.TR_LEFT, translations.TR_BOTTOM + "-" + translations.TR_RIGHT, translations.TR_TOP + "-" + translations.TR_LEFT, translations.TR_TOP + "-" + translations.TR_RIGHT]) self._notify_color = QPushButton( translations.TR_EDITOR_SCHEME_PICK_COLOR) self._notification_choosed_color = settings.NOTIFICATION_COLOR hboxNoti.addWidget(QLabel(translations.TR_POSITION_ON_SCREEN)) hboxNoti.addWidget(self._notify_position) hboxNoti.addWidget(self._notify_color, 0, Qt.AlignRight) # Resetting preferences vboxReset = QVBoxLayout(groupBoxReset) self._btnReset = QPushButton( translations.TR_PREFERENCES_GENERAL_RESET_PREFERENCES) vboxReset.addWidget(self._btnReset, alignment=Qt.AlignLeft) #Settings qsettings = IDE.ninja_settings() qsettings.beginGroup('preferences') qsettings.beginGroup('general') self._checkLastSession.setChecked( qsettings.value('loadFiles', True, type=bool)) self._checkActivatePlugins.setChecked( qsettings.value('activatePlugins', defaultValue=True, type=bool)) self._checkNotifyUpdates.setChecked( qsettings.value('preferences/general/notifyUpdates', defaultValue=True, type=bool)) self._checkShowStartPage.setChecked(settings.SHOW_START_PAGE) self._checkConfirmExit.setChecked(settings.CONFIRM_EXIT) self._txtWorkspace.setText(settings.WORKSPACE) extensions = ', '.join(settings.SUPPORTED_EXTENSIONS) self._txtExtensions.setText(extensions) self._notify_position.setCurrentIndex(settings.NOTIFICATION_POSITION) qsettings.endGroup() qsettings.endGroup() vbox.addWidget(groupBoxStart) vbox.addWidget(groupBoxClose) vbox.addWidget(groupBoxWorkspace) vbox.addWidget(groupBoxNoti) vbox.addWidget(groupBoxReset) #Signals self.connect(self._btnWorkspace, SIGNAL("clicked()"), self._load_workspace) self.connect(self._notify_color, SIGNAL("clicked()"), self._pick_color) self.connect(self._btnReset, SIGNAL('clicked()'), self._reset_preferences) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def _pick_color(self): # sk the user for a Color choosed_color = QColorDialog.getColor() if choosed_color.isValid(): self._notification_choosed_color = choosed_color.name() def _load_workspace(self): # Ask the user for a Workspace path path = QFileDialog.getExistingDirectory( self, translations.TR_PREFERENCES_GENERAL_SELECT_WORKSPACE) self._txtWorkspace.setText(path) def _load_python_path(self): # Ask the user for a Python path path = QFileDialog.getOpenFileName( self, translations.TR_PREFERENCES_GENERAL_SELECT_PYTHON_PATH) if path: self._txtPythonPath.setText(path) def save(self): # Method to Save all preferences values qsettings = IDE.ninja_settings() qsettings.setValue('preferences/general/loadFiles', self._checkLastSession.isChecked()) qsettings.setValue('preferences/general/activatePlugins', self._checkActivatePlugins.isChecked()) qsettings.setValue('preferences/general/notifyUpdates', self._checkNotifyUpdates.isChecked()) qsettings.setValue('preferences/general/showStartPage', self._checkShowStartPage.isChecked()) qsettings.setValue('preferences/general/confirmExit', self._checkConfirmExit.isChecked()) settings.CONFIRM_EXIT = self._checkConfirmExit.isChecked() qsettings.setValue('preferences/general/workspace', self._txtWorkspace.text()) settings.WORKSPACE = self._txtWorkspace.text() extensions = str(self._txtExtensions.text()).split(',') extensions = [e.strip() for e in extensions] qsettings.setValue('preferences/general/supportedExtensions', extensions) settings.SUPPORTED_EXTENSIONS = list(extensions) settings.NOTIFICATION_POSITION = self._notify_position.currentIndex() qsettings.setValue('preferences/general/notification_position', settings.NOTIFICATION_POSITION) settings.NOTIFICATION_COLOR = self._notification_choosed_color qsettings.setValue('preferences/general/notification_color', settings.NOTIFICATION_COLOR) def _reset_preferences(self): # Method to Reset all Preferences to default values result = QMessageBox.question( self, translations.TR_PREFERENCES_GENERAL_RESET_TITLE, translations.TR_PREFERENCES_GENERAL_RESET_BODY, buttons=QMessageBox.Yes | QMessageBox.No) if result == QMessageBox.Yes: qsettings = IDE.ninja_settings() qsettings.clear() self._preferences.close() preferences.Preferences.register_configuration( 'GENERAL', GeneralConfiguration, translations.TR_PREFERENCES_GENERAL, preferences.SECTIONS['GENERAL']) """
17,339
Python
.py
375
37.362667
80
0.685262
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,575
preferences_editor_configuration.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_editor_configuration.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QGroupBox, QCheckBox, QTreeWidget, QTreeWidgetItem, QPushButton, QGridLayout, QSpacerItem, QLabel, QSpinBox, QComboBox, QSizePolicy ) from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.tools import ui_tools from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences class EditorConfiguration(QWidget): """EditorConfiguration widget class""" def __init__(self, parent): super(EditorConfiguration, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) # groups group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_INDENT) group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_MARGIN) group3 = QGroupBox(translations.TR_LINT_DIRTY_TEXT) group4 = QGroupBox(translations.TR_PEP8_DIRTY_TEXT) group5 = QGroupBox(translations.TR_HIGHLIGHTER_EXTRAS) group6 = QGroupBox(translations.TR_TYPING_ASSISTANCE) group7 = QGroupBox(translations.TR_DISPLAY) # groups container container_widget_with_all_preferences = QWidget() formFeatures = QGridLayout(container_widget_with_all_preferences) # Indentation hboxg1 = QHBoxLayout(group1) hboxg1.setContentsMargins(5, 15, 5, 5) self._spin, self._checkUseTabs = QSpinBox(), QComboBox() self._spin.setRange(1, 10) self._spin.setValue(settings.INDENT) hboxg1.addWidget(self._spin) self._checkUseTabs.addItems([ translations.TR_PREFERENCES_EDITOR_CONFIG_SPACES.capitalize(), translations.TR_PREFERENCES_EDITOR_CONFIG_TABS.capitalize()]) self._checkUseTabs.setCurrentIndex(int(settings.USE_TABS)) hboxg1.addWidget(self._checkUseTabs) formFeatures.addWidget(group1, 0, 0) # Margin Line hboxg2 = QHBoxLayout(group2) hboxg2.setContentsMargins(5, 15, 5, 5) self._checkShowMargin = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MARGIN_LINE) self._checkShowMargin.setChecked(settings.SHOW_MARGIN_LINE) hboxg2.addWidget(self._checkShowMargin) self._spinMargin = QSpinBox() self._spinMargin.setRange(50, 100) self._spinMargin.setSingleStep(2) self._spinMargin.setValue(settings.MARGIN_LINE) hboxg2.addWidget(self._spinMargin) hboxg2.addWidget(QLabel(translations.TR_CHARACTERS)) formFeatures.addWidget(group2, 0, 1) # Display Errors vboxDisplay = QVBoxLayout(group7) vboxDisplay.setContentsMargins(5, 15, 5, 5) self._checkHighlightLine = QComboBox() self._checkHighlightLine.addItems([ translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_BACKGROUND, translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_UNDERLINE]) self._checkHighlightLine.setCurrentIndex( int(settings.UNDERLINE_NOT_BACKGROUND)) hboxDisplay1 = QHBoxLayout() hboxDisplay1.addWidget(QLabel(translations.TR_DISPLAY_ERRORS)) hboxDisplay1.addWidget(self._checkHighlightLine) hboxDisplay2 = QHBoxLayout() self._checkDisplayLineNumbers = QCheckBox( translations.TR_DISPLAY_LINE_NUMBERS) self._checkDisplayLineNumbers.setChecked(settings.SHOW_LINE_NUMBERS) hboxDisplay2.addWidget(self._checkDisplayLineNumbers) vboxDisplay.addLayout(hboxDisplay1) vboxDisplay.addLayout(hboxDisplay2) formFeatures.addWidget(group7, 1, 0, 1, 0) # Find Lint Errors (highlighter) vboxg3 = QVBoxLayout(group3) self._checkErrors = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS) self._checkErrors.setChecked(settings.FIND_ERRORS) self._checkErrors.stateChanged[int].connect(self._disable_show_errors) self._showErrorsOnLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS) self._showErrorsOnLine.setChecked(settings.ERRORS_HIGHLIGHT_LINE) self._showErrorsOnLine.stateChanged[int].connect( self._enable_errors_inline) vboxg3.addWidget(self._checkErrors) vboxg3.addWidget(self._showErrorsOnLine) vboxg3.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding)) formFeatures.addWidget(group3, 2, 0) # Find PEP8 Errors (highlighter) vboxg4 = QHBoxLayout(group4) vboxg4.setContentsMargins(5, 15, 5, 5) vvbox = QVBoxLayout() self._checkStyle = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8) self._checkStyle.setChecked(settings.CHECK_STYLE) self._checkStyle.stateChanged[int].connect(self._disable_check_style) vvbox.addWidget(self._checkStyle) self._checkStyleOnLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8) self._checkStyleOnLine.setChecked(settings.CHECK_HIGHLIGHT_LINE) self._checkStyleOnLine.stateChanged[int].connect( self._enable_check_inline) vvbox.addWidget(self._checkStyleOnLine) vvbox.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) vboxg4.addLayout(vvbox) # Container for tree widget and buttons widget = QWidget() hhbox = QHBoxLayout(widget) hhbox.setContentsMargins(0, 0, 0, 0) # Tree Widget with custom item delegate # always adds uppercase text self._listIgnoreViolations = QTreeWidget() self._listIgnoreViolations.setObjectName("ignore_pep8") self._listIgnoreViolations.setItemDelegate(ui_tools.CustomDelegate()) self._listIgnoreViolations.setMaximumHeight(80) self._listIgnoreViolations.setHeaderLabel( translations.TR_PREFERENCES_EDITOR_CONFIG_IGNORE_PEP8) for ic in settings.IGNORE_PEP8_LIST: self._listIgnoreViolations.addTopLevelItem(QTreeWidgetItem([ic])) hhbox.addWidget(self._listIgnoreViolations) box = QVBoxLayout() box.setContentsMargins(0, 0, 0, 0) btn_add = QPushButton(QIcon(":img/add_small"), '') btn_add.setMaximumSize(26, 24) btn_add.clicked.connect(self._add_code_pep8) box.addWidget(btn_add) btn_remove = QPushButton(QIcon(":img/delete_small"), '') btn_remove.setMaximumSize(26, 24) btn_remove.clicked.connect(self._remove_code_pep8) box.addWidget(btn_remove) box.addItem(QSpacerItem(0, 0, QSizePolicy.Fixed, QSizePolicy.Expanding)) hhbox.addLayout(box) vboxg4.addWidget(widget) formFeatures.addWidget(group4) # Show Python3 Migration, DocStrings and Spaces (highlighter) vboxg5 = QVBoxLayout(group5) vboxg5.setContentsMargins(5, 15, 5, 5) self._showMigrationTips = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MIGRATION) self._showMigrationTips.setChecked(settings.SHOW_MIGRATION_TIPS) vboxg5.addWidget(self._showMigrationTips) self._checkForDocstrings = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_CHECK_FOR_DOCSTRINGS) self._checkForDocstrings.setChecked(settings.CHECK_FOR_DOCSTRINGS) vboxg5.addWidget(self._checkForDocstrings) self._checkShowSpaces = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES) self._checkShowSpaces.setChecked(settings.SHOW_TABS_AND_SPACES) vboxg5.addWidget(self._checkShowSpaces) self._checkIndentationGuide = QCheckBox( translations.TR_SHOW_INDENTATION_GUIDE) self._checkIndentationGuide.setChecked(settings.SHOW_INDENTATION_GUIDE) vboxg5.addWidget(self._checkIndentationGuide) formFeatures.addWidget(group5, 3, 0) # End of line, Stop Scrolling At Last Line, Trailing space, Word wrap vboxg6 = QVBoxLayout(group6) vboxg6.setContentsMargins(5, 15, 5, 5) self._checkEndOfLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE) self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE) vboxg6.addWidget(self._checkEndOfLine) self._checkEndAtLastLine = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_END_AT_LAST_LINE) self._checkEndAtLastLine.setChecked(settings.END_AT_LAST_LINE) vboxg6.addWidget(self._checkEndAtLastLine) self._checkTrailing = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING) self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES) vboxg6.addWidget(self._checkTrailing) self._allowWordWrap = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP) self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP) vboxg6.addWidget(self._allowWordWrap) formFeatures.addWidget(group6, 3, 1) # pack all the groups vbox.addWidget(container_widget_with_all_preferences) vbox.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding)) self._preferences.savePreferences.connect(self.save) def _add_code_pep8(self): item = QTreeWidgetItem() item.setFlags(item.flags() | Qt.ItemIsEditable) self._listIgnoreViolations.addTopLevelItem(item) self._listIgnoreViolations.setCurrentItem(item) self._listIgnoreViolations.editItem(item, 0) def _remove_code_pep8(self): index = self._listIgnoreViolations.indexOfTopLevelItem( self._listIgnoreViolations.currentItem()) self._listIgnoreViolations.takeTopLevelItem(index) def _enable_check_inline(self, val): """Method that takes a value to enable the inline style checking""" if val == Qt.Checked: self._checkStyle.setChecked(True) def _enable_errors_inline(self, val): """Method that takes a value to enable the inline errors checking""" if val == Qt.Checked: self._checkErrors.setChecked(True) def _disable_check_style(self, val): """Method that takes a value to disable the inline style checking""" if val == Qt.Unchecked: self._checkStyleOnLine.setChecked(False) def _disable_show_errors(self, val): """Method that takes a value to disable the inline errors checking""" if val == Qt.Unchecked: self._showErrorsOnLine.setChecked(False) def save(self): """Method to save settings""" qsettings = IDE.ninja_settings() settings.USE_TABS = bool(self._checkUseTabs.currentIndex()) qsettings.setValue('preferences/editor/useTabs', settings.USE_TABS) margin_line = self._spinMargin.value() settings.MARGIN_LINE = margin_line settings.pycodestylemod_update_margin_line_length(margin_line) qsettings.setValue('preferences/editor/marginLine', margin_line) settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked() qsettings.setValue('preferences/editor/showMarginLine', settings.SHOW_MARGIN_LINE) settings.INDENT = self._spin.value() qsettings.setValue('preferences/editor/indent', settings.INDENT) endOfLine = self._checkEndOfLine.isChecked() settings.USE_PLATFORM_END_OF_LINE = endOfLine qsettings.setValue('preferences/editor/platformEndOfLine', endOfLine) settings.UNDERLINE_NOT_BACKGROUND = \ bool(self._checkHighlightLine.currentIndex()) qsettings.setValue('preferences/editor/errorsUnderlineBackground', settings.UNDERLINE_NOT_BACKGROUND) settings.FIND_ERRORS = self._checkErrors.isChecked() qsettings.setValue('preferences/editor/errors', settings.FIND_ERRORS) settings.ERRORS_HIGHLIGHT_LINE = self._showErrorsOnLine.isChecked() qsettings.setValue('preferences/editor/errorsInLine', settings.ERRORS_HIGHLIGHT_LINE) settings.CHECK_STYLE = self._checkStyle.isChecked() qsettings.setValue('preferences/editor/checkStyle', settings.CHECK_STYLE) settings.SHOW_MIGRATION_TIPS = self._showMigrationTips.isChecked() qsettings.setValue('preferences/editor/showMigrationTips', settings.SHOW_MIGRATION_TIPS) settings.CHECK_HIGHLIGHT_LINE = self._checkStyleOnLine.isChecked() qsettings.setValue('preferences/editor/checkStyleInline', settings.CHECK_HIGHLIGHT_LINE) settings.END_AT_LAST_LINE = self._checkEndAtLastLine.isChecked() qsettings.setValue('preferences/editor/endAtLastLine', settings.END_AT_LAST_LINE) settings.REMOVE_TRAILING_SPACES = self._checkTrailing.isChecked() qsettings.setValue('preferences/editor/removeTrailingSpaces', settings.REMOVE_TRAILING_SPACES) settings.ALLOW_WORD_WRAP = self._allowWordWrap.isChecked() qsettings.setValue('preferences/editor/allowWordWrap', settings.ALLOW_WORD_WRAP) settings.SHOW_TABS_AND_SPACES = self._checkShowSpaces.isChecked() qsettings.setValue('preferences/editor/showTabsAndSpaces', settings.SHOW_TABS_AND_SPACES) settings.SHOW_INDENTATION_GUIDE = ( self._checkIndentationGuide.isChecked()) qsettings.setValue('preferences/editor/showIndentationGuide', settings.SHOW_INDENTATION_GUIDE) settings.CHECK_FOR_DOCSTRINGS = self._checkForDocstrings.isChecked() qsettings.setValue('preferences/editor/checkForDocstrings', settings.CHECK_FOR_DOCSTRINGS) settings.SHOW_LINE_NUMBERS = self._checkDisplayLineNumbers.isChecked() qsettings.setValue('preferences/editor/showLineNumbers', settings.SHOW_LINE_NUMBERS) current_ignores = set(settings.IGNORE_PEP8_LIST) new_ignore_codes = [] # Get pep8 from tree widget for index in range(self._listIgnoreViolations.topLevelItemCount()): ignore_code = self._listIgnoreViolations.topLevelItem( index).text(0) if ignore_code: new_ignore_codes.append(ignore_code.strip()) # pep8 list that will be removed to_remove = [x for x in current_ignores if x not in new_ignore_codes] # Update list settings.IGNORE_PEP8_LIST = new_ignore_codes qsettings.setValue('preferences/editor/defaultIgnorePep8', settings.IGNORE_PEP8_LIST) # Add for ignore_code in settings.IGNORE_PEP8_LIST: settings.pycodestylemod_add_ignore(ignore_code) # Remove for ignore_code in to_remove: settings.pycodestylemod_remove_ignore(ignore_code) if settings.USE_TABS: settings.pycodestylemod_add_ignore("W191") else: settings.pycodestylemod_remove_ignore("W191") preferences.Preferences.register_configuration( 'EDITOR', EditorConfiguration, translations.TR_PREFERENCES_EDITOR_CONFIGURATION, weight=0, subsection='CONFIGURATION')
16,353
Python
.py
325
40.738462
79
0.688332
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,576
preferences_editor_scheme_designer.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_editor_scheme_designer.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import copy from getpass import getuser from string import ascii_letters from PyQt4.QtGui import QDialog from PyQt4.QtGui import QGridLayout from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QScrollArea from PyQt4.QtGui import QFrame from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QMessageBox from PyQt4.QtGui import QLineEdit from PyQt4.QtGui import QLabel from PyQt4.QtGui import QColor from PyQt4.QtGui import QColorDialog from PyQt4.QtGui import QGroupBox from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from ninja_ide import translations from ninja_ide import resources from ninja_ide.core.file_handling import file_manager from ninja_ide.tools import json_manager from ninja_ide.gui.ide import IDE class EditorSchemeDesigner(QDialog): """Editor Scheme Designer Class Widget""" def __init__(self, scheme, parent): super(EditorSchemeDesigner, self).__init__(parent, Qt.Dialog) self.original_style = copy.copy(resources.CUSTOM_SCHEME) self._avoid_on_loading, self.saved, self._components = True, False, {} self.setWindowTitle(translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER) self.setMinimumSize(450, 480) self.setMaximumSize(500, 900) self.resize(450, 600) # all layouts and groupboxes group0 = QGroupBox(translations.TR_PROJECT_NAME) # scheme filename group1 = QGroupBox(translations.TR_PROJECT_PROPERTIES) # properties group2 = QGroupBox(translations.TR_PREVIEW) # quick preview thingy group0_hbox, group1_vbox = QHBoxLayout(group0), QVBoxLayout(group1) this_dialog_vbox, group2_vbox = QVBoxLayout(self), QVBoxLayout(group2) self._grid, scrollArea, frame = QGridLayout(), QScrollArea(), QFrame() # widgets self.line_name, btnSave = QLineEdit(), QPushButton(translations.TR_SAVE) self.line_name.setPlaceholderText(getuser().capitalize() + "s_scheme") group0_hbox.addWidget(self.line_name) group0_hbox.addWidget(btnSave) self.connect(btnSave, SIGNAL("clicked()"), self.save_scheme) _demo = "<center>" + ascii_letters # demo text for preview self.preview_label1, self.preview_label2 = QLabel(_demo), QLabel(_demo) group2_vbox.addWidget(self.preview_label1) group2_vbox.addWidget(self.preview_label2) # rows titles self._grid.addWidget(QLabel("<b>" + translations.TR_PROJECT_NAME), 0, 0) self._grid.addWidget(QLabel("<b>" + translations.TR_CODE), 0, 1) self._grid.addWidget( QLabel("<b>" + translations.TR_EDITOR_SCHEME_PICK_COLOR), 0, 2) # fill rows for key in sorted(tuple(resources.COLOR_SCHEME.keys())): self.add_item(key, scheme) self.preview_label1.setStyleSheet('background:transparent') self.preview_label2.setStyleSheet('color: transparent') # fill the scroll area frame.setLayout(self._grid) scrollArea.setWidget(frame) group1_vbox.addWidget(scrollArea) # put groups on the dialog this_dialog_vbox.addWidget(group1) this_dialog_vbox.addWidget(group2) this_dialog_vbox.addWidget(group0) self._avoid_on_loading = self._modified = False def add_item(self, key, scheme): """Take key and scheme arguments and fill up the grid with widgets.""" row = self._grid.rowCount() self._grid.addWidget(QLabel(key), row, 0) isnum = isinstance(scheme[key], int) text = QLineEdit(str(scheme[key])) self._grid.addWidget(text, row, 1) if not isnum: btn = QPushButton() btn.setToolTip(translations.TR_EDITOR_SCHEME_PICK_COLOR) self.apply_button_style(btn, scheme[key]) self._grid.addWidget(btn, row, 2) self.connect(text, SIGNAL("textChanged(QString)"), lambda: self.apply_button_style(btn, text.text())) self.connect(btn, SIGNAL("clicked()"), lambda: self._pick_color(text, btn)) else: self.connect(text, SIGNAL("textChanged(QString)"), self._preview_style) self._components[key] = (text, isnum) def apply_button_style(self, btn, color_name): """Take a button widget and color name and apply as stylesheet.""" if QColor(color_name).isValid(): self._modified = True btn.setStyleSheet('background:' + color_name) self.preview_label1.setStyleSheet('background:' + color_name) self.preview_label2.setStyleSheet('color:' + color_name) self._preview_style() def _pick_color(self, lineedit, btn): """Pick a color name using lineedit and button data.""" color = QColorDialog.getColor( QColor(lineedit.text()), self, translations.TR_EDITOR_SCHEME_PICK_COLOR) if color.isValid(): lineedit.setText(str(color.name())) self.apply_button_style(btn, color.name()) def _preview_style(self): """Live preview style on editor.""" if self._avoid_on_loading: return scheme = {} keys = sorted(tuple(resources.COLOR_SCHEME.keys())) for key in keys: isnum = self._components[key][1] if isnum: num = self._components[key][0].text() if num.isdigit(): scheme[key] = int(num) else: scheme[key] = 0 else: scheme[key] = self._components[key][0].text() resources.CUSTOM_SCHEME = scheme editorWidget = self._get_editor() if editorWidget is not None: editorWidget.restyle(editorWidget.lang) editorWidget.highlight_current_line() return scheme def _get_editor(self): """Return current Editor.""" main_container = IDE.get_service("main_container") editorWidget = main_container.get_current_editor() return editorWidget def reject(self): """Reject this dialog.""" if self._modified: answer = QMessageBox.No answer = QMessageBox.question( self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER, (translations.TR_IDE_CONFIRM_EXIT_TITLE + ".\n" + translations.TR_PREFERENCES_GENERAL_CONFIRM_EXIT + "?"), QMessageBox.Yes, QMessageBox.No) if answer == QMessageBox.No: return super(EditorSchemeDesigner, self).reject() def hideEvent(self, event): """Handle Hide event on this dialog.""" super(EditorSchemeDesigner, self).hideEvent(event) resources.CUSTOM_SCHEME = self.original_style editorWidget = self._get_editor() if editorWidget is not None: editorWidget.restyle(editorWidget.lang) def _is_valid_scheme_name(self, name): """Check if a given name is a valid name for an editor scheme. Params: name := the name to check Returns: True if and only if the name is okay to use for a scheme. """ return name not in ('', 'default') def save_scheme(self): """Save current scheme.""" name = self.line_name.text().strip() if not self._is_valid_scheme_name(name): QMessageBox.information( self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER, translations.TR_SCHEME_INVALID_NAME) return fileName = ('{0}.color'.format( file_manager.create_path(resources.EDITOR_SKINS, name))) answer = True if file_manager.file_exists(fileName): answer = QMessageBox.question( self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER, translations.TR_WANT_OVERWRITE_FILE + ": {0}?".format(fileName), QMessageBox.Yes, QMessageBox.No) if answer in (QMessageBox.Yes, True): scheme = self._preview_style() self.original_style = copy.copy(scheme) json_manager.save_editor_skins(fileName, scheme) self._modified = False self.saved = True qsettings = IDE.ninja_settings() qsettings.setValue('preferences/editor/scheme', name) QMessageBox.information( self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER, translations.TR_SCHEME_SAVED + ": {0}.".format(fileName)) self.close() elif answer == QMessageBox.Yes: QMessageBox.information( self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER, translations.TR_INVALID_FILENAME)
9,616
Python
.py
208
37.033654
80
0.646275
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,577
preferences_editor_intellisense.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_editor_intellisense.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QCheckBox, QGroupBox ) from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences class EditorIntelliSense(QWidget): """Manage preferences about IntelliSense""" def __init__(self, parent): super().__init__(parent) self._preferences = parent container = QVBoxLayout(self) group_1 = QGroupBox(translations.TR_COMPLETE_CHARS) vbox = QVBoxLayout(group_1) self._check_braces = QCheckBox(translations.TR_COMPLETE_BRACKETS) vbox.addWidget(self._check_braces) self._check_quotes = QCheckBox(translations.TR_COMPLETE_QUOTES) vbox.addWidget(self._check_quotes) container.addWidget(group_1) container.addStretch(1) # Initial settings self._check_braces.setChecked(settings.AUTOCOMPLETE_BRACKETS) self._check_quotes.setChecked(settings.AUTOCOMPLETE_QUOTES) self._preferences.savePreferences.connect(self._save) def _save(self): qsettings = IDE.editor_settings() qsettings.beginGroup("editor") qsettings.beginGroup("intellisense") settings.AUTOCOMPLETE_BRACKETS = self._check_braces.isChecked() qsettings.setValue("autocomplete_brackets", settings.AUTOCOMPLETE_BRACKETS) settings.AUTOCOMPLETE_QUOTES = self._check_quotes.isChecked() qsettings.setValue("autocomplete_quotes", settings.AUTOCOMPLETE_QUOTES) qsettings.endGroup() qsettings.endGroup() preferences.Preferences.register_configuration( "EDITOR", EditorIntelliSense, "IntelliSense", weight=2, subsection="IntelliSense" )
2,523
Python
.py
63
34.142857
73
0.714928
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,578
preferences_interface.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_interface.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import os from PyQt5.QtWidgets import QWidget from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QGroupBox from PyQt5.QtWidgets import QCheckBox from PyQt5.QtWidgets import QComboBox from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QStyle from PyQt5.QtWidgets import QToolBar from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QSizePolicy from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QPushButton from PyQt5.QtCore import Qt from PyQt5.QtCore import QSize from ninja_ide import resources from ninja_ide import translations from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.gui.ide import IDE from ninja_ide.gui.dialogs.preferences import preferences class Interface(QWidget): """Interface widget class.""" def __init__(self, parent): super(Interface, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) self.toolbar_settings = settings.TOOLBAR_ITEMS groupBoxExplorer = QGroupBox( translations.TR_PREFERENCES_INTERFACE_EXPLORER_PANEL) group_theme = QGroupBox( translations.TR_PREFERENCES_THEME) group_hdpi = QGroupBox(translations.TR_PREFERENCES_SCREEN_RESOLUTION) # translations.TR_PREFERENCES_INTERFACE_TOOLBAR_CUSTOMIZATION) groupBoxLang = QGroupBox( translations.TR_PREFERENCES_INTERFACE_LANGUAGE) # Explorers vboxExplorer = QVBoxLayout(groupBoxExplorer) self._checkProjectExplorer = QCheckBox( translations.TR_PREFERENCES_SHOW_EXPLORER) self._checkSymbols = QCheckBox( translations.TR_PREFERENCES_SHOW_SYMBOLS) self._checkWebInspetor = QCheckBox( translations.TR_PREFERENCES_SHOW_WEB_INSPECTOR) self._checkFileErrors = QCheckBox( translations.TR_PREFERENCES_SHOW_FILE_ERRORS) self._checkMigrationTips = QCheckBox( translations.TR_PREFERENCES_SHOW_MIGRATION) vboxExplorer.addWidget(self._checkProjectExplorer) vboxExplorer.addWidget(self._checkSymbols) vboxExplorer.addWidget(self._checkWebInspetor) vboxExplorer.addWidget(self._checkFileErrors) vboxExplorer.addWidget(self._checkMigrationTips) # Theme vbox_theme = QVBoxLayout(group_theme) hbox = QHBoxLayout() hbox.addWidget(QLabel(translations.TR_PREFERENCES_NINJA_THEME)) self._combobox_themes = QComboBox() self._combobox_themes.setCurrentText(settings.NINJA_SKIN) hbox.addWidget(self._combobox_themes) vbox_theme.addLayout(hbox) vbox_theme.addWidget( QLabel(translations.TR_PREFERENCES_REQUIRES_RESTART)) # HDPI hbox = QHBoxLayout(group_hdpi) self._combo_resolution = QComboBox() self._combo_resolution.addItems([ translations.TR_PREFERENCES_SCREEN_NORMAL, translations.TR_PREFERENCES_SCREEN_AUTO_HDPI, translations.TR_PREFERENCES_SCREEN_CUSTOM_HDPI ]) self._combo_resolution.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed) hbox.addWidget(self._combo_resolution) self._line_custom_hdpi = QLineEdit() self._line_custom_hdpi.setPlaceholderText("1.5") hbox.addWidget(self._line_custom_hdpi) # GUI - Toolbar # self._btnDefaultItems = QPushButton( # translations.TR_PREFERENCES_TOOLBAR_DEFAULT) # self._btnDefaultItems.setSizePolicy(QSizePolicy.Fixed, # QSizePolicy.Fixed) # vbox_toolbar.addWidget(QLabel( # translations.TR_PREFERENCES_TOOLBAR_CONFIG_HELP)) # Language vboxLanguage = QVBoxLayout(groupBoxLang) vboxLanguage.addWidget(QLabel( translations.TR_PREFERENCES_SELECT_LANGUAGE)) self._comboLang = QComboBox() self._comboLang.setEnabled(False) vboxLanguage.addWidget(self._comboLang) vboxLanguage.addWidget(QLabel( translations.TR_PREFERENCES_REQUIRES_RESTART)) # Load Languages self._load_langs() # Settings self._checkProjectExplorer.setChecked( settings.SHOW_PROJECT_EXPLORER) self._checkSymbols.setChecked(settings.SHOW_SYMBOLS_LIST) self._checkWebInspetor.setChecked(settings.SHOW_WEB_INSPECTOR) self._checkFileErrors.setChecked(settings.SHOW_ERRORS_LIST) self._checkMigrationTips.setChecked(settings.SHOW_MIGRATION_LIST) self._line_custom_hdpi.setText(settings.CUSTOM_SCREEN_RESOLUTION) index = 0 if settings.HDPI: index = 1 elif settings.CUSTOM_SCREEN_RESOLUTION: index = 2 self._combo_resolution.setCurrentIndex(index) vbox.addWidget(groupBoxExplorer) vbox.addWidget(group_theme) vbox.addWidget(group_hdpi) vbox.addWidget(groupBoxLang) vbox.addStretch(1) # Signals # self.connect(self._btnItemAdd, SIGNAL("clicked()"), # # self.toolbar_item_added) # self.connect(self._btnItemRemove, SIGNAL("clicked()"), # # self.toolbar_item_removed) # self.connect(self._btnDefaultItems, SIGNAL("clicked()"), # # self.toolbar_items_default) self._combo_resolution.currentIndexChanged.connect( self._on_resolution_changed) self._preferences.savePreferences.connect(self.save) def _on_resolution_changed(self, index): enabled = False if index == 2: enabled = True self._line_custom_hdpi.setEnabled(enabled) # self._comboToolbarItems.currentIndex()) # self.toolbar_settings.insert( # self.toolbar_settings.index(dataAction) + 1, data) # self._comboToolbarItems.currentIndex()) # self.toolbar_items = { # 'new-file': [QIcon(resources.IMAGES['new']), self.tr('New File')], # 'new-project': [QIcon(resources.IMAGES['newProj']), # self.tr('New Project')], # 'save-file': [QIcon(resources.IMAGES['save']), # self.tr('Save File')], # 'save-as': [QIcon(resources.IMAGES['saveAs']), self.tr('Save As')], # 'save-all': [QIcon(resources.IMAGES['saveAll']), # self.tr('Save All')], # 'save-project': [QIcon(resources.IMAGES['saveAll']), # self.tr('Save Project')], # 'reload-file': [QIcon(resources.IMAGES['reload-file']), # self.tr('Reload File')], # 'open-file': [QIcon(resources.IMAGES['open']), # self.tr('Open File')], # 'open-project': [QIcon(resources.IMAGES['openProj']), # self.tr('Open Project')], # 'activate-profile': [QIcon(resources.IMAGES['activate-profile']), # self.tr('Activate Profile')], # 'deactivate-profile': # [QIcon(resources.IMAGES['deactivate-profile']), # self.tr('Deactivate Profile')], # 'print-file': [QIcon(resources.IMAGES['print']), # self.tr('Print File')], # 'close-file': # [self.style().standardIcon(QStyle.SP_DialogCloseButton), # self.tr('Close File')], # 'close-projects': # [self.style().standardIcon(QStyle.SP_DialogCloseButton), # self.tr('Close Projects')], # 'find-replace': [QIcon(resources.IMAGES['findReplace']), # self.tr('Find/Replace')], # 'find-files': [QIcon(resources.IMAGES['find']), # self.tr('Find In files')], # 'code-locator': [QIcon(resources.IMAGES['locator']), # self.tr('Code Locator')], # self.tr('Split Horizontally')], # self.tr('Split Vertically')], # 'follow-mode': [QIcon(resources.IMAGES['follow']), # self.tr('Follow Mode')], # 'zoom-in': [QIcon(resources.IMAGES['zoom-in']), self.tr('Zoom In')], # 'zoom-out': [QIcon(resources.IMAGES['zoom-out']), # self.tr('Zoom Out')], # 'indent-more': [QIcon(resources.IMAGES['indent-more']), # self.tr('Indent More')], # 'indent-less': [QIcon(resources.IMAGES['indent-less']), # self.tr('Indent Less')], # self.tr('Comment')], # self.tr('Uncomment')], # 'go-to-definition': [QIcon(resources.IMAGES['go-to-definition']), # self.tr('Go To Definition')], # 'insert-import': [QIcon(resources.IMAGES['insert-import']), # self.tr('Insert Import')], # 'run-project': [QIcon(resources.IMAGES['play']), 'Run Project'], # 'run-file': [QIcon(resources.IMAGES['file-run']), 'Run File'], # 'preview-web': [QIcon(resources.IMAGES['preview-web']), # self.tr('Preview Web')]} # combo.addItem(self.toolbar_items[item][0], # self.toolbar_items[item][1], item) # pass # self.toolbar_items[item][0], self.toolbar_items[item][1]) def _load_langs(self): langs = file_manager.get_files_from_folder( resources.LANGS, '.qm') self._languages = ['English'] + \ [file_manager.get_module_name(lang) for lang in langs] self._comboLang.addItems(self._languages) if(self._comboLang.count() > 1): self._comboLang.setEnabled(True) if settings.LANGUAGE: index = self._comboLang.findText(settings.LANGUAGE) else: index = 0 self._comboLang.setCurrentIndex(index) def save(self): qsettings = IDE.ninja_settings() qsettings.beginGroup("ide") qsettings.beginGroup("interface") ninja_theme = self._combobox_themes.currentText() settings.NINJA_SKIN = ninja_theme qsettings.setValue("skin", settings.NINJA_SKIN) settings.SHOW_PROJECT_EXPLORER = self._checkProjectExplorer.isChecked() qsettings.setValue("showProjectExplorer", settings.SHOW_PROJECT_EXPLORER) settings.SHOW_SYMBOLS_LIST = self._checkSymbols.isChecked() qsettings.setValue("showSymbolsList", settings.SHOW_SYMBOLS_LIST) if self._line_custom_hdpi.isEnabled(): screen_resolution = self._line_custom_hdpi.text().strip() settings.CUSTOM_SCREEN_RESOLUTION = screen_resolution else: settings.HDPI = bool(self._combo_resolution.currentIndex()) qsettings.setValue("autoHdpi", settings.HDPI) settings.CUSTOM_SCREEN_RESOLUTION = "" qsettings.setValue("customScreenResolution", settings.CUSTOM_SCREEN_RESOLUTION) qsettings.endGroup() qsettings.endGroup() # preferences/interface # qsettings.setValue('preferences/interface/showProjectExplorer', # self._checkProjectExplorer.isChecked()) # qsettings.setValue('preferences/interface/showSymbolsList', # self._checkSymbols.isChecked()) # qsettings.setValue('preferences/interface/showWebInspector', # self._checkWebInspetor.isChecked()) # qsettings.setValue('preferences/interface/showErrorsList', # self._checkFileErrors.isChecked()) # qsettings.setValue('preferences/interface/showMigrationList', # self._checkMigrationTips.isChecked()) # qsettings.setValue('preferences/interface/toolbar', # settings.TOOLBAR_ITEMS) preferences.Preferences.register_configuration( 'GENERAL', Interface, translations.TR_PREFERENCES_INTERFACE, weight=0, subsection="INTERFACE" )
12,394
Python
.py
268
37.996269
79
0.656309
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,579
preferences_editor_display.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_editor_display.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QSpinBox, QLabel, QGroupBox, QCheckBox, QComboBox ) from PyQt5.QtCore import Qt from ninja_ide.core import settings from ninja_ide import translations from ninja_ide.gui.dialogs.preferences import preferences from ninja_ide.gui.ide import IDE class EditorDisplay(QWidget): """EditorDisplay widget class""" def __init__(self, parent): super().__init__(parent) self._preferences = parent container = QVBoxLayout(self) # Groups group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_DISPLAY_WRAPPING) group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_DISPLAY) group3 = QGroupBox(translations.TR_PREFERENCES_EDITOR_DISPLAY_LINT) # Text wrapping vbox = QVBoxLayout(group1) self._check_text_wrapping = QCheckBox( translations.TR_PREFERENCES_EDITOR_DISPLAY_ENABLE_TEXT_WRAPPING) vbox.addWidget(self._check_text_wrapping) self._check_margin_line = QCheckBox( translations.TR_PREFERENCES_EDITOR_DISPLAY_RIGHT_MARGIN_LABEL) hbox = QHBoxLayout() hbox.addWidget(self._check_margin_line) self._spin_margin_line = QSpinBox() hbox.addWidget(self._spin_margin_line) self._check_margin_line_background = QCheckBox( translations.TR_PREFERENCES_EDITOR_DISPLAY_RIGHT_MARGIN_BACKGROUND) hbox.addWidget(self._check_margin_line_background) vbox.addLayout(hbox) # Display features vbox = QVBoxLayout(group2) self._check_platform_eol = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE) vbox.addWidget(self._check_platform_eol) self._check_lineno = QCheckBox(translations.TR_DISPLAY_LINE_NUMBERS) vbox.addWidget(self._check_lineno) self._check_indentation_guides = QCheckBox( translations.TR_SHOW_INDENTATION_GUIDES) vbox.addWidget(self._check_indentation_guides) self._check_text_changes = QCheckBox( translations.TR_DISPLAY_TEXT_CHANGES) vbox.addWidget(self._check_text_changes) self._check_brace_matching = QCheckBox( translations.TR_PREFERENCES_EDITOR_DISPLAY_HIGHLIGHT_BRACKETS) vbox.addWidget(self._check_brace_matching) hbox = QHBoxLayout() self._check_current_line = QCheckBox( translations.TR_PREFERENCES_EDITOR_DISPLAY_HIGHLIGHT_CURRENT_LINE) self._combo_current_line = QComboBox() self._combo_current_line.addItems([ "Full", "Simple" ]) self._check_current_line.stateChanged.connect( lambda state: self._combo_current_line.setEnabled(state)) hbox.addWidget(self._check_current_line) hbox.addWidget(self._combo_current_line) vbox.addLayout(hbox) self._check_show_tabs = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES) vbox.addWidget(self._check_show_tabs) self._check_highlight_results = QCheckBox( translations.TR_HIGHLIGHT_RESULT_ON_SCROLLBAR) vbox.addWidget(self._check_highlight_results) self._check_center_on_scroll = QCheckBox( translations.TR_CENTER_ON_SCROLL) vbox.addWidget(self._check_center_on_scroll) # Linter vbox = QVBoxLayout(group3) self._check_find_errors = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS) vbox.addWidget(self._check_find_errors) self._check_show_tooltip_error = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS) vbox.addWidget( self._check_show_tooltip_error, alignment=Qt.AlignCenter) self._check_highlight_pep8 = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8) vbox.addWidget(self._check_highlight_pep8) self._check_show_tooltip_pep8 = QCheckBox( translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8) vbox.addWidget(self._check_show_tooltip_pep8, alignment=Qt.AlignCenter) self._check_highlight_pep8.stateChanged.connect( lambda state: self._check_show_tooltip_pep8.setEnabled(state)) container.addWidget(group1) container.addWidget(group2) container.addWidget(group3) container.addStretch(1) # Settings self._check_text_wrapping.setChecked(settings.ALLOW_WORD_WRAP) self._check_highlight_pep8.setChecked(settings.CHECK_STYLE) self._check_indentation_guides.setChecked( settings.SHOW_INDENTATION_GUIDES) self._check_find_errors.setChecked(settings.FIND_ERRORS) self._check_show_tooltip_pep8.setEnabled(settings.CHECK_STYLE) self._check_show_tabs.setChecked(settings.SHOW_TABS_AND_SPACES) self._check_margin_line.setChecked(settings.SHOW_MARGIN_LINE) self._check_text_changes.setChecked(settings.SHOW_TEXT_CHANGES) self._spin_margin_line.setValue(settings.MARGIN_LINE) self._check_margin_line_background.setChecked( settings.MARGIN_LINE_BACKGROUND) self._check_current_line.setChecked(settings.HIGHLIGHT_CURRENT_LINE) self._combo_current_line.setCurrentIndex( settings.HIGHLIGHT_CURRENT_LINE_MODE) self._check_brace_matching.setChecked(settings.BRACE_MATCHING) self._check_lineno.setChecked(settings.SHOW_LINE_NUMBERS) self._preferences.savePreferences.connect(self._save) def _save(self): qsettings = IDE.editor_settings() qsettings.beginGroup("editor") qsettings.beginGroup("display") settings.ALLOW_WORD_WRAP = self._check_text_wrapping.isChecked() qsettings.setValue("allow_word_wrap", settings.ALLOW_WORD_WRAP) settings.SHOW_TABS_AND_SPACES = self._check_show_tabs.isChecked() qsettings.setValue("show_whitespaces", settings.SHOW_TABS_AND_SPACES) settings.SHOW_INDENTATION_GUIDES = \ self._check_indentation_guides.isChecked() # qsettings.setValue("show_indentation_guides", # settings.SHOW_INDENTATION_GUIDES) settings.SHOW_MARGIN_LINE = self._check_margin_line.isChecked() qsettings.setValue("margin_line", settings.SHOW_MARGIN_LINE) settings.MARGIN_LINE = self._spin_margin_line.value() qsettings.setValue("margin_line_position", settings.MARGIN_LINE) settings.MARGIN_LINE_BACKGROUND = \ self._check_margin_line_background.isChecked() qsettings.setValue("margin_line_background", settings.MARGIN_LINE_BACKGROUND) settings.HIGHLIGHT_CURRENT_LINE = self._check_current_line.isChecked() qsettings.setValue("highlight_current_line", settings.HIGHLIGHT_CURRENT_LINE) settings.HIGHLIGHT_CURRENT_LINE_MODE = \ self._combo_current_line.currentIndex() qsettings.setValue("current_line_mode", settings.HIGHLIGHT_CURRENT_LINE_MODE) settings.BRACE_MATCHING = self._check_brace_matching.isChecked() qsettings.setValue("brace_matching", settings.BRACE_MATCHING) settings.SHOW_LINE_NUMBERS = self._check_lineno.isChecked() qsettings.setValue("show_line_numbers", settings.SHOW_LINE_NUMBERS) settings.SHOW_TEXT_CHANGES = self._check_text_changes.isChecked() qsettings.setValue("show_text_changes", settings.SHOW_TEXT_CHANGES) settings.CHECK_STYLE = self._check_highlight_pep8.isChecked() qsettings.setValue("check_style", settings.CHECK_STYLE) settings.FIND_ERRORS = self._check_find_errors.isChecked() qsettings.setValue("check_errors", settings.FIND_ERRORS) qsettings.endGroup() qsettings.endGroup() # FIXME: improve # editor.set_current_line_highlighter( # settings.HIGHLIGHT_CURRENT_LINE) # editor.set_current_line_highlighter_mode( # settings.HIGHLIGHT_CURRENT_LINE_MODE) preferences.Preferences.register_configuration( 'EDITOR', EditorDisplay, "Display", weight=1, subsection="EDITOR" )
9,024
Python
.py
186
39.919355
79
0.688131
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,580
preferences.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtWidgets import ( QDialog, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QSpacerItem, QSizePolicy, QTreeWidget, QScrollArea, QTreeWidgetItem, QLabel, QHeaderView, QStackedLayout, QDialogButtonBox ) from PyQt5.QtCore import ( Qt, pyqtSignal, pyqtSlot ) from ninja_ide import translations SECTIONS = { 'GENERAL': 0, 'EDITOR': 2 } class Preferences(QDialog): configuration = {} weight = 0 # Signals savePreferences = pyqtSignal() def __init__(self, parent=None): super().__init__(parent, Qt.Dialog) self.setWindowTitle(translations.TR_PREFERENCES_TITLE) self.setMinimumSize(900, 650) box = QVBoxLayout(self) box.setContentsMargins(3, 3, 3, 3) self.setAutoFillBackground(True) # Header self._header_label = QLabel("") header_font = self._header_label.font() header_font.setBold(True) header_font.setPointSize(header_font.pointSize() + 4) self._header_label.setFont(header_font) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) self.tree = QTreeWidget() self.tree.header().setHidden(True) self.tree.setSelectionMode(QTreeWidget.SingleSelection) self.tree.setAnimated(True) self.tree.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self.tree.setFixedWidth(200) hbox.addWidget(self.tree) self.stacked = QStackedLayout() header_layout = QVBoxLayout() header_layout.setContentsMargins(0, 0, 0, 0) header_layout.addWidget(self._header_label) header_layout.addLayout(self.stacked) hbox.addLayout(header_layout) box.addLayout(hbox) # Footer buttons button_box = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) box.addWidget(button_box) # Connections button_box.rejected.connect(self.close) button_box.accepted.connect(self._save_preferences) self.tree.selectionModel().currentRowChanged.connect( self._change_current) self.load_ui() @pyqtSlot() def _save_preferences(self): self.savePreferences.emit() self.close() def load_ui(self): sections = sorted( Preferences.configuration.keys(), key=lambda item: Preferences.configuration[item]['weight']) for section in sections: text = Preferences.configuration[section]['text'] Widget = Preferences.configuration[section]['widget'] widget = Widget(self) area = QScrollArea() area.setWidgetResizable(True) area.setWidget(widget) self.stacked.addWidget(area) index = self.stacked.indexOf(area) item = QTreeWidgetItem([text]) item.setData(0, Qt.UserRole, index) self.tree.addTopLevelItem(item) # Sort Item Children subcontent = Preferences.configuration[section].get( 'subsections', {}) subsections = sorted( subcontent.keys(), key=lambda item: subcontent[item]['weight']) for sub in subsections: text = subcontent[sub]['text'] Widget = subcontent[sub]['widget'] widget = Widget(self) area = QScrollArea() area.setWidgetResizable(True) area.setWidget(widget) self.stacked.addWidget(area) index = self.stacked.indexOf(area) subitem = QTreeWidgetItem([text]) subitem.setData(0, Qt.UserRole, index) item.addChild(subitem) self.tree.expandAll() self.tree.setCurrentIndex(self.tree.model().index(0, 0)) def _change_current(self): item = self.tree.currentItem() index = item.data(0, Qt.UserRole) self.stacked.setCurrentIndex(index) self._header_label.setText(item.text(0)) @classmethod def register_configuration(cls, section, widget, text, weight=None, subsection=None): if weight is None: Preferences.weight += 1 weight = Preferences.weight if subsection is None: Preferences.configuration[section] = { 'widget': widget, 'weight': weight, 'text': text } else: config = Preferences.configuration.get(section, {}) if not config: config[section] = { 'widget': None, 'weight': 100 } subconfig = config.get('subsections', {}) subconfig[subsection] = { 'widget': widget, 'weight': weight, 'text': text } config['subsections'] = subconfig Preferences.configuration[section] = config """ from __future__ import absolute_import from __future__ import unicode_literals from PyQt4.QtGui import QDialog from PyQt4.QtGui import QTreeWidget from PyQt4.QtGui import QTreeWidgetItem from PyQt4.QtGui import QStackedLayout from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QScrollArea from PyQt4.QtGui import QAbstractItemView from PyQt4.QtGui import QHeaderView from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QSpacerItem from PyQt4.QtGui import QSizePolicy from PyQt4.QtCore import QSize from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from ninja_ide import translations SECTIONS = { 'GENERAL': 0, 'INTERFACE': 1, 'EDITOR': 2, 'PLUGINS': 3, 'THEME': 4, } class Preferences(QDialog): configuration = {} weight = 0 def __init__(self, parent=None): super(Preferences, self).__init__(parent, Qt.Dialog) self.setWindowTitle(translations.TR_PREFERENCES_TITLE) self.setMinimumSize(QSize(900, 600)) vbox = QVBoxLayout(self) hbox = QHBoxLayout() vbox.setContentsMargins(0, 0, 5, 5) hbox.setContentsMargins(0, 0, 0, 0) self.tree = QTreeWidget() self.tree.header().setHidden(True) self.tree.setSelectionMode(QTreeWidget.SingleSelection) self.tree.setAnimated(True) self.tree.header().setHorizontalScrollMode( QAbstractItemView.ScrollPerPixel) self.tree.header().setResizeMode(0, QHeaderView.ResizeToContents) self.tree.header().setStretchLastSection(False) self.tree.setFixedWidth(200) self.stacked = QStackedLayout() hbox.addWidget(self.tree) hbox.addLayout(self.stacked) vbox.addLayout(hbox) hbox_footer = QHBoxLayout() self._btnSave = QPushButton(translations.TR_SAVE) self._btnCancel = QPushButton(translations.TR_CANCEL) hbox_footer.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox_footer.addWidget(self._btnCancel) hbox_footer.addWidget(self._btnSave) vbox.addLayout(hbox_footer) self.connect(self.tree, SIGNAL("itemSelectionChanged()"), self._change_current) self.connect(self._btnCancel, SIGNAL("clicked()"), self.close) self.connect(self._btnSave, SIGNAL("clicked()"), self._save_preferences) self.load_ui() self.tree.setCurrentItem(self.tree.topLevelItem(0)) def _save_preferences(self): self.emit(SIGNAL("savePreferences()")) self.close() def load_ui(self): sections = sorted( list(Preferences.configuration.keys()), key=lambda item: Preferences.configuration[item]['weight']) for section in sections: text = Preferences.configuration[section]['text'] Widget = Preferences.configuration[section]['widget'] widget = Widget(self) area = QScrollArea() area.setWidgetResizable(True) area.setWidget(widget) self.stacked.addWidget(area) index = self.stacked.indexOf(area) item = QTreeWidgetItem([text]) item.setData(0, Qt.UserRole, index) self.tree.addTopLevelItem(item) #Sort Item Children subcontent = Preferences.configuration[section].get( 'subsections', {}) subsections = sorted(list(subcontent.keys()), key=lambda item: subcontent[item]['weight']) for sub in subsections: text = subcontent[sub]['text'] Widget = subcontent[sub]['widget'] widget = Widget(self) area = QScrollArea() area.setWidgetResizable(True) area.setWidget(widget) self.stacked.addWidget(area) index = self.stacked.indexOf(area) subitem = QTreeWidgetItem([text]) subitem.setData(0, Qt.UserRole, index) item.addChild(subitem) self.tree.expandAll() def _change_current(self): item = self.tree.currentItem() index = item.data(0, Qt.UserRole) self.stacked.setCurrentIndex(index) @classmethod def register_configuration(cls, section, widget, text, weight=None, subsection=None): if weight is None: Preferences.weight += 1 weight = Preferences.weight if not subsection: Preferences.configuration[section] = {'widget': widget, 'weight': weight, 'text': text} else: config = Preferences.configuration.get(section, {}) if not config: config[section] = {'widget': None, 'weight': 100} subconfig = config.get('subsections', {}) subconfig[subsection] = {'widget': widget, 'weight': weight, 'text': text} config['subsections'] = subconfig Preferences.configuration[section] = config """
10,975
Python
.py
283
28.971731
79
0.616822
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,581
preferences_theme_editor.py
ninja-ide_ninja-ide/ninja_ide/gui/dialogs/preferences/preferences_theme_editor.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from getpass import getuser from PyQt4.QtGui import QDialog from PyQt4.QtGui import QApplication from PyQt4.QtGui import QVBoxLayout from PyQt4.QtGui import QHBoxLayout from PyQt4.QtGui import QPushButton from PyQt4.QtGui import QMessageBox from PyQt4.QtGui import QLineEdit from PyQt4.QtGui import QGroupBox from PyQt4.QtGui import QSizePolicy from PyQt4.QtGui import QSpacerItem from PyQt4.QtGui import QPlainTextEdit from PyQt4.QtCore import Qt from PyQt4.QtCore import SIGNAL from ninja_ide import translations from ninja_ide import resources from ninja_ide.core.file_handling import file_manager class ThemeEditor(QDialog): """ThemeEditor Scheme Designer Class Widget""" def __init__(self, parent): super(ThemeEditor, self).__init__(parent, Qt.Dialog) vbox = QVBoxLayout(self) hbox = QHBoxLayout() self.line_name = QLineEdit() self.btn_save = QPushButton(translations.TR_SAVE) self.line_name.setPlaceholderText(getuser().capitalize() + "s_theme") hbox.addWidget(self.line_name) hbox.addWidget(self.btn_save) self.edit_qss = QPlainTextEdit() css = 'QPlainTextEdit {color: %s; background-color: %s;' \ 'selection-color: %s; selection-background-color: %s;}' \ % (resources.CUSTOM_SCHEME.get( 'editor-text', resources.COLOR_SCHEME['Default']), resources.CUSTOM_SCHEME.get( 'EditorBackground', resources.COLOR_SCHEME['EditorBackground']), resources.CUSTOM_SCHEME.get( 'EditorSelectionColor', resources.COLOR_SCHEME['EditorSelectionColor']), resources.CUSTOM_SCHEME.get( 'EditorSelectionBackground', resources.COLOR_SCHEME['EditorSelectionBackground'])) self.edit_qss.setStyleSheet(css) self.btn_apply = QPushButton(self.tr("Apply Style Sheet")) hbox2 = QHBoxLayout() hbox2.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding, QSizePolicy.Fixed)) hbox2.addWidget(self.btn_apply) hbox2.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding, QSizePolicy.Fixed)) vbox.addWidget(self.edit_qss) vbox.addLayout(hbox) vbox.addLayout(hbox2) self.connect(self.btn_apply, SIGNAL("clicked()"), self.apply_stylesheet) self.connect(self.btn_save, SIGNAL("clicked()"), self.save_stylesheet) def apply_stylesheet(self): qss = self.edit_qss.toPlainText() QApplication.instance().setStyleSheet(qss) def save_stylesheet(self): try: file_name = "%s.qss" % self.line_name.text() if not self._is_valid_scheme_name(file_name): QMessageBox.information( self, translations.TR_PREFERENCES_THEME, translations.TR_SCHEME_INVALID_NAME) file_name = ('{0}.qss'.format( file_manager.create_path( resources.NINJA_THEME_DOWNLOAD, file_name))) content = self.edit_qss.toPlainText() answer = True if file_manager.file_exists(file_name): answer = QMessageBox.question( self, translations.TR_PREFERENCES_THEME, translations.TR_WANT_OVERWRITE_FILE + ": {0}?".format( file_name), QMessageBox.Yes, QMessageBox.No) if answer in (QMessageBox.Yes, True): self.apply_stylesheet() file_manager.store_file_content( file_name, content, newFile=True) self.close() except file_manager.NinjaFileExistsException as ex: QMessageBox.information( self, self.tr("File Already Exists"), (self.tr("Invalid File Name: the file '%s' already exists.") % ex.filename)) def _is_valid_scheme_name(self, name): """Check if a given name is a valid name for an editor scheme. Params: name := the name to check Returns: True if and only if the name is okay to use for a scheme. """ return name not in ('', 'Default')
5,090
Python
.py
111
36.162162
80
0.643087
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,582
plugin_services.py
ninja-ide_ninja-ide/ninja_ide/core/plugin_services.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from PyQt4.QtCore import QObject from PyQt4.QtCore import pyqtSignal from ninja_ide.core import settings from ninja_ide.core.file_handling import file_manager from ninja_ide.core import plugin_util from ninja_ide.gui.main_panel import itab_item ############################################################################### # PLUGINS SERVICES ############################################################################### class MainService(QObject): """ Main Interact whith NINJA-IDE """ # SIGNALS editorKeyPressEvent = pyqtSignal("QEvent") beforeFileSaved = pyqtSignal("QString") fileSaved = pyqtSignal("QString") currentTabChanged = pyqtSignal("QString") fileExecuted = pyqtSignal("QString") fileOpened = pyqtSignal("QString") def __init__(self): QObject.__init__(self) # Connect signals # self.connect(self._main, SIGNAL("editorKeyPressEvent(QEvent)"), # self._keyPressEvent) # self.connect(self._main, SIGNAL("beforeFileSaved(QString)"), # self._beforeFileSaved) # self.connect(self._main, SIGNAL("fileSaved(QString)"), # self._fileSaved) # self.connect(self._main, SIGNAL("currentTabChanged(QString)"), # self._currentTabChanged) # self.connect(self._action, SIGNAL("fileExecuted(QString)"), # self._fileExecuted) # self.connect(self._main, SIGNAL("fileOpened(QString)"), # self._fileOpened) ############################################################################### # Get main GUI Objects ############################################################################### def get_tab_manager(self): """ Returns the TabWidget (ninja_ide.gui.main_panel.tab_widget.TabWidget) subclass of QTabWidget """ return self._main.actualTab ############################################################################### # END main GUI Objects ############################################################################### def add_menu(self, menu, lang=".py"): """ Add an *extra context menu* to the editor context menu """ itab_item.ITabItem.add_extra_menu(menu, lang=lang) def get_opened_documents(self): """ Returns the opened documents """ documents_data = self._main.get_opened_documents() # returns ONLY names! return [doc_data[0] for doc_list in documents_data for doc_data in doc_list] def get_project_owner(self, editorWidget=None): """ Return the project where this file belongs, or an empty string. """ # if not editor try to get the current if editorWidget is None: editorWidget = self._main.get_current_editor() belongs = '' if editorWidget is None: return belongs # get the opened projects opened_projects_obj = self._explorer.get_opened_projects() for project in opened_projects_obj: if file_manager.belongs_to_folder(project.path, editorWidget.ID): belongs = project.path break return belongs def get_file_syntax(self, editorWidget=None): """Return the syntax for this file -> {}.""" if editorWidget is None: editorWidget = self._main.get_current_editor() if editorWidget is not None: ext = file_manager.get_file_extension(editorWidget.ID) lang = settings.EXTENSIONS.get(ext, '') syntax = settings.SYNTAX.get(lang, {}) return syntax return {} def add_editor(self, fileName="", content=None, syntax=None): """ Create a new editor """ editor = self._main.add_editor(fileName=fileName, syntax=syntax) if content: editor.setPlainText(content) return editor def get_editor(self): """ Returns the actual editor (instance of ninja_ide.gui.editor.Editor) This method could return None """ return self._main.get_current_editor() def get_editor_path(self): """ Returns the actual editor path This method could return None if there is not an editor """ editor = self._main.get_current_editor() if editor: return editor.ID return None def get_editor_encoding(self, editorWidget=None): """ Returns the editor encoding """ if editorWidget is None: editorWidget = self._main.get_current_editor() if editorWidget is not None: return editorWidget.encoding return None def get_text(self): """ Returns the plain text of the current editor or None if thre is not an editor. """ editor = self._main.get_current_editor() if editor: return editor.get_text() return def get_selected_text(self): """ Returns the selected text of and editor. This method could return None """ editor = self._main.get_current_editor() if editor: return editor.textCursor().selectedText() return None def insert_text(self, text): """ Insert text in the current cursor position @text: string """ editor = self._main.get_current_editor() if editor: editor.insertPlainText(text) def jump_to_line(self, lineno): """ Jump to a specific line in the current editor """ self._main.editor_jump_to_line(lineno=lineno) def get_lines_count(self): """ Returns the count of lines in the current editor """ editor = self._main.get_current_editor() if editor: return editor.get_lines_count() return None def save_file(self): """ Save the actual file """ self._main.save_file() def open_files(self, files, mainTab=True): """ Open many files """ self._main.open_files(self, files, mainTab=mainTab) def open_file(self, fileName='', cursorPosition=0, positionIsLineNumber=False): """ Open a single file, if the file is already open it get focus """ self._main.open_file(filename=fileName, cursorPosition=cursorPosition, positionIsLineNumber=positionIsLineNumber) def open_image(self, filename): """ Open a single image """ self._main.open_image(filename) def get_actual_tab(self): """ Returns the actual widget """ return self._main.get_actual_widget() # SIGNALS def _keyPressEvent(self, qEvent): """ Emit the signal when a key is pressed @event: QEvent """ self.editorKeyPressEvent.emit(qEvent) def _beforeFileSaved(self, fileName): """ Signal emitted before save a file """ self.beforeFileSaved.emit(fileName) def _fileSaved(self, fileName): """ Signal emitted after save a file """ fileName = fileName.split(":")[-1].strip() self.fileSaved.emit(fileName) def _currentTabChanged(self, fileName): """ Signal emitted when the current tab changes """ self.currentTabChanged.emit(fileName) def _fileExecuted(self, fileName): """ Signal emitted when the file is executed """ self.fileExecuted.emit(fileName) def _fileOpened(self, fileName): """ Signal emitted when the file is opened """ self.fileOpened.emit(fileName) class ToolbarService(QObject): """ Interact with the Toolbar """ def __init__(self, toolbar): QObject.__init__(self) self._toolbar = toolbar def add_action(self, action): """ Add an action to the Toolbar @action: Should be an instance(or subclass) of QAction """ settings.add_toolbar_item_for_plugins(action) self._toolbar.addAction(action) class MenuAppService(QObject): """ Interact with the Plugins Menu """ def __init__(self, plugins_menu): QObject.__init__(self) self._plugins_menu = plugins_menu def add_menu(self, menu): """ Add an extra menu to the Plugin Menu of NINJA """ self._plugins_menu.addMenu(menu) def add_action(self, action): """ Add an action to the Plugin Menu of NINJA """ self._plugins_menu.addAction(action) # """ # Interact with the New Project Wizard # """ # # """ # Add a new Project Type and the handler for it # example: # Then 'Foo Project' will appear in the New Project wizard # and foo_project_handler instance controls the wizard # # Note: project_type_handler SHOULD have a special interface see # ninja_ide.core.plugin_interfaces # """ # # # """ # Interact with the symbols tree # """ # # """ # Add a new Symbol's handler for the given file extension # example: # Then all symbols in .cpp files will be handle by cpp_symbols_handler # # Note: symbols_handler SHOULD have a special interface see # ninja_ide.core.plugin_interfaces # """ class ExplorerService(QObject): # SIGNALS projectOpened = pyqtSignal("QString") projectExecuted = pyqtSignal("QString") def __init__(self): QObject.__init__(self) # self.connect(self._explorer, SIGNAL("projectOpened(QString)"), # self._projectOpened) # self.connect(self._action, SIGNAL("projectExecuted(QString)"), # self._projectExecuted) def get_tree_projects(self): """ Returns the projects tree """ return self._explorer._treeProjects def get_item(self, path): if self._explorer._treeProjects: return self._explorer._treeProjects.get_item_for_path(path) def get_current_project_item(self): """ Returns the current item of the tree projects this method is a shortcut of self.get_tree_projects().currentItem() """ if self._explorer._treeProjects: return self._explorer._treeProjects.currentItem() return None def get_project_item_by_name(self, projectName): """ Return a ProjectItem that has the name provided. """ if self._explorer._treeProjects: return self._explorer._treeProjects.get_project_by_name( projectName) return None def get_tree_symbols(self): """ Returns the symbols tree """ return self._explorer._treeSymbols def set_symbols_handler(self, file_extension, symbols_handler): """ Add a new Symbol's handler for the given file extension example: cpp_symbols_handler = CppSymbolHandler(...) set_symbols_handler('cpp', cpp_symbols_handler) Then all symbols in .cpp files will be handle by cpp_symbols_handler Note: symbols_handler SHOULD have a special interface see ninja_ide.core.plugin_interfaces """ settings.set_symbols_handler(file_extension, symbols_handler) def set_project_type_handler(self, project_type, project_type_handler): """ Add a new Project Type and the handler for it example: foo_project_handler = FooProjectHandler(...) set_project_type_handler('Foo Project', foo_project_handler) Then 'Foo Project' will appear in the New Project wizard and foo_project_handler instance controls the wizard Note: project_type_handler SHOULD have a special interface see ninja_ide.core.plugin_interfaces """ settings.set_project_type_handler(project_type, project_type_handler) def add_tab(self, tab, title): """ Add a tab with the given title @tab: Should be an instance (or subclass )of QTabWidget @title: Name of the tab string """ self._explorer.addTab(tab, title) def get_actual_project(self): """ Returns the path of the opened projects """ return self._explorer.get_actual_project() def get_opened_projects(self): """ Return the opened projects in the Tree Project Explorer. list of <ninja_ide.gui.explorer.tree_projects_widget.ProjectTree> """ opened_projects = self._explorer.get_opened_projects() return opened_projects def add_project_menu(self, menu, lang='all'): """ Add an extra menu to the project explorer for the files with the given extension. @lang: String with file extension format (py, php, json) """ if self._explorer._treeProjects: self._explorer._treeProjects.add_extra_menu(menu, lang=lang) def add_project_menu_by_scope(self, menu, scope=None): """ Add an extra menu to the project explorer to the specific scope @scope: String with the menu scope (all, project, folder, file) """ if scope is None: # default behavior show ALL scope = plugin_util.ContextMenuScope(project=True, folder=True, files=True) if self._explorer._treeProjects: self._explorer._treeProjects.add_extra_menu_by_scope(menu, scope) # SIGNALS def _projectOpened(self, projectPath): """ Signal emitted when the project is opened """ self.projectOpened.emit(projectPath) def _projectExecuted(self, projectPath): """ Signal emitted when the project is executed """ self.projectExecuted.emit(projectPath)
14,794
Python
.py
405
28.755556
79
0.601592
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,583
nsettings.py
ninja-ide_ninja-ide/ninja_ide/core/nsettings.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals from PyQt5.QtCore import ( QSettings, pyqtSignal ) class NSettings(QSettings): """Extend QSettings to emit a signal when a value change.""" valueChanged = pyqtSignal("QString", "PyQt_PyObject") def __init__(self, path, fformat=QSettings.IniFormat): super().__init__(path, fformat) def setValue(self, key, value): super().setValue(key, value) self.valueChanged.emit(key, value) '''class NSettings(QSettings): """ Extend QSettings to emit a signal when a value change. @signals: valueChanged(QString, PyQt_PyObject) """ valueChanged = pyqtSignal('PyQt_PyObject', 'QString', 'PyQt_PyObject') def __init__(self, path, obj=None, fformat=QSettings.IniFormat, prefix=''): super(NSettings, self).__init__(path, fformat) self.__prefix = prefix self.__object = obj def setValue(self, key, value): super(NSettings, self).setValue(key, value) key = "%s_%s" % (self.__prefix, key) self.valueChanged.emit(self.__object, key, value) '''
1,832
Python
.py
46
35.804348
79
0.699155
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,584
ipc.py
ninja-ide_ninja-ide/ninja_ide/core/ipc.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import os from PyQt5.QtNetwork import QLocalSocket file_delimiter = '<-nf>' project_delimiter = '<-np>' def is_running(): local_socket = QLocalSocket() local_socket.connectToServer("ninja_ide") if local_socket.state(): # It's running result = (True, local_socket) else: # It's not running result = (False, local_socket) return result def send_data(socket, filenames, projects_path, linenos): global file_delimiter global project_delimiter file_with_nro = ['%s:%i' % (os.path.abspath(f[0]), f[1] - 1) for f in zip(filenames, linenos)] file_without_nro = ['%s:%i' % (os.path.abspath(f), 0) for f in filenames[len(linenos):]] filenames = file_with_nro + file_without_nro files = file_delimiter.join(filenames) projects = project_delimiter.join(projects_path) data = files + project_delimiter + projects data_sended = False try: result = socket.write(data) socket.flush() socket.close() if result >= 0: data_sended = True except BaseException: data_sended = False return data_sended
1,916
Python
.py
52
31.884615
70
0.679245
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,585
settings.py
ninja-ide_ninja-ide/ninja_ide/core/settings.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os import sys import datetime import enum from PyQt5.QtGui import QFont from PyQt5.QtGui import QImageReader from PyQt5.QtCore import QMimeDatabase from PyQt5.QtCore import QSettings from PyQt5.QtCore import QDir from PyQt5.QtCore import QFileInfo from ninja_ide import resources ############################################################################### # OS DETECTOR ############################################################################### # Use this flags instead of sys.platform spreaded in the source code IS_WINDOWS = IS_MAC_OS = False OS_KEY = "Ctrl" # Font FONT = QFont("Source Code Pro") if sys.platform == "darwin": from PyQt5.QtGui import QKeySequence from PyQt5.QtCore import Qt FONT = QFont("Monaco") OS_KEY = QKeySequence(Qt.CTRL).toString(QKeySequence.NativeText) IS_MAC_OS = True elif sys.platform == "win32": FONT = QFont("Courier") IS_WINDOWS = True FONT.setStyleHint(QFont.TypeWriter) FONT.setPointSize(12) FONT_ANTIALIASING = True def detect_python_path(): if (IS_WINDOWS and PYTHON_EXEC_CONFIGURED_BY_USER) or not IS_WINDOWS: return [] suggested = [] dirs = [] try: drives = [QDir.toNativeSeparators(d.absolutePath()) for d in QDir.drives()] for drive in drives: info = QFileInfo(drive) if info.isReadable(): dirs += [os.path.join(drive, folder) for folder in os.listdir(drive)] for folder in dirs: file_path = os.path.join(folder, "python.exe") if ("python" in folder.lower()) and os.path.exists(file_path): suggested.append(file_path) except BaseException: print("Detection couldnt be executed") finally: return suggested ############################################################################### # IDE ############################################################################### HDPI = False CUSTOM_SCREEN_RESOLUTION = "" # Swap File AUTOSAVE = True AUTOSAVE_DELAY = 1500 # 0: Disable # 1: Enable # 2: Alternative Dir MAX_OPACITY = TOOLBAR_AREA = 1 # UI LAYOUT # 001 : Central Rotate # 010 : Panels Rotate # 100 : Central Orientation NOTIFICATION_ON_SAVE = True LANGUAGE = EXECUTION_OPTIONS = "" SHOW_START_PAGE = CONFIRM_EXIT = True HIDE_TOOLBAR = PYTHON_EXEC_CONFIGURED_BY_USER = False PYTHON_EXEC = sys.executable SESSIONS = {} TOOLBAR_ITEMS = [ "_MainContainer.show_selector", "_MainContainer.add_editor", "ProjectTreeColumn.create_new_project", "_MainContainer.open_file", "ProjectTreeColumn.open_project_folder", "IDE.show_preferences", # "_MainContainer.save_file", # "_MainContainer.split_vertically", # "_MainContainer.split_horizontally", # "IDE.activate_profile", # "IDE.deactivate_profile", # "_MainContainer.editor_cut", # "_MainContainer.editor_copy", # "_MainContainer.editor_paste", # "_ToolsDock.execute_file", # "_ToolsDock.execute_project", # "_ToolsDock.kill_application", ] ACTIONBAR_ITEMS = [ "_ToolsDock.execute_file", "_ToolsDock.execute_project", "_ToolsDock.kill_application" ] TOOLBAR_ITEMS_DEFAULT = [ "_MainContainer.show_selector", "_MainContainer.add_editor", # "ProjectTreeColumn.create_new_project", "_MainContainer.open_file", "ProjectTreeColumn.open_project_folder", "_MainContainer.save_file", "_MainContainer.split_vertically", "_MainContainer.split_horizontally", "IDE.activate_profile", "IDE.deactivate_profile", "_MainContainer.editor_cut", "_MainContainer.editor_copy", "_MainContainer.editor_paste", "_ToolsDock.execute_file", "_ToolsDock.execute_project", "_ToolsDock.kill_application", ] # hold the toolbar actions added by plugins NINJA_SKIN = 'Dark' LAST_OPENED_FILES = [] NOTIFICATION_POSITION = 0 NOTIFICATION_COLOR = "#000" LAST_CLEAN_LOCATOR = None ############################################################################### # EDITOR ############################################################################### EDITOR_SCHEME = "Ninja Dark" # IntelliSense AUTOCOMPLETE_BRACKETS = AUTOCOMPLETE_QUOTES = True # by default Unix (\n) is used USE_TABS = ALLOW_WORD_WRAP = USE_PLATFORM_END_OF_LINE = False REMOVE_TRAILING_SPACES = True SHOW_INDENTATION_GUIDES = SHOW_TABS_AND_SPACES = False ADD_NEW_LINE_AT_EOF = HIDE_MOUSE_CURSOR = SCROLL_WHEEL_ZOMMING = True # Current Line HIGHLIGHT_CURRENT_LINE = True # 0: Full background # 1: Simple HIGHLIGHT_CURRENT_LINE_MODE = 0 INDENT = 4 SHOW_MARGIN_LINE = True MARGIN_LINE = 79 MARGIN_LINE_BACKGROUND = False # The background after the column limit BRACE_MATCHING = True MAX_REMEMBER_EDITORS = 50 CHECK_STYLE = FIND_ERRORS = True # Widgets on side area of editor SHOW_LINE_NUMBERS = True SHOW_TEXT_CHANGES = True SYNTAX = {} EXTENSIONS = {} # 0: Always ask # 1: Reload # 2: Ignore RELOAD_FILE = 0 ############################################################################### # CHECKERS ############################################################################### ############################################################################### # MINIMAP ############################################################################### ############################################################################### # FILE MANAGER ############################################################################### # File types supported by Ninja-IDE FILE_TYPES = [ ("Python files", (".py", ".pyw")), ("QML files", (".qml",)), ("HTML document", (".html", ".htm")), ("JavaScript program", (".js", ".jsm")), ("Ninja project", (".nja",)) ] # Mime types image_mimetypes = [f.data().decode() for f in QImageReader.supportedMimeTypes()][1:] db = QMimeDatabase() for mt in image_mimetypes: mimetype = db.mimeTypeForName(mt) suffixes = [".{}".format(s) for s in mimetype.suffixes()] FILE_TYPES.append((mimetype.comment(), suffixes)) LANGUAGE_MAP = { "py": "python", "pyw": "python", "js": "javascript", "html": "html", "md": "markdown", "yml": "yaml", "qml": "qml", "json": "json" } ############################################################################### # PROJECTS DATA ############################################################################### ############################################################################### # EXPLORER ############################################################################### SHOW_PROJECT_EXPLORER = SHOW_SYMBOLS_LIST = True SHOW_ERRORS_LIST = SHOW_MIGRATION_LIST = SHOW_WEB_INSPECTOR = True ############################################################################### # WORKSPACE ############################################################################### WORKSPACE = "" ############################################################################### # FUNCTIONS ############################################################################### def get_supported_extensions(): return [item for _, sub in FILE_TYPES for item in sub] def get_supported_extensions_filter(): filters = [] for title, extensions in FILE_TYPES: filters.append("%s (*%s)" % (title, " *".join(extensions))) if IS_WINDOWS: all_filter = "All Files (*.*)" else: all_filter = "All Files (*)" filters.append(all_filter) return ";;".join(sorted(filters)) # """ # Set a project type handler for the given project_type # """ # global PROJECT_TYPES # """ # Returns the handler for the given project_type # """ # global PROJECT_TYPES # """ # Returns the availables project types # """ # global PROJECT_TYPES # """ # Add a toolbar action set from some plugin # """ # global TOOLBAR_ITEMS_PLUGINS # """ # Returns the toolbar actions set by plugins # """ # global TOOLBAR_ITEMS_PLUGINS def use_platform_specific_eol(): global USE_PLATFORM_END_OF_LINE return USE_PLATFORM_END_OF_LINE ############################################################################### # Utility functions to update (patch at runtime) pep8mod.py ############################################################################### # """ # Force to reload all checks in pep8mod.py # """ # """ # Patch pycodestyle.py to ignore a given check by code # EXAMPLE: # 'W1919': 'indentation contains tabs' # """ # """ # Patch pycodestylemod.py to remove the ignore of a give check # EXAMPLE: # 'W1919': 'indentation contains tabs' # """ # """ # Patch pycodestylemod.py to update the margin line length with a new value # """ ############################################################################### # LOAD SETTINGS ############################################################################### def should_clean_locator_knowledge(): value = None if LAST_CLEAN_LOCATOR is not None: delta = datetime.date.today() - LAST_CLEAN_LOCATOR if delta.days >= 10: value = datetime.date.today() elif LAST_CLEAN_LOCATOR is None: value = datetime.date.today() return value def clean_locator_db(qsettings): """Clean Locator Knowledge""" last_clean = should_clean_locator_knowledge() if last_clean is not None: file_path = os.path.join(resources.NINJA_KNOWLEDGE_PATH, 'locator.db') if os.path.isfile(file_path): os.remove(file_path) qsettings.setValue("ide/cleanLocator", last_clean) def load_settings(): qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) data_qsettings = QSettings(resources.DATA_SETTINGS_PATH, QSettings.IniFormat) # Globals # global TOOLBAR_AREA # global LANGUAGE # global SHOW_START_PAGE # global CONFIRM_EXIT # global UI_LAYOUT global PYTHON_EXEC global EXECUTION_OPTIONS # global SWAP_FILE # global SWAP_FILE_INTERVAL # global PYTHON_EXEC_CONFIGURED_BY_USER # global SESSIONS global NINJA_SKIN # global SUPPORTED_EXTENSIONS global WORKSPACE global INDENT global USE_PLATFORM_END_OF_LINE # global REMOVE_TRAILING_SPACES # global ADD_NEW_LINE_AT_EOF # global HIDE_MOUSE_CURSOR # global SCROLL_WHEEL_ZOMMING # global SHOW_TABS_AND_SPACES global USE_TABS global ALLOW_WORD_WRAP # global COMPLETE_DECLARATIONS # global UNDERLINE_NOT_BACKGROUND global FONT global FONT_ANTIALIASING global MARGIN_LINE global SHOW_MARGIN_LINE global MARGIN_LINE_BACKGROUND global SHOW_INDENTATION_GUIDES # global IGNORE_PEP8_LIST # global ERRORS_HIGHLIGHT_LINE global FIND_ERRORS global CHECK_STYLE # global CHECK_HIGHLIGHT_LINE # global SHOW_MIGRATION_TIPS # global CODE_COMPLETION # global END_AT_LAST_LINE # global SHOW_PROJECT_EXPLORER # global SHOW_SYMBOLS_LIST global SHOW_WEB_INSPECTOR global SHOW_ERRORS_LIST # global SHOW_MIGRATION_LIST # global BOOKMARKS # global CHECK_FOR_DOCSTRINGS # global BREAKPOINTS # global BRACES global HIDE_TOOLBAR global AUTOCOMPLETE_BRACKETS global AUTOCOMPLETE_QUOTES # global TOOLBAR_ITEMS # global SHOW_MINIMAP # global MINIMAP_MAX_OPACITY # global MINIMAP_MIN_OPACITY # global SIZE_PROPORTION # global SHOW_DOCMAP # global DOCMAP_SLIDER # global EDITOR_SCROLLBAR # global DOCMAP_WIDTH # global DOCMAP_CURRENT_LINE # global DOCMAP_SEARCH_LINES # global NOTIFICATION_POSITION global NOTIFICATION_ON_SAVE # global NOTIFICATION_COLOR global LAST_CLEAN_LOCATOR global SHOW_LINE_NUMBERS global SHOW_TEXT_CHANGES global RELOAD_FILE global CUSTOM_SCREEN_RESOLUTION global HDPI global HIGHLIGHT_CURRENT_LINE global HIGHLIGHT_CURRENT_LINE_MODE global BRACE_MATCHING global EDITOR_SCHEME # General HIDE_TOOLBAR = qsettings.value("window/hide_toolbar", False, type=bool) # TOOLBAR_AREA = qsettings.value('preferences/general/toolbarArea', 1, # type=int) # LANGUAGE = qsettings.value('preferences/interface/language', '', # type='QString') # 'preferences/general/showStartPage', True, type=bool) # CONFIRM_EXIT = qsettings.value('preferences/general/confirmExit', # True, type=bool) PYTHON_EXEC = qsettings.value('execution/pythonExec', sys.executable, type=str) # 'preferences/execution/pythonExecConfigured', False, type=bool) NINJA_SKIN = qsettings.value("ide/interface/skin", "Dark", type=str) RELOAD_FILE = qsettings.value("ide/reloadSetting", 0, type=int) CUSTOM_SCREEN_RESOLUTION = qsettings.value( "ide/interface/customScreenResolution", "", type=str) HDPI = qsettings.value("ide/interface/autoHdpi", False, type=bool) # Fix later # TODO # 'preferences/interface/toolbar', []))] # EXECUTION OPTIONS EXECUTION_OPTIONS = qsettings.value( 'execution/executionOptions', defaultValue='', type=str) # 'preferences/general/supportedExtensions', []))] WORKSPACE = qsettings.value("ide/workspace", "", type=str) # Editor # 'preferences/editor/minimapShow', False, type=bool) # 'preferences/editor/minimapMaxOpacity', 0.8, type=float)) # 'preferences/editor/minimapMinOpacity', 0.1, type=float)) # 'preferences/editor/minimapSizeProportion', 0.17, type=float)) # 'preferences/editor/docmapShow', True, type=bool) # 'preferences/editor/docmapSlider', False, type=bool) # 'preferences/editor/editorScrollBar', True, type=bool) # 'preferences/editor/docmapWidth', 15, type=int)) HIGHLIGHT_CURRENT_LINE = qsettings.value( 'editor/display/highlightCurrentLine', True, type=bool) HIGHLIGHT_CURRENT_LINE_MODE = qsettings.value( "editor/display/current_line_mode", 0, type=int) BRACE_MATCHING = qsettings.value( "editor/display/brace_matching", True, type=bool) # 'preferences/editor/docmapSearchLines', True, type=bool) INDENT = int(qsettings.value( 'editor/behavior/indentation_width', 4, type=int)) USE_PLATFORM_END_OF_LINE = qsettings.value( 'editor/general/platformEndOfLine', False, type=bool) SHOW_MARGIN_LINE = qsettings.value( 'editor/display/margin_line', True, type=bool) MARGIN_LINE = qsettings.value('editor/display/margin_line_position', 79, type=int) MARGIN_LINE_BACKGROUND = qsettings.value( "editor/display/margin_line_background", False, type=bool) # FIXME: SHOW_LINE_NUMBERS = qsettings.value( 'editor/display/show_line_numbers', True, type=bool) SHOW_TEXT_CHANGES = qsettings.value( "editor/display/show_text_changes", True, type=bool) EDITOR_SCHEME = qsettings.value( "editor/general/scheme", "Ninja Dark", type=str) # 'preferences/editor/removeTrailingSpaces', True, type=bool) # "preferences/editor/addNewLineAtEnd", True, type=bool) # 'preferences/editor/show_whitespaces', False, type=bool) USE_TABS = qsettings.value('editor/behavior/use_tabs', False, type=bool) # "preferences/editor/hideMouseCursor", True, type=bool) # "preferences/editor/scrollWheelZomming", True, type=bool) # FIXME: ALLOW_WORD_WRAP = qsettings.value( 'editor/display/allow_word_wrap', False, type=bool) # 'preferences/editor/completeDeclarations', True, type=bool) # 'preferences/editor/errorsUnderlineBackground', True, type=bool) font = qsettings.value('editor/general/default_font', None) if font: FONT = font FONT_ANTIALIASING = qsettings.value("editor/general/font_antialiasing", True, type=bool) SHOW_INDENTATION_GUIDES = qsettings.value( "editor/display/show_indentation_guides", False, type=bool) # 'preferences/editor/defaultIgnorePep8', [], type='QStringList')) # FIXME: FIND_ERRORS = qsettings.value( "editor/display/check_errors", True, type=bool) # 'preferences/editor/showMigrationTips', True, type=bool) # 'preferences/editor/errorsInLine', True, type=bool) CHECK_STYLE = qsettings.value('editor/display/check_style', True, type=bool) AUTOCOMPLETE_BRACKETS = qsettings.value( "editor/intellisense/autocomplete_brackets", True, type=bool) AUTOCOMPLETE_QUOTES = qsettings.value( "editor/intellisense/autocomplete_quotes", True, type=bool) # 'preferences/editor/checkStyleInline', True, type=bool) # 'preferences/editor/codeCompletion', True, type=bool) # 'preferences/editor/endAtLastLine', True, type=bool) # parentheses = qsettings.value('preferences/editor/parentheses', True, # type=bool) # simpleQuotes = qsettings.value('preferences/editor/simpleQuotes', # True, type=bool) # doubleQuotes = qsettings.value('preferences/editor/doubleQuotes', # True, type=bool) # Projects # 'preferences/interface/showProjectExplorer', True, type=bool) # 'preferences/interface/showSymbolsList', True, type=bool) SHOW_WEB_INSPECTOR = qsettings.value( "interface/showWebInspector", False, type=bool) SHOW_ERRORS_LIST = qsettings.value( "interface/showErrorsList", True, type=bool) # 'preferences/interface/showMigrationList', True, type=bool) # Bookmarks and Breakpoints NOTIFICATION_ON_SAVE = qsettings.value( "editor/general/notificate_on_save", True, type=bool) # Checkers # 'preferences/editor/checkForDocstrings', False, type=bool) # 'interface/notification_position', 1, type=int) # 'preferences/general/notification_color', "#222", type='QString') LAST_CLEAN_LOCATOR = qsettings.value("ide/cleanLocator", None) from ninja_ide.extensions import handlers handlers.init_basic_handlers() clean_locator_db(qsettings)
18,988
Python
.py
490
34.230612
79
0.612446
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,586
plugin_util.py
ninja-ide_ninja-ide/ninja_ide/core/plugin_util.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. class ContextMenuScope(object): """ This class is just a domain class for the plugin API it hold the info about the project explorer context menu """ def __init__(self, project=False, folder=False, files=False): self.project = project self.folder = folder self.file = files
1,013
Python
.py
25
37.64
70
0.73198
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,587
plugin_manager.py
ninja-ide_ninja-ide/ninja_ide/core/plugin_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import os import sys import shutil import copy import zipfile import traceback try: from urllib.request import urlopen from urllib.error import URLError except ImportError: from urllib2 import urlopen from urllib2 import URLError from ninja_ide import resources from ninja_ide.tools.logger import NinjaLogger from ninja_ide.tools import json_manager logger = NinjaLogger('ninja_ide.core.plugin_manager') REQUIREMENTS = 'requirements.txt' COMMAND_FOR_PIP_INSTALL = 'pip install -r %s' try: # For Python2 str = unicode # lint:ok except NameError: # We are in Python3 pass class ServiceLocator(object): ''' Hold the services and allows the interaction between NINJA-IDE and plugins ''' def __init__(self, services=None): self.__services = services if services else {} def get_service(self, name): return self.__services.get(name) def get_availables_services(self): return list(self.__services.keys()) ''' NINJA-IDE Plugin my_plugin.plugin { "module": "my_plugin", "class": "MyPluginExample", "authors": "Martin Alderete <malderete@gmail.com>", "version": "0.1", "description": "Este plugin es de prueba" } class MyPluginExample(Plugin): def initialize(self): #Configure the plugin using the NINJA-IDE API!!! self.editor_s = self.service_locator.get_service('editor') self.toolbar_s = self.service_locator.get_service('toolbar') self.toolbar_s.add_action(QAction(...........)) self.appmenu_s = self.service_locator.get_service('appmenu') self.appmenu_s.add_menu(QMenu(......)) #connect events! self.editor_s.editorKeyPressEvent.connect(self.my_plugin_key_pressed) def my_plugin_key_pressed(self, ...): print 'se apreto alguna tecla en el ide...' ''' ############################################################################### # NINJA-IDE Plugin Manager ############################################################################### class PluginManagerException(Exception): pass # Singleton __pluginManagerInstance = None def PluginManager(*args, **kw): global __pluginManagerInstance if __pluginManagerInstance is None: __pluginManagerInstance = __PluginManager(*args, **kw) return __pluginManagerInstance # Extension of the NINJA-IDE plugin PLUGIN_EXTENSION = '.plugin' class __PluginManager(object): ''' Plugin manager allows to load, unload, initialize plugins. ''' def __init__(self, plugins_dir, service_locator): ''' @param plugins_dir: Path to search plugins. @param service_loctor: ServiceLocator object. ''' self._service_locator = service_locator # new! self._plugins_by_dir = {} # add all the plugins paths for path in self.__create_list(plugins_dir): self.add_plugin_dir(path) # end new! self._errors = [] # found plugins self._found_plugins = [] # active plugins # example: {"logger": (LoggerIntance, metadata), # "my_plugin": (MyPluginInstance, metadata)} self._active_plugins = {} def __create_list(self, obj): if isinstance(obj, (list, tuple)): return obj # string then returns a list of one item! return [obj] def add_plugin_dir(self, plugin_dir): ''' Add a new directory to search plugins. @param plugin_dir: absolute path. ''' if plugin_dir not in self._plugins_by_dir: self._plugins_by_dir[plugin_dir] = [] def get_actives_plugins(self): import warnings warnings.warn("Deprecated in behalf of a TYPO free method name") return self.get_active_plugins() def get_active_plugins(self): ''' Returns a list the instances ''' return [plugin[0] for plugin in list(self._active_plugins.values())] def _get_dir_from_plugin_name(self, plugin_name): ''' Returns the dir of the plugin_name ''' for dir_, plug_names in list(self._plugins_by_dir.items()): if plugin_name in plug_names: return dir_ def __getitem__(self, plugin_name): ''' Magic method to get a plugin instance from a given name. @Note: This method has the logic below. Check if the plugin is known, if it is active return it, otherwise, active it and return it. If the plugin name does not exist raise KeyError exception. @param plugin_name: plugin name. @return: Plugin instance or None ''' global PLUGIN_EXTENSION ext = PLUGIN_EXTENSION if not plugin_name.endswith(ext): plugin_name += ext if plugin_name in self._found_plugins: if plugin_name not in self._active_plugins: dir_ = self._get_dir_from_plugin_name(plugin_name) self.load(plugin_name, dir_) return self._active_plugins[plugin_name][0] raise KeyError(plugin_name) def __contains__(self, plugin_name): ''' Magic method to know whether the PluginManager contains a plugin with a given name. @param plugin_name: plugin name. @return: True or False. ''' return plugin_name in self._found_plugins def __iter__(self): ''' Magic method to iterate over all the plugin's names. @return: iterator. ''' return iter(self._found_plugins) def __len__(self): ''' Magic method to know the plugins quantity. @return: length. ''' return len(self._found_plugins) def __bool__(self): ''' Magic method to indicate that any instance must pass the if conditional if x: ''' return True def get_plugin_name(self, file_name): ''' Get the plugin's name from a file name. @param file_name: A file object name. @return: A plugin name from a file. ''' plugin_file_name, file_ext = os.path.splitext(file_name) return plugin_file_name def list_plugins(self, dir_name): ''' Crawl a directory and collect plugins. @return: List with plugin names. ''' global PLUGIN_EXTENSION ext = PLUGIN_EXTENSION try: listdir = os.listdir(dir_name) return [plug for plug in listdir if plug.endswith(ext)] except OSError: return () def is_plugin_active(self, plugin_name): ''' Check if a plugin is or not active @param plugin_name: Plugin name to check. @return: True or False ''' return plugin_name in self._active_plugins def discover(self): ''' Search all files for directory and get the valid plugin's names. ''' for dir_name in self._plugins_by_dir: for file_name in self.list_plugins(dir_name): plugin_name = file_name if plugin_name not in self._found_plugins: self._found_plugins.append(plugin_name) self._plugins_by_dir[dir_name].append(plugin_name) def _load_module(self, module, klassname, metadata, dir_name): old_syspath = copy.copy(sys.path) try: sys.path.insert(1, dir_name) module = __import__(module, globals(), locals(), []) klass = getattr(module, klassname) # Instanciate the plugin plugin_instance = klass(self._service_locator, metadata=metadata) # return the plugin instance return plugin_instance except(ImportError, AttributeError) as reason: raise PluginManagerException('Error loading "%s": %s' % (module, reason)) finally: sys.path = old_syspath return None def load(self, plugin_name, dir_name): global PLUGIN_EXTENSION if plugin_name in self._active_plugins: return for dir_name, plugin_list in list(self._plugins_by_dir.items()): if plugin_name in plugin_list: ext = PLUGIN_EXTENSION plugin_filename = os.path.join(dir_name, plugin_name) plugin_structure = json_manager.read_json(plugin_filename) plugin_structure['name'] = plugin_name.replace(ext, '') module = plugin_structure.get('module', None) klassname = plugin_structure.get('class', None) if module is not None and klassname is not None: try: plugin_instance = self._load_module(module, klassname, plugin_structure, dir_name) # set a get_plugin method to get the reference to other # call a special method *initialize* in the plugin! plugin_instance.metadata = plugin_structure logger.info("Calling initialize (%s)", plugin_name) plugin_instance.initialize() plugin_metadata = (plugin_instance, plugin_structure) self._active_plugins[plugin_name] = plugin_metadata except (PluginManagerException, Exception) as reason: logger.error("Not instanciated (%s): %s", plugin_name, reason) # remove the plugin because has errors self._found_plugins.remove(plugin_name) traceback_msg = traceback.format_exc() plugin_name = plugin_name.replace(ext, '') # add the traceback to errors self._add_error(plugin_name, traceback_msg) else: logger.info("Successfuly initialized (%s)", plugin_name) def load_all(self): for dir, pl in list(self._plugins_by_dir.items()): # Copy the list because may be we REMOVE item while iterate! found_plugins_aux = copy.copy(pl) for plugin_name in found_plugins_aux: self.load(plugin_name, dir) def load_all_external(self, plugin_path): # Copy the list because may be we REMOVE item while iterate! found_plugins_aux = copy.copy(self._found_plugins) for plugin_name in found_plugins_aux: self.load(plugin_name, plugin_path) def unload(self, plugin_name): try: plugin_object = self._active_plugins[plugin_name][0] # call a special method *finish* in the plugin! plugin_object.finish() del self._active_plugins[plugin_name] except Exception as reason: logger.error("Finishing plugin (%s): %s", plugin_name, reason) else: logger.info("Successfuly finished (%s)", plugin_name) def unload_all(self): # Copy the list because may be we REMOVE item while iterate! active_plugins_aux = copy.copy(self._active_plugins) for plugin_name in active_plugins_aux: self.unload(plugin_name) def shutdown(self): self.unload_all() def get_availables_services(self): """ Returns all services availables """ self._service_locator.get_availables_services() def _add_error(self, plugin_name, traceback_msg): self._errors.append((plugin_name, traceback_msg)) @property def errors(self): """ Returns a comma separated values of errors """ return self._errors def _availables_plugins(url): """ Return the availables plugins from an url in NINJA-IDE web page """ try: descriptor = urlopen(url) plugins = json_manager.read_json_from_stream(descriptor) return plugins except URLError: return {} def available_oficial_plugins(): ''' Returns a dict with OFICIAL availables plugins in NINJA-IDE web page ''' return _availables_plugins(resources.PLUGINS_WEB) def available_community_plugins(): ''' Returns a dict with COMMUNITY availables plugins in NINJA-IDE web page ''' return _availables_plugins(resources.PLUGINS_COMMUNITY) def local_plugins(): ''' Returns the local plugins ''' if not os.path.isfile(resources.PLUGINS_DESCRIPTOR): return [] plugins = json_manager.read_json(resources.PLUGINS_DESCRIPTOR) return plugins def __get_all_plugin_descriptors(): ''' Returns all the .plugin files ''' global PLUGIN_EXTENSION return [pf for pf in os.listdir(resources.PLUGINS) if pf.endswith(PLUGIN_EXTENSION)] def download_plugin(file_): ''' Download a plugin specified by file_ ''' global PLUGIN_EXTENSION # get all the .plugin files in local filesystem plugins_installed_before = set(__get_all_plugin_descriptors()) # download the plugin fileName = os.path.join(resources.PLUGINS, os.path.basename(file_)) content = urlopen(file_) f = open(fileName, 'wb') f.write(content.read()) f.close() # create the zip zipFile = zipfile.ZipFile(fileName, 'r') zipFile.extractall(resources.PLUGINS) zipFile.close() # clean up the enviroment os.remove(fileName) # get the name of the last installed plugin plugins_installed_after = set(__get_all_plugin_descriptors()) # using set operations get the difference that is the new plugin new_plugin = (plugins_installed_after - plugins_installed_before).pop() return new_plugin def manual_install(file_): """Copy zip file and install.""" global PLUGIN_EXTENSION # get all the .plugin files in local filesystem plugins_installed_before = set(__get_all_plugin_descriptors()) # copy the plugin fileName = os.path.join(resources.PLUGINS, os.path.basename(file_)) shutil.copyfile(file_, fileName) # extract the zip zipFile = zipfile.ZipFile(fileName, 'r') zipFile.extractall(resources.PLUGINS) zipFile.close() # clean up the enviroment os.remove(fileName) # get the name of the last installed plugin plugins_installed_after = set(__get_all_plugin_descriptors()) # using set operations get the difference that is the new plugin new_plugin = (plugins_installed_after - plugins_installed_before).pop() return new_plugin def has_dependencies(plug): global REQUIREMENTS, COMMAND_FOR_PIP_INSTALL plugin_name = plug[0] structure = [] if os.path.isfile(resources.PLUGINS_DESCRIPTOR): structure = json_manager.read_json(resources.PLUGINS_DESCRIPTOR) PLUGINS = resources.PLUGINS for p in structure: if p['name'] == plugin_name: pd_file = os.path.join(PLUGINS, p['plugin-descriptor']) p_json = json_manager.read_json(pd_file) module = p_json.get('module') # plugin_module/requirements.txt req_file = os.path.join(os.path.join(PLUGINS, module), REQUIREMENTS) if os.path.isfile(req_file): return (True, COMMAND_FOR_PIP_INSTALL % req_file) # the plugin was found but no requirement then break! break return (False, None) def update_local_plugin_descriptor(plugins): ''' updates the local plugin description The description.json file holds the information about the plugins downloaded with NINJA-IDE This is a way to track the versions of the plugins ''' structure = [] if os.path.isfile(resources.PLUGINS_DESCRIPTOR): structure = json_manager.read_json(resources.PLUGINS_DESCRIPTOR) for plug_list in plugins: # create the plugin data plug = {} plug['name'] = plug_list[0] plug['version'] = plug_list[1] plug['description'] = plug_list[2] plug['authors'] = plug_list[3] plug['home'] = plug_list[4] plug['download'] = plug_list[5] plug['plugin-descriptor'] = plug_list[6] # append the plugin data structure.append(plug) json_manager.write_json(structure, resources.PLUGINS_DESCRIPTOR) def uninstall_plugin(plug): """ Uninstall the given plugin """ plugin_name = plug[0] structure = [] if os.path.isfile(resources.PLUGINS_DESCRIPTOR): structure = json_manager.read_json(resources.PLUGINS_DESCRIPTOR) # copy the strcuture we iterate and remove at the same time structure_aux = copy.copy(structure) for plugin in structure_aux: if plugin["name"] == plugin_name: fileName = plugin["plugin-descriptor"] structure.remove(plugin) break # open <plugin>.plugin file and get the module to remove fileName = os.path.join(resources.PLUGINS, fileName) plugin = json_manager.read_json(fileName) module = plugin.get('module') if module: pluginDir = os.path.join(resources.PLUGINS, module) folders = [pluginDir] for root, dirs, files in os.walk(pluginDir): pluginFiles = [os.path.join(root, f) for f in files] # remove all files list(map(os.remove, pluginFiles)) # collect subfolders folders += [os.path.join(root, d) for d in dirs] folders.reverse() for f in folders: if os.path.isdir(f): os.removedirs(f) # remove ths plugin_name.plugin file os.remove(fileName) # write the new info json_manager.write_json(structure, resources.PLUGINS_DESCRIPTOR) ############################################################################### # Module Test ############################################################################### if __name__ == '__main__': folders = resources.PLUGINS services = {} sl = ServiceLocator(services) pm = PluginManager(folders, sl) # There are not plugins yet...lets discover pm.discover() logger.info("listing plugins names...") for p in pm: print(p) logger.info("Activating plugins...") pm.load_all() logger.info("Plugins already actives...") logger.info(pm.get_active_plugins())
19,305
Python
.py
497
30.448692
98
0.614633
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,588
interpreter_service.py
ninja-ide_ninja-ide/ninja_ide/core/interpreter_service.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os import re import subprocess import json from PyQt5.QtCore import QObject from PyQt5.QtCore import QTimer from PyQt5.QtCore import QThread from PyQt5.QtCore import pyqtSignal from ninja_ide.tools.logger import NinjaLogger from ninja_ide.tools import utils from ninja_ide.core import settings logger = NinjaLogger(__name__) if settings.IS_WINDOWS: _PYREGEX = re.compile("/^python(\\d+(.\\d+)?)?\\.exe$/") else: _PYREGEX = re.compile("^python(\\d+(.\\d+)?)?$") # TODO: esto debería ser configurable _VENV_PATHS = [".virtualenvs"] class InterpreterService(QObject): foundInterpreters = pyqtSignal(list) currentInterpreterChanged = pyqtSignal() def __init__(self): QObject.__init__(self) self.__interpreters = {} self.__current_interpreter = None self.__locator = _IntepreterLocator() def refresh(self): self.__interpreters.clear() # Search interpreters in background thread = QThread(self) self.__locator.moveToThread(thread) thread.started.connect(self.__locator.load_suggestions) self.__locator.finished.connect(thread.quit) self.__locator.finished.connect(self._on_finished) thread.finished.connect(thread.deleteLater) QTimer.singleShot(1000, thread.start) def _on_finished(self, list_of_interpreters): for interpreter in list_of_interpreters: self.__interpreters[interpreter.exec_path] = interpreter self.foundInterpreters.emit(self.get_interpreters()) @property def current(self): return self.__current_interpreter def set_interpreter(self, path): if self.__current_interpreter is None: interpreter = Interpreter(path) interpreter.version = self.__get_version(path) self.__current_interpreter = interpreter else: interpreter = self.__interpreters.get(path) if self.__current_interpreter != interpreter: self.__current_interpreter = interpreter self.currentInterpreterChanged.emit() settings.PYTHON_EXEC = path def get_interpreter(self, path): return self.__interpreters.get(path) def get_interpreters(self): return list(self.__interpreters.values()) def __get_version(self, path): return self.__locator.get_info(path)["versionInfo"] def load(self): self.refresh() self.set_interpreter(settings.PYTHON_EXEC) class Interpreter(object): def __init__(self, path): self._path = path self._venv = None self._version = None @property def path(self): return utils.path_with_tilde_homepath(self._path) @property def exec_path(self): return self._path @property def display_name(self): name = "Python {}".format(self.version) if self.venv is not None: name += " ({})".format(self.venv) return name @property def version(self): return self._version @version.setter def version(self, value): self._version = ".".join(map(str, value[:-1])) @property def venv(self): return self._venv @venv.setter def venv(self, value): self._venv = value def __str__(self): return "Python {} - {}".format(self.version, self.path) def __repr__(self): return self.__str__() def __eq__(self, other): return self.display_name == other.display_name def __hash__(self): return hash( ("display_name", self.display_name), ) class _IntepreterLocator(QObject): finished = pyqtSignal(list) def __init__(self): QObject.__init__(self) self._know_paths = [] if not settings.IS_WINDOWS: self._know_paths = [ "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/sbin" ] @staticmethod def get_info(interp_exec): string = ( "import sys\nimport json\ninfo = {}\n" "info['versionInfo'] = sys.version_info[:4]\n" "info['version'] = sys.version\n" "print(json.dumps(info))" ) output = subprocess.check_output([interp_exec, "-c", string]) return json.loads(output.decode()) def load_suggestions(self): # FIXME: unify this interpreters, venvs = [], [] for venv in _VENV_PATHS: venvdir = os.path.join(os.path.expanduser("~"), venv) if not os.path.exists(venvdir): continue subdirs = os.listdir(venvdir) for subdir in subdirs: if os.path.isdir(os.path.join(venvdir, subdir)): venvpath = os.path.join(venvdir, subdir, "bin") files = os.listdir(venvpath) for f in files: if _PYREGEX.match(f): path = os.path.join(venvpath, f) info = self.get_info(path) interpreter = Interpreter(path) interpreter.version = info["versionInfo"] interpreter.venv = subdir venvs.append(interpreter) if self._know_paths: for path in self._know_paths: if not os.path.exists(path): continue files = os.listdir(path) for f in files: if _PYREGEX.match(f): python_path = os.path.join(path, f) info = self.get_info(python_path) interpreter = Interpreter(python_path) interpreter.version = info["versionInfo"] interpreters.append(interpreter) all_interpreters = list(set(interpreters + venvs)) self.finished.emit(all_interpreters)
6,677
Python
.py
172
29.633721
70
0.603867
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,589
plugin.py
ninja-ide_ninja-ide/ninja_ide/core/plugin.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import os import sys from PyQt4.QtCore import QObject from ninja_ide.tools.logger import NinjaLogger class Plugin(QObject): ''' Base class for ALL Plugin All plugins should inherit from this class ''' def __init__(self, locator, metadata=None): QObject.__init__(self) self.locator = locator if metadata is None: self.metadata = {} else: self.metadata = metadata klass = self.__class__ plugin_name = "%s.%s" % (klass.__module__, klass.__name__) self.logger = NinjaLogger('ninja_ide.plugins.%s' % plugin_name) # set the path! try: self_module = self.__module__ path = os.path.abspath(sys.modules[self_module].__file__) self._path = os.path.dirname(path) except BaseException: self._path = '' def initialize(self): """The initialization of the Plugin should be here.""" self.logger.info("Initializing Plugin...") def finish(self): pass def get_preferences_widget(self): pass @property def path(self): return self._path
1,890
Python
.py
53
30.075472
71
0.661555
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,590
__init__.py
ninja-ide_ninja-ide/ninja_ide/core/__init__.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from .core import *
713
Python
.py
17
40.882353
70
0.759712
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,591
cliparser.py
ninja-ide_ninja-ide/ninja_ide/core/cliparser.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. """ This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions; for details see LICENSE.txt. """ import argparse USAGE = "$python ninja-ide.py <option, [option3...option n]>" def _get_parser(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('file', metavar='file', type=str, nargs='*', help='A file/s to edit', default=[]) parser.add_argument('-f', '--files', metavar='file', type=str, nargs='+', help='A file/s to edit', default=[]) parser.add_argument('-l', '--lineno', metavar='lineno', type=int, nargs='+', help='Line number for the files to open', default=[]) parser.add_argument('-p', '--project', metavar='project', type=str, nargs='+', help='A project/s to edit', default=[]) parser.add_argument('--plugin', metavar='plugin', type=str, nargs='+', help='A plugin to load', default=[]) parser.add_argument( '-v', '--verbose', action='count', default=1, help='Level to use for logging (-v -vv -vvvv)' ) parser.add_argument('--logfile', help="A file path to log, special " "words STDOUT or STDERR are accepted", default=None, metavar="logfile") return parser def parse(): filenames = projects_path = linenos = None extra_plugins = log_level = log_file = None try: args = _get_parser().parse_args() filenames = args.file \ if isinstance(args.file, list) \ else [args.file] filenames += args.files \ if hasattr(args, 'files') \ else [] projects_path = args.project \ if isinstance(args.project, list) \ else [args.project] linenos = args.lineno \ if hasattr(args, 'lineno') \ else [args.lineno] extra_plugins = args.plugin \ if isinstance(args.plugin, list) \ else [args.plugin] log_level = 40 - (10 * args.verbose) if args.verbose > 0 else 0 log_file = args.logfile except Exception as reason: print("Args couldn't be parsed.") print(reason) return (filenames, projects_path, extra_plugins, linenos, log_level, log_file)
3,133
Python
.py
74
34.391892
76
0.612004
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,592
core.py
ninja-ide_ninja-ide/ninja_ide/core/core.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import sys import os import signal from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import Qt from PyQt5.QtCore import QCoreApplication from ninja_ide.core import cliparser PR_SET_NAME = 15 PROCNAME = b"ninja-ide" def run_ninja(): """First obtain the execution args and create the resources folder.""" signal.signal(signal.SIGINT, signal.SIG_DFL) # Change the process name only for linux yet is_linux = sys.platform == "darwin" or sys.platform == "win32" if is_linux: try: import ctypes libc = ctypes.cdll.LoadLibrary('libc.so.6') # Set the application name libc.prctl(PR_SET_NAME, b"%s\0" % PROCNAME, 0, 0, 0) except OSError: print("The process couldn't be renamed'") filenames, projects_path, extra_plugins, linenos, log_level, log_file = \ cliparser.parse() # Create the QApplication object before using the # Qt modules to avoid warnings from ninja_ide.core import settings QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, settings.HDPI) app = QApplication(sys.argv) from ninja_ide import resources resources.create_home_dir_structure() # Load Logger from ninja_ide.tools.logger import NinjaLogger NinjaLogger.argparse(log_level, log_file) # Load Settings settings.load_settings() if settings.CUSTOM_SCREEN_RESOLUTION: os.environ["QT_SCALE_FACTOR"] = settings.CUSTOM_SCREEN_RESOLUTION from ninja_ide import ninja_style app.setStyle(ninja_style.NinjaStyle(resources.load_theme())) # Load icon font from ninja_ide.gui.icon_manager import icon # noqa from ninja_ide import gui # Start the UI gui.start_ide(app, filenames, projects_path, extra_plugins, linenos) sys.exit(app.exec_())
2,509
Python
.py
62
36.032258
77
0.725144
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,593
plugin_interfaces.py
ninja-ide_ninja-ide/ninja_ide/core/plugin_interfaces.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. ############################################################################### # ABSTRACT CLASSES (This file contains useful interfaces for plugins) # We know, Python does not need interfaces, but this file is useful as # documentation. Is not mandatory inherit from these interfaces but you SHOULD # implement the methods inside them. ############################################################################### class MethodNotImplemented(Exception): pass def implements(iface): """ A decorator to check if interfaces are correctly implmented #TODO: check if functions parameters are correct """ def implementsIA(cls, *args, **kwargs): """ Find out which methods should be and are not in the implementation of the interface, raise errors if class is not correctly implementing. """ should_implement = set(dir(iface)).difference(set(dir(object))) should_implement = set(should for should in should_implement if not should.startswith("_")) not_implemented = should_implement.difference(set(dir(cls))) if len(not_implemented) > 0: raise MethodNotImplemented("Methods %s not implemented" % ", ".join(not_implemented)) if cls.__name__ not in globals(): # if decorated a class is not in globals globals()[cls.__name__] = cls return cls return implementsIA class IProjectTypeHandler(object): """ Interface to create a Project type handler """ # mandatory def get_pages(self): """ Returns a collection of QWizardPage """ pass # mandatory def on_wizard_finish(self, wizard): """ Called when the user finish the wizard @wizard: QWizard instance """ pass def get_context_menus(self): """" Returns a iterable of QMenu """ pass class ISymbolsHandler: """ Interface to create a symbol handler EXAMPLE: { 'attributes': {name: line, name: line}, 'functions': {name: line, name: line}, 'classes': { name: (line, { 'attributes': {name: line}, 'function': {name: line}} ) } } """ # mandatory def obtain_symbols(self, source): """ Returns the dict needed by the tree @source: Source code in plain text """ pass class IPluginPreferences: """ Interface for plugin preferences widget """ # mandatory def save(self): """ Save the plugin data as NINJA-IDE settings """ pass
3,456
Python
.py
103
26.631068
79
0.59766
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,594
file_manager.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/file_manager.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import sys import os import re import threading import shutil from PyQt5 import QtCore from ninja_ide.core import settings if sys.version_info.major == 3: python3 = True else: python3 = False # Lock to protect the file's writing operation file_store_content_lock = threading.Lock() class NinjaIOException(Exception): """ IO operation's exception """ pass class NinjaNoFileNameException(Exception): """ Tried to write a file but I lack a file name """ pass class NinjaFileExistsException(Exception): """ Try to override existing file without confirmation exception. """ def __init__(self, filename=''): Exception.__init__(self, 'The file already exists.') self.filename = filename def create_init_file(folderName): """Create a __init__.py file in the folder received.""" if not os.path.isdir(folderName): raise NinjaIOException("The destination folder does not exist") name = os.path.join(folderName, '__init__.py') if file_exists(name): raise NinjaFileExistsException(name) f = open(name, 'w') f.flush() f.close() def create_init_file_complete(folderName): """Create a __init__.py file in the folder received. This __init__.py will contain the information of the files inside this folder.""" if not os.path.isdir(folderName): raise NinjaIOException("The destination folder does not exist") patDef = re.compile('^def .+') patClass = re.compile('^class .+') patExt = re.compile('.+\\.py') files = os.listdir(folderName) files = sorted(filter(patExt.match, files)) imports_ = [] for f in files: read = open(os.path.join(folderName, f), 'r') imp = [re.split('\\s|\\(', line)[1] for line in read.readlines() if patDef.match(line) or patClass.match(line)] imports_ += ['from ' + f[:-3] + ' import ' + i for i in imp] name = os.path.join(folderName, '__init__.py') fi = open(name, 'w') for import_ in imports_: fi.write(import_ + '\n') fi.flush() fi.close() def create_folder(folderName, add_init_file=True): """Create a new Folder inside the one received as a param.""" if os.path.exists(folderName): raise NinjaIOException("The folder already exist") os.makedirs(folderName) if add_init_file: create_init_file(folderName) def create_tree_folders(folderName): """Create a group of folders, one inside the other.""" if os.path.exists(folderName): raise NinjaIOException("The folder already exist") os.makedirs(folderName) def folder_exists(folderName): """Check if a folder already exists.""" return os.path.isdir(folderName) def file_exists(path, fileName=''): """Check if a file already exists.""" if fileName != '': path = os.path.join(path, fileName) return os.path.isfile(path) def _search_coding_line(txt): """Search a pattern like this: # -*- coding: utf-8 -*-.""" coding_pattern = "coding[:=]\\s*([-\\w.]+)" pat_coding = re.search(coding_pattern, txt) if pat_coding and pat_coding.groups()[0] != 'None': return pat_coding.groups()[0] return None def get_file_encoding(content): """Try to get the encoding of the file using the PEP 0263 rules search the first or the second line of the file Returns the encoding or the default UTF-8 """ encoding = None try: lines_to_check = content.split("\n", 2) for index in range(2): if len(lines_to_check) > index: line_encoding = _search_coding_line(lines_to_check[index]) if line_encoding: encoding = line_encoding break except UnicodeDecodeError as error: # add logger print(error) # if not encoding is set then use UTF-8 as default if encoding is None: encoding = "UTF-8" return encoding def read_file_content(fileName): """Read a file content, this function is used to load Editor content.""" try: with open(fileName, 'rU') as f: content = f.read() except IOError as reason: raise NinjaIOException(reason) except Exception: raise return content def get_basename(fileName): """Get the name of a file or folder specified in a path.""" if fileName.endswith(os.path.sep): fileName = fileName[:-1] return os.path.basename(fileName) def get_folder(fileName): """Get the name of the folder containing the file or folder received.""" return os.path.dirname(fileName) def store_file_content(fileName, content, addExtension=True, newFile=False): """Save content on disk with the given file name.""" if fileName == '': raise Exception() ext = (os.path.splitext(fileName)[-1])[1:] if ext == '' and addExtension: fileName += '.py' if newFile and file_exists(fileName): raise NinjaFileExistsException(fileName) try: flags = QtCore.QIODevice.WriteOnly | QtCore.QIODevice.Truncate f = QtCore.QFile(fileName) if settings.use_platform_specific_eol(): flags |= QtCore.QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QtCore.QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() except Exception: raise return os.path.abspath(fileName) def open_project(path): """Return a dict structure containing the info inside a folder.""" return open_project_with_extensions(settings.SUPPORTED_EXTENSIONS) def open_project_with_extensions(path, extensions): """Return a dict structure containing the info inside a folder. This function uses the extensions specified by each project.""" if not os.path.exists(path): raise NinjaIOException("The folder does not exist") valid_extensions = [ext.lower() for ext in extensions if not ext.startswith('-')] d = {} for root, dirs, files in os.walk(path, followlinks=True): for f in files: ext = os.path.splitext(f.lower())[-1] if ext in valid_extensions or '.*' in valid_extensions: d[root] = [f, dirs] elif ext == '' and '*' in valid_extensions: d[root] = [f, dirs] return d def delete_file(path, fileName=None): """Delete the proper file. If fileName is None, path and fileName are joined to create the complete path, otherwise path is used to delete the file.""" if fileName: path = os.path.join(path, fileName) if os.path.isfile(path): os.remove(path) def delete_folder(path, fileName=None): """Delete the proper folder.""" if fileName: path = os.path.join(path, fileName) if os.path.isdir(path): shutil.rmtree(path) def rename_file(old, new): """Rename a file, changing its name from 'old' to 'new'.""" if os.path.isfile(old): if file_exists(new): raise NinjaFileExistsException(new) os.rename(old, new) return new return '' def get_file_extension(fileName): """Get the file extension in the form of: 'py'""" return os.path.splitext(fileName.lower())[-1][1:] def get_file_name(fileName): """Get the file name, without the extension.""" return os.path.splitext(fileName)[0] def get_module_name(fileName): """Get the name of the file without the extension.""" module = os.path.basename(fileName) return (os.path.splitext(module)[0]) def convert_to_relative(basePath, fileName): """Convert a absolut path to relative based on its start with basePath.""" if fileName.startswith(basePath): fileName = fileName.replace(basePath, '') if fileName.startswith(os.path.sep): fileName = fileName[1:] return fileName def create_path(*args): """Join the paths provided in order to create an absolut path.""" return os.path.join(*args) def belongs_to_folder(path, fileName): """Determine if fileName is located under path structure.""" if not path.endswith(os.path.sep): path += os.path.sep return fileName.startswith(path) def get_last_modification(fileName): """Get the last time the file was modified.""" return QtCore.QFileInfo(fileName).lastModified() def has_write_permission(fileName): """Check if the file has writing permissions.""" return os.access(fileName, os.W_OK) def check_for_external_modification(fileName, old_mtime): """Check if the file was modified outside ninja.""" new_modification_time = get_last_modification(fileName) # check the file mtime attribute calling os.stat() if new_modification_time > old_mtime: return True return False def get_files_from_folder(folder, ext): """Get the files in folder with the specified extension.""" try: filesExt = os.listdir(folder) except Exception: filesExt = [] filesExt = [f for f in filesExt if f.endswith(ext)] return filesExt def is_supported_extension(filename, extensions=None): if extensions is None: extensions = settings.SUPPORTED_EXTENSIONS if os.path.splitext(filename.lower())[-1] in extensions: return True return False def show_containing_folder(path): """Cross-platform show containing folder of path""" file_info = QtCore.QFileInfo(path) program = "" param = [] if settings.IS_WINDOWS: program = "explorer.exe" param.append("/select,") param.append(QtCore.QDir.toNativeSeparators( file_info.canonicalFilePath())) elif settings.IS_MAC_OS: program = "open" param.append("-R") param.append(file_info.absolutePath()) else: program = "xdg-open" param.append(file_info.absolutePath()) QtCore.QProcess.startDetached(program, param)
10,876
Python
.py
284
32.274648
78
0.666793
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,595
nfilesystem.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/nfilesystem.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os from PyQt5.QtWidgets import QFileSystemModel from PyQt5.QtCore import QObject from PyQt5.QtCore import QDir from PyQt5.QtCore import pyqtSignal from ninja_ide.core.file_handling.nfile import NFile from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.core.file_handling.nfilesystem') class NVirtualFileSystem(QObject): # Signals projectOpened = pyqtSignal('QString') projectClosed = pyqtSignal('QString') def __init__(self, *args, **kwargs): self.__tree = {} self.__watchables = {} self.__projects = {} # bc maps are cheap but my patience is not self.__reverse_project_map = {} super(NVirtualFileSystem, self).__init__(*args, **kwargs) def list_projects(self): return list(self.__projects.keys()) def open_project(self, project): project_path = project.path qfsm = None # Should end up having a QFileSystemModel if project_path not in self.__projects: qfsm = QFileSystemModel() project.model = qfsm qfsm.setRootPath(project_path) qfsm.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDotAndDotDot) # If set to true items that dont match are displayed disabled qfsm.setNameFilterDisables(False) pext = ["*{0}".format(x) for x in project.extensions] logger.debug(pext) qfsm.setNameFilters(pext) self.__projects[project_path] = project self.__check_files_for(project_path) self.projectOpened.emit(project_path) else: qfsm = self.__projects[project_path] return qfsm def refresh_name_filters(self, project): qfsm = project.model if qfsm: pext = ["*{0}".format(x) for x in project.extensions] logger.debug(pext) qfsm.setNameFilters(pext) def close_project(self, project_path): if project_path in self.__projects: project_root = self.__projects[project_path] nfiles = list(self.__tree.values()) for nfile in nfiles: if self.__reverse_project_map[nfile] == project_root: del self.__tree[nfile.file_path] nfile.close() # This might not be needed just being extra cautious del self.__projects[project_path].model del self.__projects[project_path] self.projectClosed.emit(project_path) def __check_files_for(self, project_path): project = self.__projects[project_path] for each_file_path in list(self.__tree.keys()): nfile = self.__tree[each_file_path] if nfile.file_path.startswith(project_path): self.__reverse_project_map[nfile] = project def __closed_file(self, nfile_path): if nfile_path in self.__tree: del self.__tree[nfile_path] if nfile_path in self.__reverse_project_map: del self.__reverse_project_map[nfile_path] if nfile_path in self.__watchables: del self.__watchables[nfile_path] def __add_file(self, nfile): nfile.fileClosing['QString', bool].connect(self.__closed_file) existing_paths = sorted(list(self.__projects.keys()), reverse=True) self.__tree[nfile.file_path] = nfile for each_path in existing_paths: if nfile.file_path.startswith(each_path): project = self.__projects[each_path] self.__reverse_project_map[nfile] = project return project def get_file(self, nfile_path=None): if nfile_path is None: return NFile(nfile_path) if os.path.isdir(nfile_path): return None if nfile_path not in self.__tree: nfile = NFile(nfile_path) self.__add_file(nfile) elif nfile_path in self.__tree: nfile = self.__tree[nfile_path] else: nfile = NFile() nfile.saveAsNewFile['PyQt_PyObject', 'QString', 'QString'].connect(self.__file_copied) return nfile def __file_copied(self, nfile, old_path, new_path): self.__add_file(nfile) def get_projects(self): return self.__projects def get_project_for_file(self, filename): nfile = self.get_file(filename) project = self.__reverse_project_map.get(nfile, None) return project def get_files(self): return self.__tree
5,266
Python
.py
122
34.065574
75
0.627244
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,596
nfile.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/nfile.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os import shutil from PyQt5.QtCore import QObject from PyQt5.QtCore import QFile from PyQt5.QtCore import QFileSystemWatcher from PyQt5.QtCore import QIODevice from PyQt5.QtCore import QTextStream from PyQt5.QtCore import pyqtSignal from ninja_ide import translations # FIXME: Obtain these form a getter from ninja_ide.core import settings from ninja_ide.tools.utils import SignalFlowControl from .file_manager import NinjaIOException, NinjaNoFileNameException, \ get_file_encoding, get_basename, get_file_extension from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.core.file_handling.nfile') DEBUG = logger.debug """ How to continue: We need to have a filesystem representation object, said object, registers himself into the IDE on its __init__.py, thus avoiding all kinds of circular imports, this way all objects should start registering themselves and fail individually if they cant. So, to this object, whoever creates new NFiles should ask for a it, this way it keeps record of the files and can do closing when receives terminate from the ide, and decides to call a changed callback from each file when the watched, that should depend on it notifies a change. """ class NFile(QObject): """ SIGNALS: @askForSaveFileClosing(QString) @fileClosing(QString) @fileChanged() @willDelete(PyQt_PyObject, PyQt_PyObject) @willOverWrite(PyQt_PyObject, QString, QString) @willMove(Qt_PyQtObject, QString, QString) @willSave(QString, QString) @savedAsNewFile(PyQt_PyObject, QString, QString) @gotAPath(PyQt_PyObject) @willAttachToExistingFile(PyQt_PyObject, QString) """ fileChanged = pyqtSignal() fileRemoved = pyqtSignal() fileReaded = pyqtSignal() willAttachToExistingFile = pyqtSignal('PyQt_PyObject', 'QString') gotAPath = pyqtSignal('PyQt_PyObject') willSave = pyqtSignal('QString', 'QString') willMove = pyqtSignal('PyQt_PyObject', 'QString', 'QString') willOverWrite = pyqtSignal('PyQt_PyObject', 'QString', 'QString') willCopyTo = pyqtSignal('PyQt_PyObject', 'QString', 'QString') willDelete = pyqtSignal('PyQt_PyObject', 'PyQt_PyObject') fileClosing = pyqtSignal('QString', bool) def __init__(self, path=None): """ """ self._file_path = path self.__created = False self.__watcher = None self.__mtime = None super(NFile, self).__init__() if not self._exists(): self.__created = True @property def file_name(self): """"Returns filename of nfile""" file_name = None if self._file_path is None: file_name = translations.TR_NEW_DOCUMENT else: file_name = get_basename(self._file_path) return file_name @property def display_name(self): """Returns a pretty name to be displayed by tabs""" display_name = self.file_name if self._file_path is not None and not self.has_write_permission(): display_name += translations.TR_READ_ONLY return display_name @property def is_new_file(self): return self.__created def file_ext(self): """"Returns extension of nfile""" if self._file_path is None: return '' return get_file_extension(self._file_path) @property def file_path(self): """"Returns file path of nfile""" return self._file_path def start_watching(self): """Create a file system watcher and connect its fileChanged SIGNAL to our _file_changed SLOT""" if self.__watcher is None: self.__watcher = QFileSystemWatcher(self) self.__watcher.fileChanged['const QString&'].connect( self._file_changed) if self._file_path is not None: self.__mtime = os.path.getmtime(self._file_path) self.__watcher.addPath(self._file_path) def _file_changed(self, path): if self._exists(): current_mtime = os.path.getmtime(self._file_path) if current_mtime != self.__mtime: self.__mtime = current_mtime self.fileChanged.emit() # FIXME: for swap file def has_write_permission(self): if not self._exists(): return True return os.access(self._file_path, os.W_OK) def _exists(self): """ Check if we have been created with a path and if such path exists In case there is no path, we are most likely a new file. """ file_exists = False if self._file_path and os.path.exists(self._file_path): file_exists = True return file_exists def attach_to_path(self, new_path): if os.path.exists(new_path): signal_handler = SignalFlowControl() self.willAttachToExistingFile.emit(signal_handler, new_path) if signal_handler.stopped(): return self._file_path = new_path self.gotAPath.emit(self) return self._file_path def create(self): if self.__created: self.save("") self.__created = False def save(self, content, path=None): """ Write a temporary file with .tnj extension and copy it over the original one. .nsf = Ninja Swap File # FIXME: Where to locate addExtension, does not fit here """ new_path = False if path: self.attach_to_path(path) new_path = True save_path = self._file_path if not save_path: raise NinjaNoFileNameException("I am asked to write a " "file but no one told me where") swap_save_path = "%s.nsp" % save_path # If we have a file system watcher, remove the file path # from its watch list until we are done making changes. if self.__watcher is not None: self.__watcher.removePath(save_path) flags = QIODevice.WriteOnly | QIODevice.Truncate f = QFile(swap_save_path) if settings.use_platform_specific_eol(): flags |= QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() # SIGNAL: Will save (temp, definitive) to warn folder to do something self.willSave.emit(swap_save_path, save_path) self.__mtime = os.path.getmtime(swap_save_path) shutil.move(swap_save_path, save_path) self.reset_state() # If we have a file system watcher, add the saved path back # to its watch list, otherwise create a watcher and start # watching if self.__watcher is not None: if new_path: self.__watcher.addPath(self._file_path) else: self.__watcher.addPath(save_path) else: self.start_watching() return self def reset_state(self): """ #FIXE: to have a ref to changed I need to have the doc here """ self.__created = False def read(self, path=None): """ Read the file or fail """ open_path = path and path or self._file_path self._file_path = open_path if not self._file_path: raise NinjaNoFileNameException("I am asked to read a file " "but no one told me from where") try: with open(open_path, 'r') as f: content = f.read() except (IOError, UnicodeDecodeError) as reason: raise NinjaIOException(reason) self.fileReaded.emit() return content def move(self, new_path): """ Phisically move the file """ if self._exists(): signal_handler = SignalFlowControl() # SIGNALL: WILL MOVE TO, to warn folder to exist self.willMove.emit(signal_handler, self._file_path, new_path) if signal_handler.stopped(): return if os.path.exists(new_path): signal_handler = SignalFlowControl() self.willOverWrite.emit(signal_handler, self._file_path, new_path) if signal_handler.stopped(): return if self.__watcher is not None: self.__watcher.removePath(self._file_path) shutil.move(self._file_path, new_path) if self.__watcher: self.__watcher.addPath(new_path) self._file_path = new_path def copy(self, new_path): """ Copy the file to a new path """ if self._exists(): signal_handler = SignalFlowControl() # SIGNALL: WILL COPY TO, to warn folder to exist self.willCopyTo.emit(signal_handler, self._file_path, new_path) if signal_handler.stopped(): return if os.path.exists(new_path): signal_handler = SignalFlowControl() self.willOverWrite.emit(signal_handler, self._file_path, new_path) if signal_handler.stopped(): return shutil.copy(self._file_path, new_path) def delete(self, force=False): """ This deletes the object and closes the file. """ # if created but exists this file migth to someone else self.close() if ((not self.__created) or force) and self._exists(): DEBUG("Deleting our own NFile %s" % self._file_path) signal_handler = SignalFlowControl() self.willDelete.emit(signal_handler, self) if not signal_handler.stopped(): if self.__watcher is not None: self.__watcher.removePath(self._file_path) os.remove(self._file_path) def close(self, force_close=False): """ Lets let people know we are going down so they can act upon As you can see close does nothing but let everyone know that we are not saved yet """ DEBUG("About to close NFile") self.fileClosing.emit(self._file_path, force_close) def remove_watcher(self): if self.__watcher is not None: self.__watcher.removePath(self._file_path)
11,611
Python
.py
291
30.219931
78
0.606611
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,597
nswapfile.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/nswapfile.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. import os import hashlib from PyQt5.QtCore import QObject from PyQt5.QtCore import QFile from PyQt5.QtCore import QTextStream from PyQt5.QtCore import QIODevice from PyQt5.QtCore import QTimer from PyQt5.QtCore import pyqtSlot from ninja_ide.core import settings from ninja_ide.gui.ide import IDE from ninja_ide import resources from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger(__name__) # TODO: handle untitled files class NSwapFile(QObject): """ This class implements the hot-exit and autosave feature. Ninja will remember unsaved changes to files when you exit by default. Hot exit is triggered when the IDE is closed. If the auto-save feature is enabled, Ninja will create backup files periodically. """ def __init__(self, neditable): QObject.__init__(self) self._neditable = neditable self.__dirty = False self.__filename = None self.__timer = QTimer(self) self.__timer.setSingleShot(True) self.__timer.timeout.connect(self._autosave) ninjaide = IDE.get_service("ide") # Connections ninjaide.goingDown.connect(self._on_ide_going_down) self._neditable.fileLoaded.connect(self._on_file_loaded) self._neditable.fileSaved.connect(self._on_file_saved) self._neditable.fileClosing.connect(self._on_file_closing) @pyqtSlot() def _on_file_closing(self): if not self._neditable.new_document: self.__remove() self.deleteLater() @pyqtSlot() def _autosave(self): if self._neditable.editor.is_modified: flags = QIODevice.WriteOnly f = QFile(self.filename()) if not f.open(flags): raise IOError(f.errorString()) content = self._neditable.editor.text stream = QTextStream(f) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() def filename(self): if self.__filename is None: self.__filename = self.__unique_filename() return self.__filename def __unique_filename(self): fname = self._neditable.file_path.encode() unique_filename = hashlib.md5(fname).hexdigest() return os.path.join(resources.BACKUP_FILES, unique_filename) def exists(self): exists = False if os.path.exists(self.filename()): exists = True return exists @pyqtSlot() def _on_ide_going_down(self): if not self._neditable.new_document: self._autosave() @pyqtSlot() def _on_file_saved(self): self.__remove() def __remove(self): if self.exists(): logger.debug("Removing backup file...") os.remove(self.filename()) self.__dirty = False @property def dirty(self): return self.__dirty @pyqtSlot() def _on_file_loaded(self): if self._neditable.new_document: return if os.path.exists(self.filename()): logger.debug("Reloaded...") self.__dirty = True with open(self.filename()) as fp: content = fp.read() self._neditable.editor.text = content self._neditable.document.setModified(True) self._neditable.editor.textChanged.connect(self._on_text_changed) @pyqtSlot() def _on_text_changed(self): if not self._neditable.editor.is_modified or not settings.AUTOSAVE: return if self.__timer.isActive(): self.__timer.stop() self.__timer.start(settings.AUTOSAVE_DELAY)
4,382
Python
.py
117
30.282051
75
0.655343
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,598
linux.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/filesystem_notifications/linux.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from ninja_ide.core.file_handling.filesystem_notifications import base_watcher import os from PyQt4.QtCore import QThread from pyinotify import ProcessEvent, IN_CREATE, IN_DELETE, IN_DELETE_SELF, \ IN_MODIFY, WatchManager, Notifier, ExcludeFilter from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.core.file_handling.filesystem_notifications.linux') DEBUG = logger.debug ADDED = base_watcher.ADDED DELETED = base_watcher.DELETED REMOVE = base_watcher.REMOVE RENAME = base_watcher.RENAME MODIFIED = base_watcher.MODIFIED # FIXME: For some reaseon the code below raises an import error with name ADDED # DELETED, REMOVE, RENAME, MODIFIED mask = IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY class NinjaProcessEvent(ProcessEvent): def __init__(self, process_callback): self._process_callback = process_callback ProcessEvent.__init__(self) def process_IN_CREATE(self, event): self._process_callback((ADDED, event.pathname)) def process_IN_DELETE(self, event): self._process_callback((DELETED, event.pathname)) def process_IN_DELETE_SELF(self, event): self._process_callback((DELETED, event.pathname)) def process_IN_MODIFY(self, event): self._process_callback((MODIFIED, event.pathname)) def process_IN_MOVED_TO(self, event): self._process_callback((REMOVE, event.pathname)) def process_IN_MOVED_FROM(self, event): self._process_callback((REMOVE, event.pathname)) def process_IN_MOVE_SELF(self, event): self._process_callback((RENAME, event.pathname)) class QNotifier(QThread): def __init__(self, wm, processor): self.event_queue = list() self._processor = processor self.notifier = Notifier(wm, NinjaProcessEvent(self.event_queue.append)) self.notifier.coalesce_events(True) self.keep_running = True QThread.__init__(self) def run(self): while self.keep_running: try: self.notifier.process_events() except OSError: pass # OSError: [Errno 2] No such file or directory happens e_dict = {} while len(self.event_queue): e_type, e_path = self.event_queue.pop(0) e_dict.setdefault(e_path, []).append(e_type) keys = list(e_dict.keys()) while len(keys): key = keys.pop(0) event = e_dict.pop(key) if (ADDED in event) and (DELETED in event): event = [e for e in event if e not in (ADDED, DELETED)] for each_event in event: self._processor(each_event, key) if self.notifier.check_events(): self.notifier.read_events() self.notifier.stop() class NinjaFileSystemWatcher(base_watcher.BaseWatcher): def __init__(self): self.watching_paths = {} super(NinjaFileSystemWatcher, self).__init__() self._ignore_hidden = ('.git', '.hg', '.svn', '.bzr') def add_watch(self, path): if path not in self.watching_paths: try: wm = WatchManager() notifier = QNotifier(wm, self._emit_signal_on_change) notifier.start() exclude = ExcludeFilter([os.path.join(path, folder) for folder in self._ignore_hidden]) wm.add_watch(path, mask, rec=True, auto_add=True, exclude_filter=exclude) self.watching_paths[path] = notifier except (OSError, IOError): pass # Shit happens, most likely temp file def remove_watch(self, path): if path in self.watching_paths: notifier = self.watching_paths.pop(path) notifier.keep_running = False notifier.quit() def shutdown_notification(self): base_watcher.BaseWatcher.shutdown_notification(self) for each_path in self.watching_paths: notifier = self.watching_paths[each_path] notifier.keep_running = False notifier.quit()
4,998
Python
.py
111
36.153153
83
0.636214
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)
11,599
windows.py
ninja-ide_ninja-ide/ninja_ide/core/file_handling/filesystem_notifications/windows.py
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from ninja_ide.core.file_handling.filesystem_notifications import base_watcher from threading import Thread import win32con import win32file import win32event import pywintypes import os from ninja_ide.core.file_handling import file_manager from ninja_ide.tools.logger import NinjaLogger logger = NinjaLogger('ninja_ide.core.file_handling.filesystem_notifications.windows') DEBUG = logger.debug ADDED = base_watcher.ADDED DELETED = base_watcher.DELETED REMOVE = base_watcher.REMOVE RENAME = base_watcher.RENAME MODIFIED = base_watcher.MODIFIED ACTIONS = { 1: ADDED, 2: DELETED, 3: MODIFIED, 4: RENAME, 5: RENAME } # Thanks to Claudio Grondi for the correct set of numbers FILE_LIST_DIRECTORY = 0x0001 watchmask = win32con.FILE_NOTIFY_CHANGE_FILE_NAME | \ win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | \ win32con.FILE_NOTIFY_CHANGE_DIR_NAME def listdir(path): fdict = file_manager.open_project(path) for each_folder in fdict: files, folders = fdict[each_folder] yield each_folder for each_file in files: yield os.path.join(each_folder, each_file) # Credit on this workaround for the shortsightness of windows developers goes # to Malthe Borch http://pypi.python.org/pypi/MacFSEvents class FileEventCallback(object): def __init__(self, callback, paths): self.snapshots = {} for path in paths: self.snapshot(path) self.callback = callback self._path_last_time = {} self.cookie = 0 def pulentastack(self, path): return os.stat(path) def __call__(self, paths): events = [] deleted = {} for path in sorted(paths): path = path.rstrip('/') snapshot = self.snapshots[path] current = {} try: for name in listdir(path): try: current[name] = self.pulentastack(os.path.join(path, name)) except OSError: pass except OSError: # recursive delete causes problems with path being non-existent pass observed = set(current) for name, snap_stat in list(snapshot.items()): filename = os.path.join(path, name) if name in observed: stat = current[name] if stat.st_mtime > snap_stat.st_mtime: events.append((MODIFIED, filename)) observed.discard(name) else: event = (DELETED, filename) deleted[snap_stat.st_ino] = event events.append(event) for name in observed: if name != path: stat = current[name] filename = os.path.join(path, name) event = deleted.get(stat.st_ino) if event is not None: event = (REMOVE, filename) else: event = (ADDED, filename) if os.path.isdir(filename): self.snapshot(filename) events.append(event) snapshot.clear() snapshot.update(current) for event in events: self.callback(*event) def snapshot(self, path): path = os.path.realpath(path) refs = self.snapshots refs[path] = {} for root, dirs, files in os.walk(path): entry = refs[root] for filename in files: try: entry[filename] = self.pulentastack(os.path.join(root, filename)) except OSError: continue for directory in dirs: refs[os.path.join(root, directory)] = {} if os.path.isdir(path): refs[os.path.join(root, path)] = {} for name in listdir(os.path.join(root, path)): try: refs[path][name] = self.pulentastack(os.path.join(path, name)) except OSError: pass class ThreadedFSWatcher(Thread): def __init__(self, path, callback): self._watch_path = path self._callback = callback # FileEventCallback(callback, (path, )) self._windows_sucks_flag = True self._wait_stop = win32event.CreateEvent(None, 0, 0, None) self._overlapped = pywintypes.OVERLAPPED() self._overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) super(ThreadedFSWatcher, self).__init__() def stop(self): self._windows_sucks_flag = False win32event.SetEvent(self._wait_stop) def run(self): hDir = win32file.CreateFileW( self._watch_path, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS | win32con.FILE_FLAG_OVERLAPPED, None ) while self._windows_sucks_flag: buf = win32file.AllocateReadBuffer(1024) win32file.ReadDirectoryChangesW( hDir, buf, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, self._overlapped ) result_stack = {} rc = win32event.WaitForMultipleObjects((self._wait_stop, self._overlapped.hEvent), 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: # Stop event break data = win32file.GetOverlappedResult(hDir, self._overlapped, True) # lets read the data and store it in the results results = win32file.FILE_NOTIFY_INFORMATION(buf, data) for action, afile in results: if action in ACTIONS: full_filename = os.path.join(self._watch_path, afile) result_stack.setdefault(full_filename, []).append(ACTIONS.get(action)) keys = list(result_stack.keys()) while len(keys): key = keys.pop(0) event = result_stack.pop(key) if (ADDED in event) and (DELETED in event): event = [e for e in event if e not in (ADDED, DELETED)] noticed = [] for each_event in event: if each_event not in noticed: self._callback(each_event, full_filename) noticed.append(each_event) class NinjaFileSystemWatcher(base_watcher.BaseWatcher): def __init__(self): super(NinjaFileSystemWatcher, self).__init__() # do stuff self.watching_paths = {} def add_watch(self, path): if path not in self.watching_paths: watch = ThreadedFSWatcher(path, self._emit_signal_on_change) watch.start() self.watching_paths[path] = watch # Add real watcher using platform specific things def remove_watch(self, path): if path in self.watching_paths: self.watching_paths[path].stop() self.watching_paths[path].join() del(self.watching_paths[path]) # Remove real watcher using platform specific things def shutdown_notification(self): base_watcher.BaseWatcher.shutdown_notification(self) for each_path in self.watching_paths: each_path = self.watching_paths[each_path] each_path.stop() each_path.join()
8,876
Python
.py
215
28.902326
85
0.566044
ninja-ide/ninja-ide
927
248
195
GPL-3.0
9/5/2024, 5:11:18 PM (Europe/Amsterdam)