示例#1
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", 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)
示例#2
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)
示例#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)
示例#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", 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)
示例#5
0
文件: qmlloader.py 项目: hosiet/dae
class QmlWindow(QtWidgets.QWidget):
    def __init__(self, url):
        super(QmlWindow, self).__init__()

        self.setAttribute(Qt.WA_QuitOnClose, True)
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        #self.setTransBackground(True)

        self.qmlWindow = QQuickWidget(self)
        self.qmlWindow.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.qmlWindow.rootContext().setContextProperty(
            "qmlWindow", self.qmlWindow)
        self.qmlWindow.setSource(QUrl(url))

        windowFlags = Qt.FramelessWindowHint
        self.setWindowFlags(windowFlags)

        self.show()

    @pyqtSlot(bool)
    def setTransBackground(self, transBackground):
        palette = self.palette()
        if transBackground:
            palette.setBrush(QPalette.Base, Qt.transparent)
        else:
            palette.setBrush(QPalette.Base, Qt.white)
        self.setPalette(palette)
示例#6
0
 def widgetForQMLUsingQQuickWidget(self, qmlFilename, parentWindow):
   widget = QQuickWidget()
   qurl = resourceMgr.urlToQMLResource(resourceSubpath=qmlFilename)
   widget.setSource(qurl)
   widget.show()
   " Return widget both as widget and quickThing having rootObject() "
   return widget, widget
示例#7
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)
示例#8
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)
示例#9
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)
示例#10
0
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()
示例#12
0
 def ui(self):
     layout = QVBoxLayout(self)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QQuickWidget(self)
     widget.setContentsMargins(0, 0, 0, 0)
     widget.rootContext().setContextProperty('self', self.obj)
     widget.setSource(QUrl(self.qml))
     layout.addWidget(widget)
     return layout
示例#13
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 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()
示例#15
0
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()
示例#16
0
def quickWidgetFromIpfs(ipfsPath: IPFSPath, parent=None):
    app = runningApp()

    url = app.subUrl(str(ipfsPath))
    parentUrl = app.subUrl(str(ipfsPath.parent()))

    qWidget = QQuickWidget(parent)
    qWidget.engine().setBaseUrl(parentUrl)
    qWidget.setSource(url)
    return qWidget
示例#17
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))
    def _create_qml_view(self, qml_file, minimum_size=(0,0)):

        path = str(ConfigInstall.Path.join_qml_path(qml_file))

        widget = QQuickWidget(self.qml_engine, 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)

        return widget
示例#19
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))
示例#20
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)
示例#21
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))
示例#22
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)
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))
    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)
示例#25
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)
示例#26
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
示例#27
0
    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)
示例#28
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)
示例#29
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)
示例#30
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)
示例#31
0
    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)
示例#32
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)
示例#33
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)
示例#34
0
    def ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        widget = QQuickWidget(self)
        widget.setContentsMargins(0, 0, 0, 0)
        widget.rootContext().setContextProperty('self', self.obj)
        widget.setSource(QtCore.QUrl(self.qml))
        layout.addWidget(widget)
        pdsWidget = ProductList(self.products)

        width = 750
        pdsWidget.setMinimumWidth(width)
        pdsWidget.setMaximumWidth(width)

        product_layout = QHBoxLayout(self)
        product_layout.setContentsMargins(0, 0, 0, 0)
        product_layout.addSpacing(30)
        product_layout.addWidget(pdsWidget)
        product_layout.addStretch(1)

        layout.addLayout(product_layout)
        layout.addStretch(1)
        return layout
示例#35
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
示例#36
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
示例#37
0
    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)
示例#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()
示例#39
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())
示例#40
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()
示例#41
0
class RelationEditorFeatureSideWidget(QgsAbstractRelationEditorWidget,
                                      WidgetUi):
    class LastView(str, Enum):
        ListView = "ListView"
        IconView = "IconView"

    settingsLastView = QgsSettingsEntryString(
        'relationEditorFeatureSideLastView', PluginHelper.PLUGIN_SLUG,
        LastView.ListView,
        PluginHelper.tr(
            'Last view used in the relation editor document side widget'))

    signalCurrentViewChanged = pyqtSignal()

    def __init__(self, config, parent):
        super().__init__(config, parent)
        self._updateUiTimer = QTimer()
        self._updateUiTimer.setSingleShot(True)
        self._updateUiTimer.timeout.connect(self.updateUiTimeout)
        self.setupUi(self)

        print('DocumentRelationEditorFeatureSideWidget.__init__')

        self.documents_path = str()
        self.document_filename = str()

        self.model = DocumentModel()

        self._nmRelation = QgsRelation()
        self._layerInSameTransactionGroup = False

        self._currentDocumentId = None

        # Actions
        self.actionToggleEditing = QAction(
            QIcon(":/images/themes/default/mActionToggleEditing.svg"),
            self.tr("Toggle editing mode for child layers"))
        self.actionToggleEditing.setCheckable(True)
        self.actionSaveEdits = QAction(
            QIcon(":/images/themes/default/mActionSaveEdits.svg"),
            self.tr("Save child layer edits"))
        self.actionShowForm = QAction(
            QIcon(":/images/themes/default/mActionMultiEdit.svg"),
            self.tr("Show form"))
        self.actionAddFeature = QAction(
            QIcon(":/images/themes/default/symbologyAdd.svg"),
            self.tr("Add document"))
        self.actionDeleteFeature = QAction(
            QIcon(":/images/themes/default/mActionDeleteSelected.svg"),
            self.tr("Drop document"))
        self.actionLinkFeature = QAction(
            QIcon(":/images/themes/default/mActionLink.svg"),
            self.tr("Link document"))
        self.actionUnlinkFeature = QAction(
            QIcon(":/images/themes/default/mActionUnlink.svg"),
            self.tr("Unlink document"))

        # Tool buttons
        self.mToggleEditingToolButton.setDefaultAction(
            self.actionToggleEditing)
        self.mSaveEditsToolButton.setDefaultAction(self.actionSaveEdits)
        self.mShowFormToolButton.setDefaultAction(self.actionShowForm)
        self.mAddFeatureToolButton.setDefaultAction(self.actionAddFeature)
        self.mDeleteFeatureToolButton.setDefaultAction(
            self.actionDeleteFeature)
        self.mLinkFeatureToolButton.setDefaultAction(self.actionLinkFeature)
        self.mUnlinkFeatureToolButton.setDefaultAction(
            self.actionUnlinkFeature)

        self.mListViewToolButton.setIcon(
            QIcon(":/images/themes/default/mIconListView.svg"))
        self.mIconViewToolButton.setIcon(
            QIcon(":/images/themes/default/mActionIconView.svg"))
        self.mListViewToolButton.setChecked(self.currentView == str(
            RelationEditorFeatureSideWidget.LastView.ListView))
        self.mIconViewToolButton.setChecked(self.currentView == str(
            RelationEditorFeatureSideWidget.LastView.IconView))

        # Quick image providers
        self._previewImageProvider = PreviewImageProvider()
        self._fileTypeSmallIconProvider = FileTypeIconImageProvider(32)
        self._fileTypeBigIconProvider = FileTypeIconImageProvider(100)

        # Setup QML part
        self.view = QQuickWidget()
        self.view.rootContext().setContextProperty("documentModel", self.model)
        self.view.rootContext().setContextProperty("parentWidget", self)
        self.view.rootContext().setContextProperty(
            "CONST_LIST_VIEW",
            str(RelationEditorFeatureSideWidget.LastView.ListView))
        self.view.rootContext().setContextProperty(
            "CONST_ICON_VIEW",
            str(RelationEditorFeatureSideWidget.LastView.IconView))
        self.view.engine().addImageProvider("previewImageProvider",
                                            self._previewImageProvider)
        self.view.engine().addImageProvider("fileTypeSmallIconProvider",
                                            self._fileTypeSmallIconProvider)
        self.view.engine().addImageProvider("fileTypeBigIconProvider",
                                            self._fileTypeBigIconProvider)
        self.view.setSource(
            QUrl.fromLocalFile(
                os.path.join(os.path.dirname(__file__),
                             '../qml/DocumentList.qml')))
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.layout().addWidget(self.view)

        # Set initial state for add / remove etc.buttons
        self.updateButtons()

        # Signal slots
        self.actionToggleEditing.triggered.connect(self.toggleEditing)
        self.actionSaveEdits.triggered.connect(self.saveChildLayerEdits)
        self.actionShowForm.triggered.connect(self.showDocumentForm)
        self.actionAddFeature.triggered.connect(self.addDocument)
        self.actionDeleteFeature.triggered.connect(self.dropDocument)
        self.actionLinkFeature.triggered.connect(self.linkDocument)
        self.actionUnlinkFeature.triggered.connect(self.unlinkDocument)
        self.mListViewToolButton.toggled.connect(
            self.listViewToolButtonToggled)
        self.mIconViewToolButton.toggled.connect(
            self.iconViewToolButtonToggled)

    @pyqtProperty(str)
    def currentView(self):
        return self.settingsLastView.value()

    def updateCurrentView(self):
        if self.mListViewToolButton.isChecked():
            self.settingsLastView.setValue(
                str(RelationEditorFeatureSideWidget.LastView.ListView))
        else:
            self.settingsLastView.setValue(
                str(RelationEditorFeatureSideWidget.LastView.IconView))

        self.signalCurrentViewChanged.emit()

    @pyqtProperty(QVariant)
    def currentDocumentId(self):
        return self._currentDocumentId

    @pyqtSlot(QVariant)
    def setCurrentDocumentId(self, value):
        self._currentDocumentId = value
        self.updateButtons()

    def nmRelation(self):
        return self._nmRelation

    def config(self):
        return {}

    def setConfig(self, config):
        self.documents_path = config['documents_path']
        self.document_filename = config['document_filename']

    def updateUi(self):
        self._updateUiTimer.start(200)

    def updateUiTimeout(self):
        self.model.init(self.relation(), self.nmRelation(), self.feature(),
                        self.documents_path, self.document_filename)

    def updateButtons(self):
        toggleEditingButtonEnabled = False
        editable = False
        linkable = False
        spatial = False
        selectionNotEmpty = self._currentDocumentId is not None

        if self.relation().isValid():
            toggleEditingButtonEnabled = self.relation().referencingLayer(
            ).supportsEditing()
            editable = self.relation().referencingLayer().isEditable()
            linkable = self.relation().referencingLayer().isEditable()
            spatial = self.relation().referencingLayer().isSpatial()

        if self.nmRelation().isValid():
            toggleEditingButtonEnabled |= self.nmRelation().referencedLayer(
            ).supportsEditing()
            editable = self.nmRelation().referencedLayer().isEditable()
            spatial = self.nmRelation().referencedLayer().isSpatial()

        self.mToggleEditingToolButton.setEnabled(toggleEditingButtonEnabled)
        self.mAddFeatureToolButton.setEnabled(editable)
        self.mLinkFeatureToolButton.setEnabled(linkable)
        self.mDeleteFeatureToolButton.setEnabled(editable
                                                 and selectionNotEmpty)
        self.mUnlinkFeatureToolButton.setEnabled(linkable
                                                 and selectionNotEmpty)
        self.mToggleEditingToolButton.setChecked(editable)
        self.mSaveEditsToolButton.setEnabled(editable or linkable)

        self.mShowFormToolButton.setEnabled(selectionNotEmpty)

        self.mToggleEditingToolButton.setVisible(
            self._layerInSameTransactionGroup is False)
        self.mSaveEditsToolButton.setVisible(
            self._layerInSameTransactionGroup is False)

    def afterSetRelations(self):
        self._nmRelation = QgsProject.instance().relationManager().relation(
            str(self.nmRelationId()))

        self._checkTransactionGroup()

        if self.relation().isValid():
            self.relation().referencingLayer().editingStopped.connect(
                self.updateButtons)
            self.relation().referencingLayer().editingStarted.connect(
                self.updateButtons)

        if self.nmRelation().isValid():
            self.nmRelation().referencedLayer().editingStarted.connect(
                self.updateButtons)
            self.nmRelation().referencedLayer().editingStopped.connect(
                self.updateButtons)

        self.updateButtons()

    def _checkTransactionGroup(self):

        self._layerInSameTransactionGroup = False
        connectionString = PluginHelper.connectionString(
            self.relation().referencedLayer().source())
        transactionGroup = QgsProject.instance().transactionGroup(
            self.relation().referencedLayer().providerType(), connectionString)

        if transactionGroup is None:
            return

        if self.nmRelation().isValid():
            if (self.relation().referencedLayer() in transactionGroup.layers()
                    and self.relation().referencingLayer()
                    in transactionGroup.layers()
                    and self.nmRelation().referencedLayer()
                    in transactionGroup.layers()):
                self._layerInSameTransactionGroup = True
        else:
            if (self.relation().referencedLayer() in transactionGroup.layers()
                    and self.relation().referencingLayer()
                    in transactionGroup.layers()):
                self._layerInSameTransactionGroup = True

    def parentFormValueChanged(self, attribute, newValue):
        pass

    def checkLayerEditingMode(self):

        if self.relation().referencingLayer().isEditable() is False:
            QMessageBox.critical(
                self, self.tr("Layer not editable"),
                self.tr("Layer '{0}' is not in editing mode.").format(
                    self.relation().referencingLayer().name()))
            return False

        if self.nmRelation().isValid():
            if self.nmRelation().referencedLayer().isEditable() is False:
                QMessageBox.critical(
                    self, self.tr("Layer not editable"),
                    self.tr("Layer '{0}' is not in editing mode.").format(
                        self.nmRelation().referencedLayer().name()))
                return False

        return True

    @pyqtSlot(bool)
    def toggleEditing(self, state):

        super().toggleEditing(state)
        self.updateButtons()

    @pyqtSlot()
    def saveChildLayerEdits(self):

        super().saveEdits()

    @pyqtSlot()
    def addDocument(self):

        # Workaround because of QGIS not resetting this property after linking features
        self.editorContext().vectorLayerTools().setForceSuppressFormPopup(
            False)
        self.addFeature()

    @pyqtSlot()
    def dropDocument(self):

        if self._currentDocumentId is None:
            return

        self.deleteFeature(self._currentDocumentId)

    @pyqtSlot(str)
    def addDroppedDocument(self, fileUrl):

        if self.checkLayerEditingMode() is False:
            return

        # Workaround because of QGIS not resetting this property after linking features
        self.editorContext().vectorLayerTools().setForceSuppressFormPopup(
            False)

        layer = self.relation().referencingLayer()
        if self.nmRelation().isValid():
            layer = self.nmRelation().referencedLayer()

        default_documents_path = str()
        if self.documents_path:
            exp = QgsExpression(self.documents_path)
            context = QgsExpressionContext()
            context.appendScopes(
                QgsExpressionContextUtils.globalProjectLayerScopes(layer))
            default_documents_path = str(exp.evaluate(context))

        filename = QUrl(fileUrl).toLocalFile()
        if default_documents_path:
            filename = QDir(default_documents_path).relativeFilePath(filename)

        keyAttrs = dict()

        # Fields of the linking table
        fields = self.relation().referencingLayer().fields()

        # For generated relations insert the referenced layer field
        if self.relation().type() == QgsRelation.Generated:
            polyRel = self.relation().polymorphicRelation()
            keyAttrs[fields.indexFromName(
                polyRel.referencedLayerField())] = polyRel.layerRepresentation(
                    self.relation().referencedLayer())

        if self.nmRelation().isValid():
            # only normal relations support m:n relation
            if self.nmRelation().type() != QgsRelation.Normal:
                QMessageBox.critical(
                    self, self.tr("Add document"),
                    self.
                    tr("Invalid relation, Only normal relations support m:n relation."
                       ))
                return

            # Pre fill inserting document filepath
            attributes = {
                self.nmRelation().referencedLayer().fields().indexFromName(self.document_filename):
                filename
            }

            # n:m Relation: first let the user create a new feature on the other table
            # and autocreate a new linking feature.
            ok, feature = self.editorContext().vectorLayerTools().addFeature(
                self.nmRelation().referencedLayer(), attributes, QgsGeometry())
            if not ok:
                QMessageBox.critical(
                    self, self.tr("Add document"),
                    self.tr("Could not add a new linking feature."))
                return

            for key in self.relation().fieldPairs():
                keyAttrs[fields.indexOf(key)] = self.feature().attribute(
                    self.relation().fieldPairs()[key])

            for key in self.nmRelation().fieldPairs():
                keyAttrs[fields.indexOf(key)] = feature.attribute(
                    self.nmRelation().fieldPairs()[key])

            linkFeature = QgsVectorLayerUtils.createFeature(
                self.relation().referencingLayer(), QgsGeometry(), keyAttrs,
                self.relation().referencingLayer().createExpressionContext())

            if not self.relation().referencingLayer().addFeature(linkFeature):
                QMessageBox.critical(self, self.tr("Add document"),
                                     self.tr("Could not add a new feature."))
                return

        else:
            for key in self.relation().fieldPairs():
                keyAttrs[fields.indexFromName(key)] = self.feature().attribute(
                    self.relation().fieldPairs()[key])

            # Pre fill inserting document filepath
            keyAttrs[fields] = filename

            ok, feature = self.editorContext().vectorLayerTools().addFeature(
                self.relation().referencingLayer(), keyAttrs, QgsGeometry())
            if not ok:
                QMessageBox.critical(self, self.tr("Add document"),
                                     self.tr("Could not add a new feature."))
                return

        self.updateUi()

    @pyqtSlot()
    def linkDocument(self):

        self.linkFeature()

    @pyqtSlot()
    def unlinkDocument(self):

        if self._currentDocumentId is None:
            return

        self.unlinkFeature(self._currentDocumentId)

    @pyqtSlot()
    def showDocumentForm(self):

        if self._currentDocumentId is None:
            return

        layer = self.relation().referencingLayer()
        if self.nmRelation().isValid():
            layer = self.nmRelation().referencedLayer()

        showDocumentFormDialog = QgsAttributeDialog(
            layer, layer.getFeature(self._currentDocumentId), False, self,
            True)
        showDocumentFormDialog.exec()
        self.updateUi()

    @pyqtSlot(bool)
    def listViewToolButtonToggled(self, checked):
        self.mIconViewToolButton.blockSignals(True)
        self.mIconViewToolButton.setChecked(checked is False)
        self.mIconViewToolButton.blockSignals(False)
        self.updateCurrentView()

    @pyqtSlot(bool)
    def iconViewToolButtonToggled(self, checked):
        self.mListViewToolButton.blockSignals(True)
        self.mListViewToolButton.setChecked(checked is False)
        self.mListViewToolButton.blockSignals(False)
        self.updateCurrentView()
示例#42
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
示例#44
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)
示例#45
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()
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()
示例#47
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_())
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)
示例#49
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()