Exemple #1
0
class TutorialView(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self._presenter = TutorialPresenter(self)
        self._widget = QQuickWidget(self)
        self.testComponent = TestComponent(self._widget.engine(), self)
        self._widget.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self._widget.rootContext().setContextProperty('tutorialView', self)
        self._widget.rootContext().setContextProperty('testComponent',
                                                      self.testComponent)
        self._widget.setSource(
            QUrl('modules/tutorial/tutorialForm/TutorialForm.qml'))
        self.__setConnections()
        self.__locateWidgets()
        self.getSections()

    def __setConnections(self):
        self.reqReprSections.connect(self.setModel)
        self.reqReprTopics.connect(self.setModel)

    def __locateWidgets(self):
        self.setLayout(QHBoxLayout())
        self.layout().setContentsMargins(1, 1, 1, 1)
        self.layout().addWidget(self._widget)

    _reqSections = pyqtSignal(name='requireSections')
    _reqTopics = pyqtSignal(str, name='requireTopics')
    _reqReprSections = pyqtSignal(QQuickItem,
                                  str,
                                  list,
                                  name='reqReprSections')
    _reqReprTopics = pyqtSignal(QQuickItem, str, list, name='reqReprTopics')

    @pyqtSlot(name='getSections')
    def _getSections(self):
        self.requireSections.emit()

    def reprSectionsList(self, sections):
        self.reqReprSections.emit(self._widget.rootObject(),
                                  'setSectionsModel', sections)

    @pyqtSlot(str, name='getTopics')
    def _getTopics(self, section_id):
        self.requireTopics.emit(section_id)

    def reprTopicsList(self, topics):
        self.reqReprTopics.emit(self._widget.rootObject(), 'setTopicsModel',
                                topics)

    @pyqtSlot(QQuickItem, str, list, name='setModel')
    def _setModel(self, obj, callF, values):
        QMetaObject.invokeMethod(obj, callF, Q_ARG(QVariant, values))
Exemple #2
0
    def __init__(self, parent=None):
        super().__init__(parent, Qt.Dialog | Qt.FramelessWindowHint)
        # parent,
        # Qt.Dialog | Qt.FramelessWindowHint
        # )
        self._operations = {'row': False, 'col': True}
        self.setModal(True)
        # self.setAttribute(Qt.WA_TranslucentBackground)
        # self.setStyleSheet("background:transparent;")
        self.setFixedHeight(150)
        self.setFixedWidth(300)
        # Create the QML user interface.
        view = QQuickWidget()
        view.rootContext().setContextProperty("theme", NTheme.get_colors())
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("SplitOrientation.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)
        view.setFocusPolicy(Qt.StrongFocus)

        short_esc = QShortcut(QKeySequence(Qt.Key_Escape), self)
        short_esc.activated.connect(self.hide)
        self._root.selected['QString'].connect(self._split_operation)
Exemple #3
0
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)
Exemple #4
0
    def __init__(self, parent=None):
        super().__init__(parent, Qt.Dialog | Qt.FramelessWindowHint)
        self._main_container = parent
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setFixedWidth(650)
        # Create the QML UI
        view = QQuickWidget()
        view.rootContext().setContextProperty("theme", NTheme.get_colors())
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("AddFileFolder.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self._base_path = ""
        self._create_file_operation = True

        short_esc = QShortcut(QKeySequence(Qt.Key_Escape), self)
        short_esc.activated.connect(self.close)

        # Connection
        self._root.create.connect(self._create)
Exemple #5
0
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)
    def __init__(self, parent=None):
        super().__init__(parent, Qt.Dialog | Qt.FramelessWindowHint)
        self._main_container = parent
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setFixedWidth(650)
        # Create the QML UI
        view = QQuickWidget()
        view.rootContext().setContextProperty("theme", resources.QML_COLORS)
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("AddFileFolder.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self._base_path = ""
        self._create_file_operation = True

        short_esc = QShortcut(QKeySequence(Qt.Key_Escape), self)
        short_esc.activated.connect(self.close)

        # Connection
        self._root.create.connect(self._create)
Exemple #7
0
    def __init__(self, parent=None):
        super(LocatorWidget, self).__init__(
            parent, Qt.Dialog | Qt.FramelessWindowHint)
        self._parent = parent
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background:transparent;")
        self.setFixedHeight(400)
        self.setFixedWidth(500)
        view = QQuickWidget()
        view.rootContext().setContextProperty("theme", NTheme.get_colors())
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("Locator.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self.locate_symbols = locator.LocateSymbolsThread()
        self.locate_symbols.finished.connect(self._cleanup)
        # FIXME: invalid signal
        # self.locate_symbols.terminated.connect(self._cleanup)
        # Hide locator with Escape key
        shortEscMisc = QShortcut(QKeySequence(Qt.Key_Escape), self)
        shortEscMisc.activated.connect(self.hide)

        # Locator things
        self.filterPrefix = re.compile(r'(@|<|>|-|!|\.|/|:)')
        self.page_items_step = 10
        self._colors = {
            "@": "#5dade2",
            "<": "#4becc9",
            ">": "#ff555a",
            "-": "#66ff99",
            ".": "#a591c6",
            "/": "#f9d170",
            ":": "#18ffd6",
            "!": "#ff884d"}
        self._filters_list = [
            ("@", "Filename"),
            ("<", "Class"),
            (">", "Function"),
            ("-", "Attribute"),
            (".", "Current"),
            ("/", "Opened"),
            (":", "Line"),
            ("!", "NoPython")
        ]
        self._replace_symbol_type = {"<": "&lt;", ">": "&gt;"}
        self.reset_values()

        self._filter_actions = {
            '.': self._filter_this_file,
            '/': self._filter_tabs,
            ':': self._filter_lines
        }
        self._root.textChanged['QString'].connect(self.set_prefix)
        self._root.open['QString', int].connect(self._open_item)
        self._root.fetchMore.connect(self._fetch_more)
    def __init__(self, parent=None):
        super(LocatorWidget, self).__init__(
            parent, Qt.Dialog | Qt.FramelessWindowHint)
        self._parent = parent
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background:transparent;")
        self.setFixedHeight(400)
        self.setFixedWidth(500)
        view = QQuickWidget()
        view.rootContext().setContextProperty("theme", resources.QML_COLORS)
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("Locator.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self.locate_symbols = locator.LocateSymbolsThread()
        self.locate_symbols.finished.connect(self._cleanup)
        # FIXME: invalid signal
        # self.locate_symbols.terminated.connect(self._cleanup)
        # Hide locator with Escape key
        shortEscMisc = QShortcut(QKeySequence(Qt.Key_Escape), self)
        shortEscMisc.activated.connect(self.hide)

        # Locator things
        self.filterPrefix = re.compile(r'(@|<|>|-|!|\.|/|:)')
        self.page_items_step = 10
        self._colors = {
            "@": "#5dade2",
            "<": "#4becc9",
            ">": "#ff555a",
            "-": "#66ff99",
            ".": "#a591c6",
            "/": "#f9d170",
            ":": "#18ffd6",
            "!": "#ff884d"}
        self._filters_list = [
            ("@", "Filename"),
            ("<", "Class"),
            (">", "Function"),
            ("-", "Attribute"),
            (".", "Current"),
            ("/", "Opened"),
            (":", "Line"),
            ("!", "NoPython")
        ]
        self._replace_symbol_type = {"<": "&lt;", ">": "&gt;"}
        self.reset_values()

        self._filter_actions = {
            '.': self._filter_this_file,
            '/': self._filter_tabs,
            ':': self._filter_lines
        }
        self._root.textChanged['QString'].connect(self.set_prefix)
        self._root.open['QString', int].connect(self._open_item)
        self._root.fetchMore.connect(self._fetch_more)
class PythonSelector(QWidget):

    def __init__(self, btn, parent=None):
        super().__init__(parent, Qt.FramelessWindowHint | Qt.Popup)
        self.btn_selector = btn
        self.setAttribute(Qt.WA_TranslucentBackground)
        box = QVBoxLayout(self)
        self.view = QQuickWidget()
        self.view.setClearColor(Qt.transparent)
        self.setFixedWidth(400)
        self.setFixedHeight(200)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("PythonChooser.qml"))

        self._root = self.view.rootObject()
        box.addWidget(self.view)

        self._model = []
        self._root.pythonSelected.connect(self.set_python_interpreter)

    def setVisible(self, visible):
        super().setVisible(visible)
        self.btn_selector.setChecked(visible)

    def showEvent(self, event):
        ide = IDE.get_service("ide")
        move_to = ide.mapToGlobal(QPoint(0, 0))
        move_to -= QPoint(
            -ide.width() + self.width() - 5,
            -ide.height() + self.height() + 20)
        self.move(move_to)
        self._root.setModel(self._model)
        super().showEvent(event)

    def set_python_interpreter(self, path):
        ide = IDE.get_service("ide")
        obj = ide.get_interpreter(path)
        ide.set_interpreter(path)

        self.btn_selector.setText(obj.display_name)
        self.btn_selector.setToolTip(obj.path)

    def add_model(self, interpreters):
        self._model.clear()
        model = []
        for interpreter in interpreters:
            model.append([
                interpreter.display_name,
                interpreter.path,
                interpreter.exec_path
            ])
        self._model = model
        locator = IDE.get_service("interpreter")
        self.btn_selector.setText(locator.current.display_name)
        self.btn_selector.setEnabled(True)

    def hideEvent(self, event):
        super().hideEvent(event)
        self._root.clearModel()
class MainSelector(QWidget):
    removeWidget = pyqtSignal(int)
    changeCurrent = pyqtSignal(int)
    ready = pyqtSignal()
    animationCompleted = pyqtSignal()
    closePreviewer = pyqtSignal()

    def __init__(self, parent=None):
        super(MainSelector, self).__init__(parent)
        # Create the QML user interface.
        self.view = QQuickWidget()
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.engine().quit.connect(self.hide)
        self.view.setSource(ui_tools.get_qml_resource("MainSelector.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[int].connect(self.changeCurrent.emit)
        self._root.open[int].connect(self._clean_removed)
        self._root.ready.connect(self.ready.emit)
        self._root.closePreviewer.connect(self.closePreviewer.emit)
        self._root.animationCompleted.connect(self.animationCompleted.emit)

    def set_model(self, model):
        for index, path, closable in model:
            self.add_to_model(index, path, closable)

    @pyqtSlot(int, "QString", bool)
    def add_to_model(self, i, path, type_state):
        self._root.add_widget(i, path, type_state)

    def set_preview(self, index, preview_path):
        self._root.add_preview(index, preview_path)

    def close_selector(self):
        self._root.close_selector()

    def GoTo_GridPreviews(self):  #start_animation
        self._root.start_animation()
        self._root.forceActiveFocus()

    def showPreview(self):
        self._root.showPreview()
        self._root.forceActiveFocus()

    def open_item(self, index):
        """Open the item at index."""
        self._root.select_item(index)

    def _clean_removed(self):
        removed = sorted(self._root.get_removed(), reverse=True)
        print("_clean_removed", removed)
        for r in removed:
            self.removeWidget.emit(r)
        self._root.clean_removed()
class MainSelector(QWidget):
    removeWidget = pyqtSignal(int)
    changeCurrent = pyqtSignal(int)
    ready = pyqtSignal()
    animationCompleted = pyqtSignal()
    closePreviewer = pyqtSignal()
    def __init__(self, parent=None):
        super(MainSelector, self).__init__(parent)
        # Create the QML user interface.
        self.view = QQuickWidget()
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.engine().quit.connect(self.hide)
        self.view.setSource(ui_tools.get_qml_resource("MainSelector.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[int].connect(self.changeCurrent.emit)
        self._root.open[int].connect(self._clean_removed)
        self._root.ready.connect(self.ready.emit)
        self._root.closePreviewer.connect(self.closePreviewer.emit)
        self._root.animationCompleted.connect(self.animationCompleted.emit)

    def set_model(self, model):
        for index, path, closable in model:
            self.add_to_model(index, path, closable)

    @pyqtSlot(int, "QString", bool)
    def add_to_model(self, i, path, type_state):
        self._root.add_widget(i, path, type_state)

    def set_preview(self, index, preview_path):
        self._root.add_preview(index, preview_path)

    def close_selector(self):
        self._root.close_selector()

    def GoTo_GridPreviews(self):#start_animation
        self._root.start_animation()
        self._root.forceActiveFocus()

    def showPreview(self):
        self._root.showPreview()
        self._root.forceActiveFocus()

    def open_item(self, index):
        """Open the item at index."""
        self._root.select_item(index)

    def _clean_removed(self):
        removed = sorted(self._root.get_removed(), reverse=True)
        print("_clean_removed", removed)
        for r in removed:
            self.removeWidget.emit(r)
        self._root.clean_removed()
Exemple #12
0
class ScheduleView(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self._presenter = SchedulePresenter(self)
        self._widget = QQuickWidget(self)
        self.setLayout(QHBoxLayout())
        self.layout().setContentsMargins(1, 1, 1, 1)
        self.layout().addWidget(self._widget)
        self._widget.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        self._widget.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self._widget.rootContext().setContextProperty('scheduleView', self)
        self._widget.rootContext().setContextProperty('groupsModel', self)
        self._widget.setSource(
            QUrl('modules/schedule/scheduleForm/ScheduleForm.qml'))
        self.reqReprSchedules.connect(self.setModel)
        self.reqInitSchedule.connect(self.initSchedule)

    @pyqtSlot(int, name='changeWidth')
    def _changeWidth(self, _width):
        self.setFixedWidth(_width)

    _reqGroups = pyqtSignal(name='requireGroups')
    _reqSchedules = pyqtSignal(str,
                               name='requireSchedules',
                               arguments=['group'])
    _reqReprSchedules = pyqtSignal(QQuickItem,
                                   str,
                                   list,
                                   name='reqReprSchedules')
    _reqInitSchedule = pyqtSignal(QQuickItem, name='reqInitSchedule')

    @pyqtSlot(name='getGroups')
    def _getGroups(self):
        self.requireGroups.emit()

    def reprGroupsList(self, groups):
        self.setPropertyList('groupsModel', groups)

    def setPropertyList(self, objectName, values):
        self._widget.rootContext().setContextProperty(objectName, values)

    @pyqtSlot(str, name='getSchedules')
    def _getSchedules(self, group):
        self.requireSchedules.emit(group)

    def reprSchedules(self, schedules):
        self.reqReprSchedules.emit(self._widget.rootObject(),
                                   'setScheduleModel', schedules)

    @pyqtSlot(QQuickItem, str, list, name='setModel')
    def _setModel(self, obj, callF, values):
        QMetaObject.invokeMethod(obj, callF, Q_ARG(QVariant, values))

    @pyqtSlot(QQuickItem, name='initSchedule')
    def _initSchedule(self, obj):
        QMetaObject.invokeMethod(obj, "initSchedule")
class PythonSelector(QWidget):
    def __init__(self, btn, parent=None):
        super().__init__(parent, Qt.FramelessWindowHint | Qt.Popup)
        self.btn_selector = btn
        self.setAttribute(Qt.WA_TranslucentBackground)
        box = QVBoxLayout(self)
        self.view = QQuickWidget()
        self.view.setClearColor(Qt.transparent)
        self.setFixedWidth(400)
        self.setFixedHeight(200)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("PythonChooser.qml"))

        self._root = self.view.rootObject()
        box.addWidget(self.view)

        self._model = []
        self._root.pythonSelected.connect(self.set_python_interpreter)

    def setVisible(self, visible):
        super().setVisible(visible)
        self.btn_selector.setChecked(visible)

    def showEvent(self, event):
        ide = IDE.get_service("ide")
        move_to = ide.mapToGlobal(QPoint(0, 0))
        move_to -= QPoint(-ide.width() + self.width() - 5,
                          -ide.height() + self.height() + 20)
        self.move(move_to)
        self._root.setModel(self._model)
        super().showEvent(event)

    def set_python_interpreter(self, path):
        ide = IDE.get_service("ide")
        obj = ide.get_interpreter(path)
        ide.set_interpreter(path)

        self.btn_selector.setText(obj.display_name)
        self.btn_selector.setToolTip(obj.path)

    def add_model(self, interpreters):
        self._model.clear()
        model = []
        for interpreter in interpreters:
            model.append([
                interpreter.display_name, interpreter.path,
                interpreter.exec_path
            ])
        self._model = model
        locator = IDE.get_service("interpreter")
        self.btn_selector.setText(locator.current.display_name)
        self.btn_selector.setEnabled(True)

    def hideEvent(self, event):
        super().hideEvent(event)
        self._root.clearModel()
Exemple #14
0
    def __init__(self, parent=None):
        super().__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        view = QQuickWidget()
        qml = os.path.join(settings.QML_PATH, "ListRelation.qml")
        view.setSource(QUrl.fromLocalFile(qml))
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        vbox.addWidget(view)

        self._root = view.rootObject()

        self._root.itemClicked.connect(lambda i: self.itemClicked.emit(i))
Exemple #15
0
class gauge(QWidget):
    def __init__(self, parent = None):
        super(gauge, self).__init__(parent)
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.gaugeWidget = QQuickWidget()
        self.gaugeWidget.setSource(QUrl('full_gauge.qml'))
        self.gauge = self.gaugeWidget.rootObject().findChild(QObject, 'test_gauge')
        self.gauge.setProperty('gauge_value',0)
        self.layout.addWidget(self.gaugeWidget)

    def setValue(self, time, value):
        #print ('guage value = ', value)
        self.gauge.setProperty('gauge_value',value)
Exemple #16
0
 def __init__(self, parent=None):
     super(MainSelector, self).__init__(parent)
     self.setAttribute(Qt.WA_TranslucentBackground)
     self.setAttribute(Qt.WA_ShowWithoutActivating)
     # Create the QML user interface.
     view = QQuickWidget()
     view.setClearColor(Qt.transparent)
     view.setResizeMode(QQuickWidget.SizeRootObjectToView)
     view.setSource(ui_tools.get_qml_resource("MainSelector.qml"))
     self._root = view.rootObject()
     vbox = QVBoxLayout(self)
     vbox.setContentsMargins(0, 0, 0, 0)
     vbox.setSpacing(0)
     vbox.addWidget(view)
    def __init__(self, parent=None):
        super().__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        view = QQuickWidget()
        qml = os.path.join(settings.QML_PATH, "ListRelation.qml")
        view.setSource(QUrl.fromLocalFile(qml))
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        vbox.addWidget(view)

        self._root = view.rootObject()

        self._root.itemClicked.connect(
            lambda i: self.itemClicked.emit(i))
class Window(QWidget):
    # RIGHT_SIDEBAR_VIEW_PATH = "side-bar-ui.qml"
    RIGHT_SIDEBAR_VIEW_PATH = "custom.qml"

    def __init__(self):
        QWidget.__init__(self)
        self.move(450, 90)
        self.resize(322, 600)
        self._define_ui()
        # self._connect_ui()
        self._init_window()
        self.show()

    def _define_ui(self):
        self.quick = QQuickWidget()
        self.quick.statusChanged.connect(self.handleStatusChange)
        self.quick.setSource(QUrl().fromLocalFile(
            self.RIGHT_SIDEBAR_VIEW_PATH))
        self.quick.setResizeMode(QQuickWidget.SizeRootObjectToView)

        self._quick = self.quick.rootObject()

    def _connect_ui(self):
        self._quick.newImage.connect(self._newImage)
        self._quick.editImage.connect(self._editImage)
        self._quick.deleteImage.connect(self._deleteImage)

    def _init_window(self):
        box_layout = QHBoxLayout()
        box_layout.addWidget(self.quick)
        self.setLayout(box_layout)

    def handleStatusChange(self, status):
        if status == self.quick.Error:
            [print(e.toString()) for e in self.quick.errors()]

    @pyqtSlot(str)
    def _newImage(self, index):
        print("newImage({0})".format(int(index) + 1))

    @pyqtSlot(str)
    def _editImage(self, index):
        print("edit({0})".format(int(index) + 1))

    @pyqtSlot(str)
    def _deleteImage(self, index):
        print("delete({0})".format(int(index) + 1))
Exemple #19
0
 def initTabWidget(self, tabWidget: ColorTabWidget, handle: ProjectReader):
     tabManager = TabManager(tabWidget, handle)
     # init qml main page list
     projectMainPage = QQuickWidget(tabWidget)
     projectMainPage.setResizeMode(QQuickWidget.SizeRootObjectToView)
     projectMainPage.setSource(
         QUrl.fromLocalFile('QML/ProjectMainPage.qml'))
     projectMainPage.setMinimumWidth(550)
     projectMainPage.setMinimumHeight(250)
     projectMainPage.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
     obj_projectMainPage = projectMainPage.rootObject()
     # send main page init dict
     obj_projectMainPage.onInitMainPageItems(
         self.getProjectDetail(tabManager))
     obj_projectMainPage.sendData.connect(self.getData_ProjectMainPage)
     tabManager.qmlHandle = obj_projectMainPage
     tabManager.qmlWidget = projectMainPage
     tabWidget.addTab(projectMainPage, 'MainPage:MainPage')
     return tabManager
Exemple #20
0
    def __init__(self, parent=None):
        super(SplitOrientation,
              self).__init__(parent, Qt.Dialog | Qt.FramelessWindowHint)
        self._operations = {'row': False, 'col': True}
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background:transparent;")
        self.setFixedHeight(150)
        self.setFixedWidth(290)
        # Create the QML user interface.
        view = QQuickWidget()
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("SplitOrientation.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self._root.selected.connect(self._split_operation)
    def __init__(self, parent=None):
        super(SplitOrientation, self).__init__(parent,
            Qt.Dialog | Qt.FramelessWindowHint)
        self._operations = {'row': False, 'col': True}
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background:transparent;")
        self.setFixedHeight(150)
        self.setFixedWidth(290)
        # Create the QML user interface.
        view = QQuickWidget()
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("SplitOrientation.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self._root.selected.connect(self._split_operation)
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.__need_restart = False
        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        view = QQuickWidget()
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        qml = os.path.join(settings.QML_PATH, "Preferences.qml")
        view.setSource(QUrl.fromLocalFile(qml))
        box.addWidget(view)

        self.__root = view.rootObject()
        # Lista de idiomas para el Combo qml
        available_langs = file_manager.get_files_from_folder(
            settings.LANGUAGE_PATH)
        langs = ["English"] + available_langs
        self.__root.addLangsToCombo(langs)

        self.__root.setCurrentLanguage(CONFIG.get("language"))

        font = CONFIG.get("fontFamily")
        size = CONFIG.get("fontSize")
        if font is None:
            font, size = CONFIG._get_font()

        self.__root.setFontFamily(font, size)

        self.__root.setInitialStates(
            CONFIG.get("highlightCurrentLine"),
            CONFIG.get("matchParenthesis"))

        # Conexiones
        self.__root.close.connect(lambda: self.settingsClosed.emit())
        self.__root.resetSettings.connect(self.__reset_settings)
        self.__root.checkForUpdates.connect(self.__check_for_updates)
        self.__root.changeLanguage.connect(self.__change_language)
        self.__root.stateCurrentLineChanged[bool].connect(
            self.__on_state_current_line_changed)
        self.__root.stateMatchingParenChanged[bool].connect(
            self.__on_state_matching_parenthesis_changed)
        self.__root.needChangeFont.connect(self.__change_font)
Exemple #23
0
    def __init__(self, parent=None):
        super(Notification, self).__init__(None, Qt.ToolTip)
        self._parent = parent
        self._duration = 3000
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setAttribute(Qt.WA_TransparentForMouseEvents)
        self.setAttribute(Qt.WA_ShowWithoutActivating)
        self.setFixedHeight(30)
        # Create the QML user interface.
        view = QQuickWidget()
        view.setClearColor(Qt.transparent)
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("Notification.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self._root.close.connect(self.close)
        self._parent.goingDown.connect(self.close)
Exemple #24
0
    def __init__(self, parent=None):
        super(Notification, self).__init__(None, Qt.ToolTip)
        self._parent = parent
        self._duration = 3000
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setAttribute(Qt.WA_TransparentForMouseEvents)
        self.setAttribute(Qt.WA_ShowWithoutActivating)
        self.setStyleSheet("background:transparent")
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setFixedHeight(30)
        # Create the QML user interface.
        view = QQuickWidget()
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("Notification.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self._root.close.connect(self.close)
    def __init__(self, parent=None):
        super(Notification, self).__init__(None, Qt.ToolTip)
        self._parent = parent
        self._duration = 3000
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setAttribute(Qt.WA_TransparentForMouseEvents)
        self.setAttribute(Qt.WA_ShowWithoutActivating)
        self.setStyleSheet("background:transparent")
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setFixedHeight(30)
        # Create the QML user interface.
        view = QQuickWidget()
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("Notification.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self._root.close.connect(self.close)
Exemple #26
0
    def __init__(self, parent=None):
        super().__init__(parent, Qt.WindowStaysOnTopHint)
        box = QVBoxLayout(self)
        box.setContentsMargins(3, 3, 3, 3)
        box.setSpacing(0)
        # Model
        self._manager = BookmarkManager()
        # QML UI
        view = QQuickWidget()
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.rootContext().setContextProperty("bookmarkModel", self._manager)
        view.rootContext().setContextProperty("theme", resources.QML_COLORS)
        view.setSource(ui_tools.get_qml_resource("BookmarkList.qml"))
        box.addWidget(view)

        self._root = view.rootObject()

        self._root.openBookmark.connect(self._open_bookmark)
        self._root.menuRequested.connect(self._show_menu)

        IDE.register_service("bookmarks", self)
        ExplorerContainer.register_tab("Bookmarks", self)
    def __init__(self, parent=None):
        super().__init__(parent, Qt.WindowStaysOnTopHint)
        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        box.setSpacing(0)
        # Model
        self._manager = BookmarkManager()
        # QML UI
        view = QQuickWidget()
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.rootContext().setContextProperty("bookmarkModel", self._manager)
        view.rootContext().setContextProperty("theme", resources.QML_COLORS)
        view.setSource(ui_tools.get_qml_resource("BookmarkList.qml"))
        box.addWidget(view)

        self._root = view.rootObject()

        self._root.openBookmark.connect(self._open_bookmark)
        self._root.menuRequested.connect(self._show_menu)

        IDE.register_service("bookmarks", self)
        ExplorerContainer.register_tab("Bookmarks", self)
Exemple #28
0
    def __init__(self, parent=None):
        super(Notification, self).__init__(None, Qt.ToolTip)
        self._parent = parent
        self._duration = 1800
        self._text = ""
        self._running = False
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setAttribute(Qt.WA_TransparentForMouseEvents)
        self.setAttribute(Qt.WA_ShowWithoutActivating)
        self.setFixedHeight(30)
        # Create the QML user interface.
        view = QQuickWidget()
        view.setClearColor(Qt.transparent)
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("Notification.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self._root.close.connect(self.close)
        self._parent.goingDown.connect(self.close)
Exemple #29
0
    def __init__(self, qml_file, qml_engine=None):

        super().__init__()

        path = str(ConfigInstall.Path.join_qml_path(qml_file + '.qml'))

        if qml_engine is not None:
            widget = QQuickWidget(qml_engine, self)
        else:
            widget = QQuickWidget(self)
        # The view will automatically resize the root item to the size of the view.
        widget.setResizeMode(QQuickWidget.SizeRootObjectToView)
        # The view resizes with the root item in the QML.
        # widget.setResizeMode(QQuickWidget.SizeViewToRootObject)
        widget.setSource(QUrl(path))
        # widget.resize(*minimum_size)

        root_object = widget.rootObject()
        root_object.accepted.connect(self.accept)
        root_object.rejected.connect(self.reject)

        self._widget = widget
        self._root_object = root_object
Exemple #30
0
    def __init__(self, qml_file, qml_engine=None):

        super().__init__()

        path = str(ConfigInstall.Path.join_qml_path(qml_file + '.qml'))

        if qml_engine is not None:
            widget = QQuickWidget(qml_engine, self)
        else:
            widget = QQuickWidget(self)
        # The view will automatically resize the root item to the size of the view.
        widget.setResizeMode(QQuickWidget.SizeRootObjectToView)
        # The view resizes with the root item in the QML.
        # widget.setResizeMode(QQuickWidget.SizeViewToRootObject)
        widget.setSource(QUrl(path))
        # widget.resize(*minimum_size)

        root_object = widget.rootObject()
        root_object.accepted.connect(self.accept)
        root_object.rejected.connect(self.reject)

        self._widget = widget
        self._root_object = root_object
    def __init__(self, parent=None):
        super().__init__(parent, Qt.Dialog | Qt.FramelessWindowHint)
        self._operations = {'row': False, 'col': True}
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background:transparent;")
        self.setFixedHeight(150)
        self.setFixedWidth(290)
        # Create the QML user interface.
        view = QQuickWidget()
        view.setClearColor(Qt.transparent)
        view.rootContext().setContextProperty("theme", resources.QML_COLORS)
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("SplitOrientation.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)
        view.setFocusPolicy(Qt.StrongFocus)

        short_esc = QShortcut(QKeySequence(Qt.Key_Escape), self)
        short_esc.activated.connect(self.hide)
        self._root.selected['QString'].connect(self._split_operation)
Exemple #32
0
class StartPage(QWidget):
    openPreferences = pyqtSignal()
    newFile = pyqtSignal(str)
    openProject = pyqtSignal(str)
    openFiles = pyqtSignal(list)

    def __init__(self, parent=None):
        super(StartPage, self).__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self.view = QQuickWidget()
        self.view.setMinimumWidth(400)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("StartPage.qml"))
        self.root = self.view.rootObject()
        vbox.addWidget(self.view)

        self.load_items()

        self.root.openProject.connect(self._open_project)
        self.root.removeProject.connect(self._on_click_on_delete)
        self.root.markAsFavorite.connect(self._on_click_on_favorite)
        self.root.openPreferences.connect(self.openPreferences.emit)
        self.root.newFile.connect(lambda: self.newFile.emit(
            translations.TR_NEW_DOCUMENT))  #self.test)
        self.root.openFiles.connect(self.checkFiles)

        self.root.set_year(str(datetime.datetime.now().year))

    def test(self, c="-.-"):
        print(c)
        self.newFile.emit(c)

    def checkFiles(self, lst):
        f = QFileInfo()
        newLst = []
        for url in lst:
            _file = url.toLocalFile()
            print("FILE::", url, _file)
            f.setFile(_file)
            if f.suffix() not in ("tar", "exe", "mp3", "mp4", "flv", "zip",
                                  "rar", "iso"):
                newLst.append(_file)

        if newLst:
            self.openFiles.emit(newLst)

    def _open_project(self, path):
        projects_explorer = IDE.get_service('projects_explorer')
        if projects_explorer:
            projects_explorer.open_project_folder(path)

    def _on_click_on_delete(self, path):
        settings = IDE.data_settings()
        recent_projects = settings.value("recentProjects")
        if path in recent_projects:
            del recent_projects[path]
            settings.setValue("recentProjects", recent_projects)

    def _on_click_on_favorite(self, path, value):
        settings = IDE.data_settings()
        recent_projects = settings.value("recentProjects")
        properties = recent_projects[path]
        properties["isFavorite"] = value
        recent_projects[path] = properties
        settings.setValue("recentProjects", recent_projects)

    def load_items(self):
        settings = IDE.data_settings()
        listByFavorites = []
        listNoneFavorites = []
        recent_projects_dict = dict(settings.value('recentProjects', {}))
        #Filter for favorites
        for recent_project_path, content in list(recent_projects_dict.items()):
            if bool(dict(content)["isFavorite"]):
                listByFavorites.append(
                    (recent_project_path, content["lastopen"]))
            else:
                listNoneFavorites.append(
                    (recent_project_path, content["lastopen"]))
        if len(listByFavorites) > 1:
            # sort by date favorites
            listByFavorites = sorted(listByFavorites,
                                     key=lambda date: listByFavorites[1])

        if len(listNoneFavorites) > 1:
            #sort by date last used
            listNoneFavorites = sorted(listNoneFavorites,
                                       key=lambda date: listNoneFavorites[1])

        for recent_project_path in listByFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, True)

        for recent_project_path in listNoneFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, False)
        self.root.forceActiveFocus()
Exemple #33
0
class FilesHandler(QWidget):
    def __init__(self, parent=None):
        super(FilesHandler, self).__init__(None,
                                           Qt.FramelessWindowHint | Qt.Popup)
        self._main_container = parent
        self.setStyleSheet("background:transparent;")
        # Create the QML user interface.
        self.view = QQuickWidget()
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("FilesHandler.qml"))
        self._root = self.view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        self._model = {}
        self._temp_files = {}
        self._max_index = 0

        self._root.open['QString', 'QString', 'QString'].connect(self._open)
        self._root.hide.connect(self.hide)
        # self.connect(self._root, SIGNAL("open(QString, QString, QString)"),
        #             self._open)
        # self.connect(self._root, SIGNAL("close(QString, QString)"), self._close)
        # self.connect(self._root, SIGNAL("hide()"), self.hide)
        # self.connect(self._root, SIGNAL("fuzzySearch(QString)"),
        #             self._fuzzy_search)

    def _open(self, path, temp, project):
        if project:
            path = os.path.join(os.path.split(project)[0], path)
            self._main_container.open_file(path)
        elif temp:
            nfile = self._temp_files[temp]
            ninjaide = IDE.get_service("ide")
            neditable = ninjaide.get_or_create_editable(nfile=nfile)
            self._main_container.current_widget.set_current(neditable)
        else:
            self._main_container.open_file(path)
            index = self._model[path]
            self._max_index = max(self._max_index, index) + 1
            self._model[path] = self._max_index
        self.hide()

    def _close(self, path, temp):
        if temp:
            nfile = self._temp_files.get(temp, None)
        else:
            ninjaide = IDE.get_service("ide")
            nfile = ninjaide.get_or_create_nfile(path)
        if nfile is not None:
            nfile.close()

    def _fuzzy_search(self, search):
        search = '.+'.join(re.escape(search).split('\\ '))
        pattern = re.compile(search, re.IGNORECASE)

        model = []
        for project_path in locator.files_paths:
            files_in_project = locator.files_paths[project_path]
            base_project = os.path.basename(project_path)
            for file_path in files_in_project:
                file_path = os.path.join(
                    base_project, os.path.relpath(file_path, project_path))
                if pattern.search(file_path):
                    model.append(
                        [os.path.basename(file_path), file_path, project_path])
        self._root.set_fuzzy_model(model)

    def _add_model(self):
        ninjaide = IDE.get_service("ide")
        files = ninjaide.opened_files
        # Update model
        old = set(self._model.keys())
        new = set([nfile.file_path for nfile in files])
        result = old - new
        for item in result:
            del self._model[item]
        current_editor = self._main_container.get_current_editor()
        current_path = None
        if current_editor:
            current_path = current_editor.file_path
        model = []
        for nfile in files:
            if (nfile.file_path not in self._model
                    and nfile.file_path is not None):
                self._model[nfile.file_path] = 0
            neditable = ninjaide.get_or_create_editable(nfile=nfile)
            checkers = neditable.sorted_checkers
            checks = []
            for items in checkers:
                checker, color, _ = items
                if checker.dirty:
                    # Colors needs to be reversed for QML
                    color = "#%s" % color[::-1][:-1]
                    checks.append({
                        "checker_text": checker.dirty_text,
                        "checker_color": color
                    })
            modified = neditable.editor.is_modified
            temp_file = str(uuid.uuid4()) if nfile.file_path is None else ""
            filepath = nfile.file_path if nfile.file_path is not None else ""
            model.append(
                [nfile.file_name, filepath, checks, modified, temp_file])
            if temp_file:
                self._temp_files[temp_file] = nfile
        if current_path:
            index = self._model[current_path]
            self._max_index = max(self._max_index, index) + 1
            self._model[current_path] = self._max_index
        model = sorted(model,
                       key=lambda x: self._model.get(x[1], False),
                       reverse=True)
        self._root.set_model(model)

    def showEvent(self, event):
        self._add_model()
        widget = self._main_container.get_current_editor()
        if widget is None:
            widget = self._main_container
        if self._main_container.splitter.count() < 2:
            width = max(widget.width() / 2, 500)
            height = max(widget.height() / 2, 400)
        else:
            width = widget.width()
            height = widget.height()
        self.view.setFixedWidth(width)
        self.view.setFixedHeight(height)

        super(FilesHandler, self).showEvent(event)
        self._root.show_animation()
        point = widget.mapToGlobal(self.view.pos())
        self.move(point.x(), point.y())
        self.view.setFocus()
        self._root.activateInput()

    def hideEvent(self, event):
        super(FilesHandler, self).hideEvent(event)
        self._temp_files = {}
        self._root.clear_model()

    def next_item(self):
        if not self.isVisible():
            self.show()
        self._root.next_item()

    def previous_item(self):
        if not self.isVisible():
            self.show()
        self._root.previous_item()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.hide()
        elif (event.modifiers() == Qt.ControlModifier and event.key()
              == Qt.Key_PageDown) or event.key() == Qt.Key_Down:
            self._root.next_item()
        elif (event.modifiers() == Qt.ControlModifier
              and event.key() == Qt.Key_PageUp) or event.key() == Qt.Key_Up:
            self._root.previous_item()
        elif event.key() in (Qt.Key_Return, Qt.Key_Enter):
            self._root.open_item()
        super(FilesHandler, self).keyPressEvent(event)
Exemple #34
0
class Scene(QGraphicsScene):
    RIGHT_SIDEBAR_VIEW_PATH = "design.qml"

    def __init__(self):
        QGraphicsScene.__init__(self)
        self._define_ui()
        self._connect_ui()

        self.pen = QPen(QColor("#000000"), 4)

        self.origin_pos = None
        self.current_pos = None
        self.mode = None

    def _define_ui(self):
        self.quick = QQuickWidget()
        self.quick.setSource(QUrl().fromLocalFile(
            Scene.RIGHT_SIDEBAR_VIEW_PATH))
        self.quick.setResizeMode(QQuickWidget.SizeRootObjectToView)

        self._root_object = self.quick.rootObject()

    def _connect_ui(self):
        self._root_object.changeColor.connect(self._change_color)
        self._root_object.setShape.connect(self._set_shape)
        self._root_object.clear.connect(self._clear)

    def mousePressEvent(self, event):
        self.origin_pos = event.scenePos()

    def mouseMoveEvent(self, event):
        self.current_pos = event.scenePos()

        if self.mode == "rectangle":
            self.draw_rectangle()
        if self.mode == "line":
            self.draw_line()
        if self.mode == "brush":
            self.draw_curve()

    def draw_rectangle(self):
        rect = QRectF(self.origin_pos, self.current_pos)
        rect_item = QGraphicsRectItem(rect)
        rect_item.setPen(self.pen)
        rect_item.setFlag(QGraphicsItem.ItemIsMovable, True)
        if len(self.items()) > 0:
            self.clear_last_item()
        self.addItem(rect_item)

    def draw_line(self):
        line = QLineF(self.origin_pos, self.current_pos)
        line_item = QGraphicsLineItem(line)
        line_item.setPen(self.pen)
        line_item.setFlag(QGraphicsItem.ItemIsMovable, True)
        if len(self.items()) > 0:
            self.clear_last_item()
        self.addItem(line_item)

    def draw_curve(self):
        curve = QLineF(self.origin_pos, self.current_pos)
        curve_item = QGraphicsLineItem(curve)
        curve_item.setPen(self.pen)
        curve_item.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.addItem(curve_item)
        self.origin_pos = self.current_pos

    def clear_last_item(self):
        self.removeItem(self.items()[len(self.items()) - 1])
        self.update()

    @pyqtSlot(str)
    def _change_color(self, color):
        self.pen = QPen(QColor(color), 4)

    @pyqtSlot(str)
    def _set_shape(self, mode):
        self.mode = mode

    @pyqtSlot()
    def _clear(self):
        if self:
            for item in self.items():
                self.removeItem(item)
                self.update()
Exemple #35
0
class PageThumbnailer(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._view = QQuickWidget()  # QQuickWidget
        self._size = QSize(450, 253) * gVar.app.devicePixelRatio()
        self._url = QUrl()
        self._title = ''
        self._loadTitle = False

        self._view.setAttribute(Qt.WA_DontShowOnScreen)
        self._view.setSource(QUrl('qrc:data/thumbnailer.qml'))
        self._view.rootContext().setContextProperty('thumbnailer', self)
        self._view.show()

    def setSize(self, size):
        if size.isValid():
            self._size = size

    def setUrl(self, url):
        if url.isValid():
            self._url = url

    def url(self):
        return self._url

    def loadTitle(self):
        '''
        @return: bool
        '''
        return self._loadTitle

    def setLoadTitle(self, load):
        '''
        @param: load bool
        '''
        self._loadTitle = load

    def title(self):
        title = self._title
        if not title:
            title = self._url.host()
        if not title:
            title = self._url.toString()
        return title

    def start(self):
        if self._view.rootObject() and WebView.isUrlValid(self._url):
            self._view.rootObject().setProperty('url', self._url)
        else:

            def func():
                self.thumbnailCreated.emit(QPixmap())

            QTimer.singleShot(500, func)

    # Q_SIGNALS:
    thumbnailCreated = pyqtSignal(QPixmap)

    # public Q_SLOTS:
    @pyqtSlot(result=str)
    def afterLoadScript(self):
        '''
        @return: QString
        '''
        return Scripts.setCss('::~webkit-scrollbar{display:none;}')

    @pyqtSlot(bool)
    def createThumbnail(self, status):
        '''
        @param: status bool
        '''
        if not status:
            self.thumbnailCreated.emit(QPixmap())
            return

        def func():
            self._title = self._view.rootObject().property('title').strip()
            img = self._view.grabFramebuffer().scaled(self._size,
                                                      Qt.IgnoreAspectRatio,
                                                      Qt.SmoothTransformation)
            pixmap = QPixmap.fromImage(img)
            self.thumbnailCreated.emit(pixmap)

        QTimer.singleShot(1000, func)
Exemple #36
0
class FilesHandler(QWidget):

    def __init__(self, parent=None):
        super(FilesHandler, self).__init__(
            None, Qt.FramelessWindowHint | Qt.Popup)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self._main_container = parent
        # Create the QML user interface.
        self.setFixedHeight(300)
        self.setFixedWidth(400)
        self.view = QQuickWidget()
        self.view.rootContext().setContextProperty(
            "theme", resources.QML_COLORS)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("FilesHandler.qml"))
        # self.view.setClearColor(Qt.transparent)
        self._root = self.view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        self._model = {}
        self._temp_files = {}
        self._max_index = 0

        self._root.open.connect(self._open)
        self._root.close.connect(self._close)
        self._root.fuzzySearch.connect(self._fuzzy_search)
        self._root.hide.connect(self.hide)

    def _open(self, path, temp, project):
        if project:
            path = os.path.join(os.path.split(project)[0], path)
            self._main_container.open_file(path)
        elif temp:
            nfile = self._temp_files[temp]
            ninjaide = IDE.get_service("ide")
            neditable = ninjaide.get_or_create_editable(nfile=nfile)
            self._main_container.combo_area.set_current(neditable)
        else:
            self._main_container.open_file(path)
            index = self._model[path]
            self._max_index = max(self._max_index, index) + 1
            self._model[path] = self._max_index
        self.hide()

    def _close(self, path, temp):
        # FIXME: when we have splitters?
        if temp:
            nfile = self._temp_files.get(temp, None)
        else:
            ninjaide = IDE.get_service("ide")
            nfile = ninjaide.get_or_create_nfile(path)
        if nfile is not None:
            nfile.close()

    def _fuzzy_search(self, search):
        search = '.+'.join(re.escape(search).split('\\ '))
        pattern = re.compile(search, re.IGNORECASE)

        model = []
        for project_path in locator.files_paths:
            files_in_project = locator.files_paths[project_path]
            base_project = os.path.basename(project_path)
            for file_path in files_in_project:
                file_path = os.path.join(
                    base_project, os.path.relpath(file_path, project_path))
                if pattern.search(file_path):
                    model.append([os.path.basename(file_path), file_path,
                                  project_path])
        self._root.set_fuzzy_model(model)

    def _add_model(self):
        ninjaide = IDE.get_service("ide")
        files = ninjaide.opened_files
        # Update model
        current_editor = self._main_container.get_current_editor()
        current_path = None
        if current_editor is not None:
            current_path = current_editor.file_path
        model = []
        for nfile in files:
            if nfile.file_path is not None and \
                    nfile.file_path not in self._model:
                self._model[nfile.file_path] = 0
            neditable = ninjaide.get_or_create_editable(nfile=nfile)
            checkers = neditable.sorted_checkers
            checks = []
            for item in checkers:
                checker, color, _ = item
                if checker.dirty:
                    checks.append({
                        "checker_text": checker.dirty_text,
                        "checker_color": color
                    })
            modified = neditable.editor.is_modified
            temp_file = str(uuid.uuid4()) if nfile.file_path is None else ""
            filepath = nfile.file_path if nfile.file_path is not None else ""
            model.append([
                nfile.file_name, filepath,
                checks, modified, temp_file])
            if temp_file:
                self._temp_files[temp_file] = nfile
        if current_path is not None:
            index = self._model[current_path]
            self._max_index = max(self._max_index, index) + 1
            self._model[current_path] = self._max_index
        model = sorted(model, key=lambda x: self._model.get(x[1], False),
                       reverse=True)
        self._root.set_model(model)

    def showEvent(self, event):
        self._add_model()
        editor_widget = self._main_container.get_current_editor()
        simple = False
        if editor_widget.height() < 400 or editor_widget.width() < 350:
            width = editor_widget.width()
            height = self._main_container.height() / 3
            simple = True
        else:
            width = max(editor_widget.width() / 3, 550)
            height = max(editor_widget.height() / 2, 400)

        self.setFixedWidth(width)
        self.setFixedHeight(height)

        self._root.setMode(simple)
        super(FilesHandler, self).showEvent(event)
        # self._root.show_animation()
        point = editor_widget.mapToGlobal(self.view.pos())
        self.move(point)
        # Trick
        QTimer.singleShot(100, self.__set_focus)

    def __set_focus(self):
        self.view.setFocus()
        self._root.activateInput()

    def hideEvent(self, event):
        super(FilesHandler, self).hideEvent(event)
        self._temp_files = {}
        self._root.clear_model()
        # Recovery focus
        editor_widget = self._main_container.get_current_editor()
        if editor_widget is not None:
            editor_widget.setFocus()

    def next_item(self):
        if not self.isVisible():
            self.show()
        # self._root.next_item()

    def previous_item(self):
        if not self.isVisible():
            self.show()
        self._root.previous_item()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.hide()
        elif (event.modifiers() == Qt.ControlModifier and
                event.key() == Qt.Key_Tab):
            self._root.next_item()
        elif (event.modifiers() == Qt.ControlModifier and
                event.key() == Qt.Key_PageDown) or event.key() == Qt.Key_Down:
            self._root.next_item()
        elif (event.modifiers() == Qt.ControlModifier and
                event.key() == Qt.Key_PageUp) or event.key() == Qt.Key_Up:
            self._root.previous_item()
        elif event.key() in (Qt.Key_Return, Qt.Key_Enter):
            self._root.open_item()
        super(FilesHandler, self).keyPressEvent(event)
class PluginsStore(QDialog):
    processCompleted = pyqtSignal('QObject*')

    def __init__(self, parent=None):
        super(PluginsStore, self).__init__(parent, Qt.Popup)  #Qt.Tool
        self.setWindowTitle(translations.TR_MANAGE_PLUGINS)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        #self.setWindowState(Qt.WindowActive)
        self.view = QQuickWidget()
        self.view.setMinimumWidth(800)
        self.view.setMinimumHeight(600)
        self.view.setResizeMode(QQuickWidget.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

        # QApplication.instance().focusChanged["QWidget*", "QWidget*"].connect(\
        #     lambda w1, w2, this=self: this.hide() if w1 == this.view else None)

        self.root.loadPluginsGrid.connect(self._load_by_name)
        self.root.close.connect(lambda: print("self.close", self.close()))
        self.root.showPluginDetails[int].connect(self.show_plugin_details)
        self.root.loadTagsGrid.connect(self._load_tags_grid)
        self.root.loadAuthorGrid.connect(self._load_author_grid)
        self.root.search[str].connect(self._load_search_results)
        self.root.loadPluginsForCategory[str].connect(
            self._load_plugins_for_category)
        self.processCompleted.connect(self._process_complete)

        self.nenv = nenvironment.NenvEggSearcher()
        self.nenv.searchCompleted.connect(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:
            plugin.pluginMetadataInflated.connect(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:
            plugin.pluginMetadataInflated.connect(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.processCompleted.emit(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
Exemple #38
0
class AddFileFolderWidget(QDialog):
    """LocatorWidget class with the Logic for the QML UI"""
    def __init__(self, parent=None):
        super(AddFileFolderWidget,
              self).__init__(parent, Qt.Dialog | Qt.FramelessWindowHint)
        self._main_container = parent
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background:transparent;")
        self.setFixedHeight(70)
        self.setFixedWidth(650)
        # Create the QML user interface.
        self.view = QQuickWidget()
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("AddFileFolder.qml"))
        self._root = self.view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        self._base_path = ""

        self._create_file_operation = True

        self._root.create.connect(self._create)

    def create_file(self, base_path, project_path):
        self._create_file_operation = True
        self._base_path = project_path
        base_path = os.path.relpath(base_path, project_path)
        self._root.setDialogType(self._create_file_operation)
        self._root.setBasePath(base_path + os.path.sep)
        self.show()

    def create_folder(self, base_path, project_path):
        self._create_file_operation = False
        self._base_path = project_path
        base_path = os.path.relpath(base_path, project_path)
        self._root.setDialogType(self._create_file_operation)
        self._root.setBasePath(base_path + os.path.sep)
        self.show()

    def showEvent(self, event):
        """Method takes an event to show the Notification"""
        super(AddFileFolderWidget, self).showEvent(event)
        ninjaide = IDE.get_service("ide")
        point = self._main_container.mapToGlobal(self.view.pos())
        x = point.x() + (ninjaide.width() / 2) - (self.width() / 2)
        self.move(x, point.y())
        self.view.setFocus()
        self._root.activateInput()

    def _create(self, path):
        """Open the item received."""
        if self._create_file_operation:
            path = os.path.join(self._base_path, path)
            folder = os.path.split(path)[0]
            if not os.path.exists(folder):
                file_manager.create_folder(folder)
            ninjaide = IDE.getInstance()
            current_nfile = ninjaide.get_or_create_nfile(path)
            current_nfile.create()
            main_container = IDE.get_service('main_container')
            if main_container:
                main_container.open_file(path)
        else:
            path = os.path.join(self._base_path, path)
            if not os.path.exists(path):
                file_manager.create_folder(path)
        self.hide()

    def hideEvent(self, event):
        super(AddFileFolderWidget, self).hideEvent(event)
        self._root.cleanText()
Exemple #39
0
class FilesHandler(QFrame):
#Qt.WindowStaysOnTopHint | 
    def __init__(self, parent=None):#SplashScreen
        super(FilesHandler, self).__init__(None, Qt.SplashScreen)#, Qt.Popup | Qt.FramelessWindowHint
        # self.setAttribute(Qt.WA_TranslucentBackground)
        # self.setStyleSheet("background:transparent;")
        #self.setStyleSheet("background-color: rgb(25, 255, 60);")
        self.setWindowState(Qt.WindowActive)# | Qt.SplashScreen
        self.setAttribute(Qt.WA_AlwaysStackOnTop, False)
        # Create the QML user interface.
        self._main_container = parent.container#IDE.get_service('main_container')
        self.comboParent = parent
        # self.rawObj = raww(self)

        self.view = QQuickWidget()
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.engine().quit.connect(self.hide)
        # self.view.rootContext().setContextProperty("rawObj", self.rawObj)
        self.view.setSource(ui_tools.get_qml_resource("FilesHandler.qml"))
        self._root = self.view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        self._model = {}
        self._temp_files = {}
        self._max_index = 0


        # QApplication.instance().focusChanged["QWidget*", "QWidget*"].connect(\
        #     lambda w1, w2: print("\n\n:focusChanged:", w1, w1.geometry() if w1\
        #     else "_No es un widget",  w2, w2.geometry() if w2 else "_No es un widget"))

        QApplication.instance().focusChanged["QWidget*", "QWidget*"].connect(\
            lambda w1, w2, this=self: this.hide() if w1 == this.view else None)

        self._root.open.connect(self._open)
        self._root.close.connect(self._close)
        self._root.hide.connect(self.hide)
        self._root.fuzzySearch.connect(self._fuzzy_search)
        #QTimer.singleShot(15000, lambda: print("QTimer::", self.show()))

        # self._root.setVisible(True)

    def _open(self, path, temp, project):
        if project:
            path = os.path.join(os.path.split(project)[0], path)
            self._main_container.open_file(path)
        elif temp:
            nfile = self._temp_files[temp]
            ninjaide = IDE.getInstance()
            neditable = ninjaide.get_or_create_editable(nfile=nfile)
            self._main_container.current_widget.set_current(neditable)
        else:
            self._main_container.open_file(path)
            index = self._model[path]
            self._max_index = max(self._max_index, index) + 1
            self._model[path] = self._max_index
        self.hide()

    def _close(self, path, temp):
        if temp:
            nfile = self._temp_files.get(temp, None)
        else:
            ninjaide = IDE.getInstance()
            nfile = ninjaide.get_or_create_nfile(path)
        if nfile is not None:
            nfile.close()

    def _fuzzy_search(self, search):
        search = '.+'.join(re.escape(search).split('\\ '))
        pattern = re.compile(search, re.IGNORECASE)

        model = []
        for project_path in locator.files_paths:
            files_in_project = locator.files_paths[project_path]
            base_project = os.path.basename(project_path)
            for file_path in files_in_project:
                file_path = os.path.join(
                    base_project, os.path.relpath(file_path, project_path))
                if pattern.search(file_path):
                    model.append([os.path.basename(file_path), file_path,
                                  project_path])
        self._root.set_fuzzy_model(model)

    def _add_model(self):
        print("_add_model:_add_model")
        ninjaide = IDE.getInstance()
        files = ninjaide.opened_files
        # print("_add_model::", files, "\n", self._model.keys())
        # Update model
        # old = set(self._model.keys())
        # now = set([nfile.file_path for nfile in files])
        # new = old - now
        # for item in new:
        #     del self._model[item]

        past = set(self._model.keys())
        now = set([nfile.file_path for nfile in files])
        old = past - now
        # print("\n_model:past:", past)
        # print("\n_model:now:", now)
        # print("\n_model:old:", old)
        for item in old:
            del self._model[item]

        current_editor = self._main_container.get_current_editor()
        current_path = None
        if current_editor:
            current_path = current_editor.file_path
        model = []
        # print("len(files)", len(files), [nfile.file_path for nfile in files], "\n\n")
        for nfile in files:
            if (nfile.file_path not in self._model and
                    nfile.file_path is not None):
                self._model[nfile.file_path] = 0
            neditable = ninjaide.get_or_create_editable(nfile=nfile)
            checkers = neditable.sorted_checkers
            checks = []
            for items in checkers:
                checker, color, _ = items
                if checker.dirty:
                    # Colors needs to be reversed for QML
                    color = "#%s" % color[::-1]
                    checks.append(
                        {"checker_text": checker.dirty_text,
                         "checker_color": color})
            modified = neditable.editor.is_modified
            temp_file = str(uuid.uuid4()) if nfile.file_path is None else ""
            filepath = nfile.file_path if nfile.file_path is not None else ""
            model.append([nfile.file_name, filepath, checks, modified,
                          temp_file])
            if temp_file:
                self._temp_files[temp_file] = nfile
        if current_path:
            index = self._model[current_path]
            self._max_index = max(self._max_index, index) + 1
            self._model[current_path] = self._max_index
        model = sorted(model, key=lambda x: self._model.get(x[1], False),
                       reverse=True)
        self._root.set_model(model)

    def showEvent(self, event):
        print("\nshowEvent:::showEvent")
        self._add_model()
        widget = self._main_container.get_current_editor()
        if widget is None:
            widget = self._main_container
        if self._main_container.splitter.count() < 2:
            width = max(widget.width() / 2, 500)
            height = max(widget.height() / 2, 400)
        else:
            width = widget.width()
            height = widget.height()
        self.view.setFixedWidth(width)
        self.view.setFixedHeight(height)

        super(FilesHandler, self).showEvent(event)
        self._root.show_animation()
        point = widget.mapToGlobal(self.view.pos())
        self.move(point.x(), point.y())
        self.view.setFocus()
        self._root.activateInput()
        # QTimer.singleShot(5000, lambda item=self._root.childItems()[0].childItems()[0]:\
        #     print("QTimer::", item, item.hasActiveFocus(), item.scopedFocusItem(),\
        #         item.hasFocus(), item.isFocusScope() ))

    def hideEvent(self, event):
        print("\nhideEvent:::")
        super(FilesHandler, self).hideEvent(event)
        self._temp_files = {}
        self._root.clear_model()

    def next_item(self):
        print("next_item()", self)
        if not self.isVisible():
            self.show()
        self._root.next_item()

    def previous_item(self):
        print("previous_item()", self)
        if not self.isVisible():
            self.show()
        self._root.previous_item()

    def keyPressEvent(self, event):
        print("keyPressEvent()", event.key(), event.key() == Qt.Key_Escape)
        if event.key() == Qt.Key_Escape:
            self.hide()
        elif (event.modifiers() == Qt.ControlModifier and
                event.key() == Qt.Key_PageDown) or event.key() == Qt.Key_Down:
            self._root.next_item()
        elif (event.modifiers() == Qt.ControlModifier and
                event.key() == Qt.Key_PageUp) or event.key() == Qt.Key_Up:
            self._root.previous_item()
        elif event.key() in (Qt.Key_Return, Qt.Key_Enter):
            self._root.open_item()
        # elif event.key() == Qt.Key_Asterisk):
        #     print("keyPressEvent()", self,self.isVisible())
        super(FilesHandler, self).keyPressEvent(event)

    def mousePressEvent(self, event):
        if QApplication.instance().widgetAt( self.mapToGlobal(event.pos()) ) == self.comboParent:
            event.ignore()
            self.comboParent.hidePopup()
            return
        super(FilesHandler, self).mousePressEvent(event)


    def hideEvent(self, event):
        print("hideEvent()", event)
        super(FilesHandler, self).hideEvent(event)
class LocatorWidget(QDialog):
    """LocatorWidget class with the Logic for the QML UI"""

    def __init__(self, parent=None):
        super(LocatorWidget, self).__init__(
            parent, Qt.SplashScreen)# | Qt.FramelessWindowHint)
        self._parent = parent
        # self.setModal(True)
        # self.setAttribute(Qt.WA_TranslucentBackground)
        # self.setStyleSheet("background:transparent;")
        self.setWindowState(Qt.WindowActive)
        self.setFixedHeight(400)
        self.setFixedWidth(500)
        # Create the QML user interface.
        self.view = QQuickWidget()
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.engine().quit.connect(self.hide)
        self.view.setSource(ui_tools.get_qml_resource("Locator.qml"))
        self._root = self.view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        self.locate_symbols = locator.LocateSymbolsThread()
        self.locate_symbols.finished.connect(self._cleanup)
        self.locate_symbols.terminated.connect(self._cleanup)

        QApplication.instance().focusChanged["QWidget*", "QWidget*"].connect(\
            lambda old, now, this=self: this.hide() if old == this.view else None)

        # Locator things
        self.filterPrefix = re.compile(r'(@|<|>|-|!|\.|/|:)')
        self.page_items_step = 10
        self._colors = {
            "@": "white",
            "<": "#18ff6a",
            ">": "red",
            "-": "#18e1ff",
            ".": "#f118ff",
            "/": "#fff118",
            ":": "#18ffd6",
            "!": "#ffa018"}
        self._filters_list = [
            ("@", "Filename"),
            ("<", "Class"),
            (">", "Function"),
            ("-", "Attribute"),
            (".", "Current"),
            ("/", "Opened"),
            (":", "Line"),
            ("!", "NoPython")
        ]
        self._replace_symbol_type = {"<": "&lt;", ">": "&gt;"}
        self.reset_values()

        self._filter_actions = {
            '.': self._filter_this_file,
            '/': self._filter_tabs,
            ':': self._filter_lines
        }

        self._root.textChanged.connect(self.set_prefix)
        self._root.open.connect(self._open_item)
        self._root.fetchMore.connect(self._fetch_more)

    # @pyqtSlot(result=tuple)
    def currentItem(self):
        item = self._root.currentItem()
        return item.toVariant()\
            if item else None

    def reset_values(self):
        self._avoid_refresh = False
        self.__prefix = ''
        self.__pre_filters = []
        self.__pre_results = []
        self.tempLocations = []
        self.items_in_page = 0
        self._line_jump = -1

    def showEvent(self, event):
        """Method takes an event to show the Notification"""
        super(LocatorWidget, self).showEvent(event)
        pgeo = self._parent.geometry()
        x = pgeo.left() + (self._parent.width() / 2) - (self.width() / 2)
        y = pgeo.top()
        #y = self._parent.y() + self._main_container.combo_header_size
        self.setGeometry(x, y, self.width(), self.height())
        self._root.activateInput()
        self._refresh_filter()

    def _cleanup(self):
        self.locate_symbols.wait()

    def explore_code(self):
        self.locate_symbols.find_code_location()

    def explore_file_code(self, path):
        self.locate_symbols.find_file_code_location(path)

    def set_prefix(self, prefix):
        """Set the prefix for the completer."""
        self.__prefix = prefix.lower()
        if not self._avoid_refresh:
            self._refresh_filter()

    def _refresh_filter(self):
        items = self.filter()
        self._root.clear()
        self._load_items(items)
        filter_composite = ""
        for symbol, text in self._filters_list:
            typeIcon = self._replace_symbol_type.get(symbol, symbol)
            if symbol in self.__prefix:
                composite = "<font color='{0}'>{1}{2}</font> ".format(
                    self._colors.get(symbol, "#8f8f8f"), typeIcon, text)
                filter_composite += composite
            else:
                composite = "<font color='#8f8f8f'>{0}{1}</font> ".format(
                    typeIcon, text)
                filter_composite += composite
        self._root.setFilterComposite(filter_composite)

    def _load_items(self, items):
        for item in items:
            typeIcon = self._replace_symbol_type.get(item.type, item.type)
            self._root.loadItem(typeIcon, item.name, item.lineno,
                                item.path, self._colors[item.type])

    def _fetch_more(self):
        locations = self._create_list_items(self.tempLocations)
        self._load_items(locations)

    def _create_list_items(self, locations):
        """Create a list of items (using pages for results to speed up)."""
        #The list is regenerated when the locate metadata is updated
        #for example: open project, etc.
        #Create the list items
        begin = self.items_in_page
        self.items_in_page += self.page_items_step
        locations_view = [x for x in locations[begin:self.items_in_page]]
        return locations_view

    def filter(self):
        self._line_jump = -1
        self.items_in_page = 0

        filterOptions = self.filterPrefix.split(self.__prefix.lstrip())
        if filterOptions[0] == '':
            del filterOptions[0]

        if len(filterOptions) == 0:
            self.tempLocations = self.locate_symbols.get_locations()
        elif len(filterOptions) == 1:
            self.tempLocations = [
                x for x in self.locate_symbols.get_locations()
                if x.comparison.lower().find(filterOptions[0].lower()) > -1]
        else:
            index = 0
            if not self.tempLocations and (self.__pre_filters == filterOptions):
                self.tempLocations = self.__pre_results
                return self._create_list_items(self.tempLocations)
            while index < len(filterOptions):
                filter_action = self._filter_actions.get(
                    filterOptions[index], self._filter_generic)
                if filter_action is None:
                    break
                index = filter_action(filterOptions, index)
            if self.tempLocations:
                self.__pre_filters = filterOptions
                self.__pre_results = self.tempLocations
        return self._create_list_items(self.tempLocations)

    def _filter_generic(self, filterOptions, index):
        at_start = (index == 0)
        if at_start:
            self.tempLocations = [
                x for x in self.locate_symbols.get_locations()
                if x.type == filterOptions[0] and
                x.comparison.lower().find(filterOptions[1].lower()) > -1]
        else:
            currentItem = self.currentItem()
            if (filterOptions[index - 2] == locator.FILTERS['classes'] and
                    currentItem):
                symbols = self.locate_symbols.get_symbols_for_class(
                    currentItem[2], currentItem[1])
                self.tempLocations = symbols
            elif currentItem:
                global mapping_symbols
                self.tempLocations = locator.mapping_symbols.get(
                    currentItem[2], [])
            self.tempLocations = [x for x in self.tempLocations
                                  if x.type == filterOptions[index] and
                                  x.comparison.lower().find(
                                      filterOptions[index + 1].lower()) > -1]
        return index + 2

    def _filter_this_file(self, filterOptions, index):
        at_start = (index == 0)
        if at_start:
            main_container = IDE.get_service('main_container')
            editorWidget = None
            if main_container:
                editorWidget = main_container.get_current_editor()
            index += 2
            if editorWidget:
                exts = settings.SYNTAX.get('python')['extension']
                file_ext = file_manager.get_file_extension(
                    editorWidget.file_path)
                if file_ext in exts:
                    filterOptions.insert(0, locator.FILTERS['files'])
                else:
                    filterOptions.insert(0, locator.FILTERS['non-python'])
                filterOptions.insert(1, editorWidget.file_path)
                self.tempLocations = \
                    self.locate_symbols.get_this_file_symbols(
                        editorWidget.file_path)
                search = filterOptions[index + 1].lstrip().lower()
                self.tempLocations = [x for x in self.tempLocations
                                      if x.comparison.lower().find(search) > -1]
        else:
            del filterOptions[index + 1]
            del filterOptions[index]
        return index

    def _filter_tabs(self, filterOptions, index):
        at_start = (index == 0)
        if at_start:
            ninjaide = IDE.getInstance()
            opened = ninjaide.filesystem.get_files()
            self.tempLocations = [
                locator.ResultItem(
                    locator.FILTERS['files'],
                    opened[f].file_name, opened[f].file_path) for f in opened]
            search = filterOptions[index + 1].lstrip().lower()
            self.tempLocations = [
                x for x in self.tempLocations
                if x.comparison.lower().find(search) > -1]
            index += 2
        else:
            del filterOptions[index + 1]
            del filterOptions[index]
        return index

    def _filter_lines(self, filterOptions, index):
        at_start = (index == 0)
        if at_start:
            main_container = IDE.get_service('main_container')
            editorWidget = None
            if main_container:
                editorWidget = main_container.get_current_editor()
            index = 2
            if editorWidget:
                exts = settings.SYNTAX.get('python')['extension']
                file_ext = file_manager.get_file_extension(
                    editorWidget.file_path)
                if file_ext in exts:
                    filterOptions.insert(0, locator.FILTERS['files'])
                else:
                    filterOptions.insert(0, locator.FILTERS['non-python'])
                filterOptions.insert(1, editorWidget.file_path)
            self.tempLocations = [
                x for x in self.locate_symbols.get_locations()
                if x.type == filterOptions[0] and
                x.path == filterOptions[1]]
        else:
            currentItem = self.currentItem()
            if currentItem:
                self.tempLocations = [
                    x for x in self.locate_symbols.get_locations()
                    if x.type == currentItem[0] and
                    x.path == currentItem[2]]
        if filterOptions[index + 1].isdigit():
            self._line_jump = int(filterOptions[index + 1]) - 1
        return index + 2

    def _open_item(self, path, lineno):
        """Open the item received."""
        main_container = IDE.get_service('main_container')
        if not main_container:
            return
        jump = lineno if self._line_jump == -1 else self._line_jump
        main_container.open_file(path, jump)
        self.hide()

    def hideEvent(self, event):
        super(LocatorWidget, self).hideEvent(event)
        # clean
        self._avoid_refresh = True
        self._root.cleanText()
        self._root.clear()
        self.reset_values()
Exemple #41
0
class StartPage(QWidget, itab_item.ITabItem):
    openPreferences = pyqtSignal()
    openProject = pyqtSignal(str)
    def __init__(self, parent=None):
        super(StartPage, self).__init__(parent)
        self._id = "Start Page"
        vbox = QVBoxLayout(self)
        self.view = QQuickWidget()
        self.view.setMinimumWidth(400)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        path_qml = QDir.fromNativeSeparators(
            os.path.join(resources.QML_FILES, "StartPage.qml"))
        path_qml = urlunparse(urlparse(path_qml)._replace(scheme='file'))
        self.view.setSource(QUrl(path_qml))
        #self.view.show()
        self.root = self.view.rootObject()
        self.view.setMinimumSize(630, 400)
        vbox.addWidget(self.view)

        self.load_items()

        # self.root.openProject[str].connect(self._open_project)
        # self.root.removeProject[str].connect(self._on_click_on_delete)
        # self.root.markAsFavorite[str, bool].connect(self._on_click_on_favorite)
        # self.root.openPreferences.connect(self.openPreferences.emit)

        self.root.openProject.connect(self._open_project)
        self.root.removeProject.connect(self._on_click_on_delete)
        self.root.markAsFavorite.connect(self._on_click_on_favorite)
        self.root.openPreferences.connect(self.openPreferences.emit)

    def _open_project(self, path):
        self.openProject.emit(path)

    def _on_click_on_delete(self, path):
        settings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat)
        recent_projects = settings.value("recentProjects")
        if path in recent_projects:
            del recent_projects[path]
            settings.setValue("recentProjects", recent_projects)

    def _on_click_on_favorite(self, path, value):
        settings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat)
        recent_projects = settings.value("recentProjects")
        properties = recent_projects[path]
        properties["isFavorite"] = value
        recent_projects[path] = properties
        settings.setValue("recentProjects", recent_projects)

    def load_items(self):
        settings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat)
        listByFavorites = []
        listNoneFavorites = []
        recent_projects_dict = dict(settings.value('recentProjects', {}))
        #Filter for favorites
        for recent_project_path, content in list(recent_projects_dict.items()):
            if bool(dict(content)["isFavorite"]):
                listByFavorites.append((recent_project_path,
                    content["lastopen"]))
            else:
                listNoneFavorites.append((recent_project_path,
                    content["lastopen"]))
        if len(listByFavorites) > 1:
            # sort by date favorites
            listByFavorites = sorted(listByFavorites,
                key=lambda date: listByFavorites[1])

        if len(listNoneFavorites) > 1:
            #sort by date last used
            listNoneFavorites = sorted(listNoneFavorites,
                key=lambda date: listNoneFavorites[1])

        for recent_project_path in listByFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, True)

        for recent_project_path in listNoneFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, False)
class PluginsStore(QDialog):
    processCompleted = pyqtSignal('QObject*')
    def __init__(self, parent=None):
        super(PluginsStore, self).__init__(parent, Qt.Popup)#Qt.Tool
        self.setWindowTitle(translations.TR_MANAGE_PLUGINS)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        #self.setWindowState(Qt.WindowActive)
        self.view = QQuickWidget()
        self.view.setMinimumWidth(800)
        self.view.setMinimumHeight(600)
        self.view.setResizeMode(QQuickWidget.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

        # QApplication.instance().focusChanged["QWidget*", "QWidget*"].connect(\
        #     lambda w1, w2, this=self: this.hide() if w1 == this.view else None)

        self.root.loadPluginsGrid.connect(self._load_by_name)
        self.root.close.connect(lambda: print("self.close", self.close()))
        self.root.showPluginDetails[int].connect(self.show_plugin_details)
        self.root.loadTagsGrid.connect(self._load_tags_grid)
        self.root.loadAuthorGrid.connect(self._load_author_grid)
        self.root.search[str].connect(self._load_search_results)
        self.root.loadPluginsForCategory[str].connect(self._load_plugins_for_category)
        self.processCompleted.connect(self._process_complete)

        self.nenv = nenvironment.NenvEggSearcher()
        self.nenv.searchCompleted.connect(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:
            plugin.pluginMetadataInflated.connect(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:
            plugin.pluginMetadataInflated.connect(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.processCompleted.emit(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
Exemple #43
0
class StartPage(QWidget):
    # Signals
    openPreferences = pyqtSignal()
    newFile = pyqtSignal()

    def __init__(self, parent=None):
        super(StartPage, self).__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self.view = QQuickWidget()
        self.view.rootContext().setContextProperty("theme",
                                                   resources.QML_COLORS)
        self.view.rootContext().setContextProperty("shortcuts",
                                                   self.get_shortcuts())
        self.view.setMinimumWidth(400)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("StartPage.qml"))
        self.root = self.view.rootObject()
        vbox.addWidget(self.view)

        # Connections
        self.root.onDrop.connect(self.__open_drop_files)
        self.root.openProject.connect(self._open_project)
        self.root.newFile.connect(lambda: self.newFile.emit())
        self.load_items()

    @pyqtSlot('QString')
    def _open_project(self, path):
        projects_explorer = IDE.get_service("projects_explorer")
        projects_explorer.open_project_folder(path)

    def get_shortcuts(self):
        shortcuts = {k: v.toString() for k, v in resources.SHORTCUTS.items()}
        return shortcuts

    def load_items(self):
        # dsettings = IDE.data_settings()
        # recent_projects_dict = dict(dsettings.value('recentProjects', {}))
        # for prj, values in recent_projects_dict.items():
        #    prj_name = values["name"]
        #    last_open = values["lastopen"]
        #    self.root.addProject(prj_name, prj, last_open)
        self.root.forceActiveFocus()
        """
        # Connections
        self.root.openProject['QString'].connect(self._open_project)
        self.root.removeProject['QString'].connect(self._on_click_on_delete)
        self.root.markAsFavorite['QString',
                                 bool].connect(self._on_click_on_favorite)
        self.root.openPreferences.connect(
            lambda: self.openPreferences.emit())
        self.root.newFile.connect(lambda: self.newFile.emit())

    def _open_project(self, path):
        projects_explorer = IDE.get_service('projects_explorer')
        if projects_explorer:
            projects_explorer.open_project_folder(path)

    def _on_click_on_delete(self, path):
        settings = IDE.data_settings()
        recent_projects = settings.value("recentProjects")
        if path in recent_projects:
            del recent_projects[path]
            settings.setValue("recentProjects", recent_projects)

    def _on_click_on_favorite(self, path, value):
        settings = IDE.data_settings()
        recent_projects = settings.value("recentProjects")
        properties = recent_projects[path]
        properties["isFavorite"] = value
        recent_projects[path] = properties
        settings.setValue("recentProjects", recent_projects)

    def load_items(self):
        settings = IDE.data_settings()
        listByFavorites = []
        listNoneFavorites = []
        recent_projects_dict = dict(settings.value('recentProjects', {}))
        # Filter for favorites
        for recent_project_path, content in list(recent_projects_dict.items()):
            if bool(dict(content)["isFavorite"]):
                listByFavorites.append((recent_project_path,
                                        content["lastopen"]))
            else:
                listNoneFavorites.append((recent_project_path,
                                          content["lastopen"]))
        if len(listByFavorites) > 1:
            # sort by date favorites
            listByFavorites = sorted(listByFavorites,
                                     key=lambda date: listByFavorites[1])

        if len(listNoneFavorites) > 1:
            # sort by date last used
            listNoneFavorites = sorted(listNoneFavorites,
                                       key=lambda date: listNoneFavorites[1])

        for recent_project_path in listByFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, True)

        for recent_project_path in listNoneFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, False)
        self.root.forceActiveFocus()
    """

    def __open_drop_files(self, files: str):
        """Open dragged files to Start Page"""
        files = files.split(',')  # FIXME: it's ok?
        main_container = IDE.get_service("main_container")
        for f in files:
            main_container.open_file(QUrl(f).toLocalFile())
class StartPage(QWidget):
    openPreferences = pyqtSignal()
    newFile = pyqtSignal(str)
    openProject = pyqtSignal(str)
    openFiles = pyqtSignal(list)
    def __init__(self, parent=None):
        super(StartPage, self).__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self.view = QQuickWidget()
        self.view.setMinimumWidth(400)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("StartPage.qml"))
        self.root = self.view.rootObject()
        vbox.addWidget(self.view)

        self.load_items()

        self.root.openProject.connect(self._open_project)
        self.root.removeProject.connect(self._on_click_on_delete)
        self.root.markAsFavorite.connect(self._on_click_on_favorite)
        self.root.openPreferences.connect(self.openPreferences.emit)
        self.root.newFile.connect(lambda: self.newFile.emit(translations.TR_NEW_DOCUMENT))#self.test)
        self.root.openFiles.connect(self.checkFiles)

        self.root.set_year(str(datetime.datetime.now().year))

    def test(self, c= "-.-"):
        print(c)
        self.newFile.emit(c)

    def checkFiles(self, lst):
        f = QFileInfo()
        newLst = []
        for url in lst:
            _file = url.toLocalFile()
            print("FILE::", url, _file)
            f.setFile(_file)
            if f.suffix() not in ("tar", "exe", "mp3", "mp4", "flv", "zip", "rar", "iso"):
                newLst.append(_file)

        if newLst:
            self.openFiles.emit(newLst)



    def _open_project(self, path):
        projects_explorer = IDE.get_service('projects_explorer')
        if projects_explorer:
            projects_explorer.open_project_folder(path)

    def _on_click_on_delete(self, path):
        settings = IDE.data_settings()
        recent_projects = settings.value("recentProjects")
        if path in recent_projects:
            del recent_projects[path]
            settings.setValue("recentProjects", recent_projects)

    def _on_click_on_favorite(self, path, value):
        settings = IDE.data_settings()
        recent_projects = settings.value("recentProjects")
        properties = recent_projects[path]
        properties["isFavorite"] = value
        recent_projects[path] = properties
        settings.setValue("recentProjects", recent_projects)

    def load_items(self):
        settings = IDE.data_settings()
        listByFavorites = []
        listNoneFavorites = []
        recent_projects_dict = dict(settings.value('recentProjects', {}))
        #Filter for favorites
        for recent_project_path, content in list(recent_projects_dict.items()):
            if bool(dict(content)["isFavorite"]):
                listByFavorites.append((recent_project_path,
                    content["lastopen"]))
            else:
                listNoneFavorites.append((recent_project_path,
                    content["lastopen"]))
        if len(listByFavorites) > 1:
            # sort by date favorites
            listByFavorites = sorted(listByFavorites,
                key=lambda date: listByFavorites[1])

        if len(listNoneFavorites) > 1:
            #sort by date last used
            listNoneFavorites = sorted(listNoneFavorites,
                key=lambda date: listNoneFavorites[1])

        for recent_project_path in listByFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, True)

        for recent_project_path in listNoneFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, False)
        self.root.forceActiveFocus()
Exemple #45
0
class StartPage(QWidget):
    # Signals
    openPreferences = pyqtSignal()
    newFile = pyqtSignal()

    def __init__(self, parent=None):
        super(StartPage, self).__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self.view = QQuickWidget()
        self.view.rootContext().setContextProperty(
            "theme", resources.QML_COLORS)
        self.view.rootContext().setContextProperty(
            "shortcuts", self.get_shortcuts())
        self.view.setMinimumWidth(400)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("StartPage.qml"))
        self.root = self.view.rootObject()
        vbox.addWidget(self.view)

        # Connections
        self.root.onDrop.connect(self.__open_drop_files)
        self.root.openProject.connect(self._open_project)
        self.root.newFile.connect(lambda: self.newFile.emit())
        self.load_items()

    @pyqtSlot('QString')
    def _open_project(self, path):
        projects_explorer = IDE.get_service("projects_explorer")
        projects_explorer.open_project_folder(path)

    def get_shortcuts(self):
        shortcuts = {k: v.toString() for k, v in resources.SHORTCUTS.items()}
        return shortcuts

    def load_items(self):
        # dsettings = IDE.data_settings()
        # recent_projects_dict = dict(dsettings.value('recentProjects', {}))
        # for prj, values in recent_projects_dict.items():
        #    prj_name = values["name"]
        #    last_open = values["lastopen"]
        #    self.root.addProject(prj_name, prj, last_open)
        self.root.forceActiveFocus()
        """
        # Connections
        self.root.openProject['QString'].connect(self._open_project)
        self.root.removeProject['QString'].connect(self._on_click_on_delete)
        self.root.markAsFavorite['QString',
                                 bool].connect(self._on_click_on_favorite)
        self.root.openPreferences.connect(
            lambda: self.openPreferences.emit())
        self.root.newFile.connect(lambda: self.newFile.emit())

    def _open_project(self, path):
        projects_explorer = IDE.get_service('projects_explorer')
        if projects_explorer:
            projects_explorer.open_project_folder(path)

    def _on_click_on_delete(self, path):
        settings = IDE.data_settings()
        recent_projects = settings.value("recentProjects")
        if path in recent_projects:
            del recent_projects[path]
            settings.setValue("recentProjects", recent_projects)

    def _on_click_on_favorite(self, path, value):
        settings = IDE.data_settings()
        recent_projects = settings.value("recentProjects")
        properties = recent_projects[path]
        properties["isFavorite"] = value
        recent_projects[path] = properties
        settings.setValue("recentProjects", recent_projects)

    def load_items(self):
        settings = IDE.data_settings()
        listByFavorites = []
        listNoneFavorites = []
        recent_projects_dict = dict(settings.value('recentProjects', {}))
        # Filter for favorites
        for recent_project_path, content in list(recent_projects_dict.items()):
            if bool(dict(content)["isFavorite"]):
                listByFavorites.append((recent_project_path,
                                        content["lastopen"]))
            else:
                listNoneFavorites.append((recent_project_path,
                                          content["lastopen"]))
        if len(listByFavorites) > 1:
            # sort by date favorites
            listByFavorites = sorted(listByFavorites,
                                     key=lambda date: listByFavorites[1])

        if len(listNoneFavorites) > 1:
            # sort by date last used
            listNoneFavorites = sorted(listNoneFavorites,
                                       key=lambda date: listNoneFavorites[1])

        for recent_project_path in listByFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, True)

        for recent_project_path in listNoneFavorites:
            path = recent_project_path[0]
            name = recent_projects_dict[path]['name']
            self.root.add_project(name, path, False)
        self.root.forceActiveFocus()
    """

    def __open_drop_files(self, files: str):

        """Open dragged files to Start Page"""
        files = files.split(',')  # FIXME: it's ok?
        main_container = IDE.get_service("main_container")
        for f in files:
            main_container.open_file(QUrl(f).toLocalFile())
Exemple #46
0
import sys

from PyQt5.QtCore import QUrl, QMetaObject, Q_ARG, QVariant, QTimer, \
    QDate
from PyQt5.QtQuickWidgets import QQuickWidget
from PyQt5.QtWidgets import QApplication

counter = 0


def onTimeout(obj):
    global counter
    value = {
        "lesson": str(counter),
        "subject": "PE",
        "day": QDate.longDayName(1 + counter % 7)
    }
    QMetaObject.invokeMethod(obj, "append", Q_ARG(QVariant, value))
    counter += 1


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QQuickWidget()
    w.setSource(QUrl('main.qml'))
    timer = QTimer()
    timer.timeout.connect(lambda: onTimeout(w.rootObject()))
    timer.start(1000)
    w.show()
    sys.exit(app.exec_())
Exemple #47
0
class Scene(QGraphicsScene):
    RIGHT_SIDEBAR_VIEW_PATH = "design.qml"

    def __init__(self):
        QGraphicsScene.__init__(self)
        self._define_ui()
        self._connect_ui()

        self.color = "#000000"
        self.pen = QPen(QColor(self.color), 4)

        self.originPos = None
        self.currentPos = None

        self.default = "Default"
        self.mode = self.default
        self.die = False

    def _define_ui(self):
        self.quick = QQuickWidget()
        self.quick.setSource(QUrl().fromLocalFile(Scene.RIGHT_SIDEBAR_VIEW_PATH))
        self.quick.setResizeMode(QQuickWidget.SizeRootObjectToView)

        self._rootObject = self.quick.rootObject()

    def _connect_ui(self):
        self._rootObject.changeColor.connect(self._changeColor)
        self._rootObject.setMode.connect(self._setMode)
        self._rootObject.clearAll.connect(self._clearAll)

    @pyqtSlot(str)
    def _changeColor(self, color):
        self.color = color
        self.pen = QPen(QColor(self.color), 4)


    @pyqtSlot(str)
    def _setMode(self, mode):
        self.mode = mode

    @pyqtSlot()
    def _clearAll(self):
        if self:
            for item in self.items():
                self.removeItem(item)
                self.die = False
                self.update()

    def clearLastItem(self):
        self.removeItem(self.items()[len(self.items()) - 1])
        self.update()

    def mousePressEvent(self, event):
        self.originPos = event.scenePos()

    def mouseMoveEvent(self, event):
        self.currentPos = event.scenePos()

        if self.die:
            print("Rest in Peace")
        else:
            if self.mode == "Segment":
                self.drawSegment()
            if self.mode == "Rectangle":
                self.drawRect()
            if self.mode == "Forever":
                self.drawForever()

    def mouseReleaseEvent(self, event):
        self.die = True

    def drawRect(self):
        rect = QRectF(self.originPos, self.currentPos)
        rect_item = QGraphicsRectItem(rect)
        rect_item.setPen(self.pen)
        rect_item.setFlag(QGraphicsItem.ItemIsMovable, True)
        if len(self.items()) > 0:
            self.clearLastItem()
        self.addItem(rect_item)

    def drawSegment(self):
        line = QLineF(self.originPos, self.currentPos)
        line_item = QGraphicsLineItem(line)
        line_item.setPen(self.pen)
        line_item.setFlag(QGraphicsItem.ItemIsMovable, True)
        if len(self.items()) > 0:
            self.clearLastItem()
        self.addItem(line_item)

    def drawForever(self):
        line = QLineF(self.originPos, self.currentPos)
        line_item = QGraphicsLineItem(line)
        line_item.setPen(self.pen)
        line_item.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.addItem(line_item)
        self.originPos = self.currentPos
Exemple #48
0
class FilesHandler(QWidget):

    def __init__(self, parent=None):
        super(FilesHandler, self).__init__(
            None, Qt.FramelessWindowHint | Qt.Popup)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self._main_container = parent
        # Create the QML user interface.
        self.setFixedHeight(300)
        self.setFixedWidth(400)
        self.view = QQuickWidget()
        self.view.rootContext().setContextProperty(
            "theme", resources.QML_COLORS)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("FilesHandler.qml"))
        self._root = self.view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        self._model = {}
        self._temp_files = {}
        self._max_index = 0

        self._root.open.connect(self._open)
        self._root.close.connect(self._close)
        self._root.fuzzySearch.connect(self._fuzzy_search)
        self._root.hide.connect(self.hide)

    def _open(self, path, temp, project):
        if project:
            path = os.path.join(os.path.split(project)[0], path)
            self._main_container.open_file(path)
        elif temp:
            nfile = self._temp_files[temp]
            ninjaide = IDE.get_service("ide")
            neditable = ninjaide.get_or_create_editable(nfile=nfile)
            self._main_container.combo_area.set_current(neditable)
        else:
            self._main_container.open_file(path)
            index = self._model[path]
            self._max_index = max(self._max_index, index) + 1
            self._model[path] = self._max_index
        self.hide()

    def _close(self, path, temp):
        # FIXME: when we have splitters?
        if temp:
            nfile = self._temp_files.get(temp, None)
        else:
            ninjaide = IDE.get_service("ide")
            nfile = ninjaide.get_or_create_nfile(path)
        if nfile is not None:
            nfile.close()

    def _fuzzy_search(self, search):
        search = '.+'.join(re.escape(search).split('\\ '))
        pattern = re.compile(search, re.IGNORECASE)

        model = []
        for project_path in locator.files_paths:
            files_in_project = locator.files_paths[project_path]
            base_project = os.path.basename(project_path)
            for file_path in files_in_project:
                file_path = os.path.join(
                    base_project, os.path.relpath(file_path, project_path))
                if pattern.search(file_path):
                    model.append([os.path.basename(file_path), file_path,
                                  project_path])
        self._root.set_fuzzy_model(model)

    def _add_model(self):
        ninjaide = IDE.get_service("ide")
        files = ninjaide.opened_files
        # Update model
        current_editor = self._main_container.get_current_editor()
        current_path = None
        if current_editor is not None:
            current_path = current_editor.file_path
        model = []
        for nfile in files:
            if nfile.file_path is not None and \
                    nfile.file_path not in self._model:
                self._model[nfile.file_path] = 0
            neditable = ninjaide.get_or_create_editable(nfile=nfile)
            checkers = neditable.sorted_checkers
            checks = []
            for item in checkers:
                checker, color, _ = item
                if checker.dirty:
                    checks.append({
                        "checker_text": checker.dirty_text,
                        "checker_color": color
                    })
            modified = neditable.editor.is_modified
            temp_file = str(uuid.uuid4()) if nfile.file_path is None else ""
            filepath = nfile.file_path if nfile.file_path is not None else ""
            model.append([
                nfile.file_name, filepath,
                checks, modified, temp_file])
            if temp_file:
                self._temp_files[temp_file] = nfile
        if current_path is not None:
            index = self._model[current_path]
            self._max_index = max(self._max_index, index) + 1
            self._model[current_path] = self._max_index
        model = sorted(model, key=lambda x: self._model.get(x[1], False),
                       reverse=True)
        self._root.set_model(model)

    def showEvent(self, event):
        self._add_model()
        editor_widget = self._main_container.get_current_editor()
        simple = False
        if editor_widget.height() < 400 or editor_widget.width() < 350:
            width = editor_widget.width()
            height = self._main_container.height() / 3
            simple = True
        else:
            width = max(editor_widget.width() / 3, 550)
            height = max(editor_widget.height() / 2, 400)

        self.setFixedWidth(width)
        self.setFixedHeight(height)

        self._root.setMode(simple)
        super(FilesHandler, self).showEvent(event)
        point = editor_widget.mapToGlobal(self.view.pos())
        self.move(point)
        # Trick
        QTimer.singleShot(100, self.__set_focus)

    def __set_focus(self):
        self.view.setFocus()
        self._root.activateInput()

    def hideEvent(self, event):
        super(FilesHandler, self).hideEvent(event)
        self._temp_files = {}
        self._root.clear_model()
        # Recovery focus
        editor_widget = self._main_container.get_current_editor()
        if editor_widget is not None:
            editor_widget.setFocus()

    def next_item(self):
        if not self.isVisible():
            self.show()

    def previous_item(self):
        if not self.isVisible():
            self.show()
        self._root.previous_item()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.hide()
        elif (event.modifiers() == Qt.ControlModifier and
                event.key() == Qt.Key_Tab):
            self._root.next_item()
        elif (event.modifiers() == Qt.ControlModifier and
                event.key() == Qt.Key_PageDown) or event.key() == Qt.Key_Down:
            self._root.next_item()
        elif (event.modifiers() == Qt.ControlModifier and
                event.key() == Qt.Key_PageUp) or event.key() == Qt.Key_Up:
            self._root.previous_item()
        elif event.key() in (Qt.Key_Return, Qt.Key_Enter):
            self._root.open_item()
        super(FilesHandler, self).keyPressEvent(event)
class LocatorWidget(QDialog):
    """LocatorWidget class with the Logic for the QML UI"""

    def __init__(self, parent=None):
        super(LocatorWidget, self).__init__(
            parent, Qt.SplashScreen)# | Qt.FramelessWindowHint)
        self._parent = parent
        # self.setModal(True)
        # self.setAttribute(Qt.WA_TranslucentBackground)
        # self.setStyleSheet("background:transparent;")
        self.setWindowState(Qt.WindowActive)
        self.setFixedHeight(400)
        self.setFixedWidth(500)
        # Create the QML user interface.
        self.view = QQuickWidget()
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.engine().quit.connect(self.hide)
        self.view.setSource(ui_tools.get_qml_resource("Locator.qml"))
        self._root = self.view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        self.locate_symbols = locator.LocateSymbolsThread()
        self.locate_symbols.finished.connect(self._cleanup)
        self.locate_symbols.terminated.connect(self._cleanup)

        QApplication.instance().focusChanged["QWidget*", "QWidget*"].connect(\
            lambda w1, w2, this=self: this.hide() if w1 == this.view else None)

        # Locator things
        self.filterPrefix = re.compile(r'(@|<|>|-|!|\.|/|:)')
        self.page_items_step = 10
        self._colors = {
            "@": "white",
            "<": "#18ff6a",
            ">": "red",
            "-": "#18e1ff",
            ".": "#f118ff",
            "/": "#fff118",
            ":": "#18ffd6",
            "!": "#ffa018"}
        self._filters_list = [
            ("@", "Filename"),
            ("<", "Class"),
            (">", "Function"),
            ("-", "Attribute"),
            (".", "Current"),
            ("/", "Opened"),
            (":", "Line"),
            ("!", "NoPython")
        ]
        self._replace_symbol_type = {"<": "&lt;", ">": "&gt;"}
        self.reset_values()

        self._filter_actions = {
            '.': self._filter_this_file,
            '/': self._filter_tabs,
            ':': self._filter_lines
        }

        self._root.textChanged.connect(self.set_prefix)
        self._root.open.connect(self._open_item)
        self._root.fetchMore.connect(self._fetch_more)

    # @pyqtSlot(result=tuple)
    def currentItem(self):
        item = self._root.currentItem()
        return item.toVariant()\
            if item else None

    def reset_values(self):
        self._avoid_refresh = False
        self.__prefix = ''
        self.__pre_filters = []
        self.__pre_results = []
        self.tempLocations = []
        self.items_in_page = 0
        self._line_jump = -1

    def showEvent(self, event):
        """Method takes an event to show the Notification"""
        super(LocatorWidget, self).showEvent(event)
        pgeo = self._parent.geometry()
        x = pgeo.left() + (self._parent.width() / 2) - (self.width() / 2)
        y = pgeo.top()
        #y = self._parent.y() + self._main_container.combo_header_size
        self.setGeometry(x, y, self.width(), self.height())
        self._root.activateInput()
        self._refresh_filter()

    def _cleanup(self):
        self.locate_symbols.wait()

    def explore_code(self):
        self.locate_symbols.find_code_location()

    def explore_file_code(self, path):
        self.locate_symbols.find_file_code_location(path)

    def set_prefix(self, prefix):
        """Set the prefix for the completer."""
        self.__prefix = prefix.lower()
        if not self._avoid_refresh:
            self._refresh_filter()

    def _refresh_filter(self):
        items = self.filter()
        self._root.clear()
        self._load_items(items)
        filter_composite = ""
        for symbol, text in self._filters_list:
            typeIcon = self._replace_symbol_type.get(symbol, symbol)
            if symbol in self.__prefix:
                composite = "<font color='{0}'>{1}{2}</font> ".format(
                    self._colors.get(symbol, "#8f8f8f"), typeIcon, text)
                filter_composite += composite
            else:
                composite = "<font color='#8f8f8f'>{0}{1}</font> ".format(
                    typeIcon, text)
                filter_composite += composite
        self._root.setFilterComposite(filter_composite)

    def _load_items(self, items):
        for item in items:
            typeIcon = self._replace_symbol_type.get(item.type, item.type)
            self._root.loadItem(typeIcon, item.name, item.lineno,
                                item.path, self._colors[item.type])

    def _fetch_more(self):
        locations = self._create_list_items(self.tempLocations)
        self._load_items(locations)

    def _create_list_items(self, locations):
        """Create a list of items (using pages for results to speed up)."""
        #The list is regenerated when the locate metadata is updated
        #for example: open project, etc.
        #Create the list items
        begin = self.items_in_page
        self.items_in_page += self.page_items_step
        locations_view = [x for x in locations[begin:self.items_in_page]]
        return locations_view

    def filter(self):
        self._line_jump = -1
        self.items_in_page = 0

        filterOptions = self.filterPrefix.split(self.__prefix.lstrip())
        if filterOptions[0] == '':
            del filterOptions[0]

        if len(filterOptions) == 0:
            self.tempLocations = self.locate_symbols.get_locations()
        elif len(filterOptions) == 1:
            self.tempLocations = [
                x for x in self.locate_symbols.get_locations()
                if x.comparison.lower().find(filterOptions[0].lower()) > -1]
        else:
            index = 0
            if not self.tempLocations and (self.__pre_filters == filterOptions):
                self.tempLocations = self.__pre_results
                return self._create_list_items(self.tempLocations)
            while index < len(filterOptions):
                filter_action = self._filter_actions.get(
                    filterOptions[index], self._filter_generic)
                if filter_action is None:
                    break
                index = filter_action(filterOptions, index)
            if self.tempLocations:
                self.__pre_filters = filterOptions
                self.__pre_results = self.tempLocations
        return self._create_list_items(self.tempLocations)

    def _filter_generic(self, filterOptions, index):
        at_start = (index == 0)
        if at_start:
            self.tempLocations = [
                x for x in self.locate_symbols.get_locations()
                if x.type == filterOptions[0] and
                x.comparison.lower().find(filterOptions[1].lower()) > -1]
        else:
            currentItem = self.currentItem()
            if (filterOptions[index - 2] == locator.FILTERS['classes'] and
                    currentItem):
                symbols = self.locate_symbols.get_symbols_for_class(
                    currentItem[2], currentItem[1])
                self.tempLocations = symbols
            elif currentItem:
                global mapping_symbols
                self.tempLocations = locator.mapping_symbols.get(
                    currentItem[2], [])
            self.tempLocations = [x for x in self.tempLocations
                                  if x.type == filterOptions[index] and
                                  x.comparison.lower().find(
                                      filterOptions[index + 1].lower()) > -1]
        return index + 2

    def _filter_this_file(self, filterOptions, index):
        at_start = (index == 0)
        if at_start:
            main_container = IDE.get_service('main_container')
            editorWidget = None
            if main_container:
                editorWidget = main_container.get_current_editor()
            index += 2
            if editorWidget:
                exts = settings.SYNTAX.get('python')['extension']
                file_ext = file_manager.get_file_extension(
                    editorWidget.file_path)
                if file_ext in exts:
                    filterOptions.insert(0, locator.FILTERS['files'])
                else:
                    filterOptions.insert(0, locator.FILTERS['non-python'])
                filterOptions.insert(1, editorWidget.file_path)
                self.tempLocations = \
                    self.locate_symbols.get_this_file_symbols(
                        editorWidget.file_path)
                search = filterOptions[index + 1].lstrip().lower()
                self.tempLocations = [x for x in self.tempLocations
                                      if x.comparison.lower().find(search) > -1]
        else:
            del filterOptions[index + 1]
            del filterOptions[index]
        return index

    def _filter_tabs(self, filterOptions, index):
        at_start = (index == 0)
        if at_start:
            ninjaide = IDE.getInstance()
            opened = ninjaide.filesystem.get_files()
            self.tempLocations = [
                locator.ResultItem(
                    locator.FILTERS['files'],
                    opened[f].file_name, opened[f].file_path) for f in opened]
            search = filterOptions[index + 1].lstrip().lower()
            self.tempLocations = [
                x for x in self.tempLocations
                if x.comparison.lower().find(search) > -1]
            index += 2
        else:
            del filterOptions[index + 1]
            del filterOptions[index]
        return index

    def _filter_lines(self, filterOptions, index):
        at_start = (index == 0)
        if at_start:
            main_container = IDE.get_service('main_container')
            editorWidget = None
            if main_container:
                editorWidget = main_container.get_current_editor()
            index = 2
            if editorWidget:
                exts = settings.SYNTAX.get('python')['extension']
                file_ext = file_manager.get_file_extension(
                    editorWidget.file_path)
                if file_ext in exts:
                    filterOptions.insert(0, locator.FILTERS['files'])
                else:
                    filterOptions.insert(0, locator.FILTERS['non-python'])
                filterOptions.insert(1, editorWidget.file_path)
            self.tempLocations = [
                x for x in self.locate_symbols.get_locations()
                if x.type == filterOptions[0] and
                x.path == filterOptions[1]]
        else:
            currentItem = self.currentItem()
            if currentItem:
                self.tempLocations = [
                    x for x in self.locate_symbols.get_locations()
                    if x.type == currentItem[0] and
                    x.path == currentItem[2]]
        if filterOptions[index + 1].isdigit():
            self._line_jump = int(filterOptions[index + 1]) - 1
        return index + 2

    def _open_item(self, path, lineno):
        """Open the item received."""
        main_container = IDE.get_service('main_container')
        if not main_container:
            return
        jump = lineno if self._line_jump == -1 else self._line_jump
        main_container.open_file(path, jump)
        self.hide()

    def hideEvent(self, event):
        super(LocatorWidget, self).hideEvent(event)
        # clean
        self._avoid_refresh = True
        self._root.cleanText()
        self._root.clear()
        self.reset_values()