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()
Пример #2
0
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()
Пример #3
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
Пример #4
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))
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()
Пример #6
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()
Пример #7
0
class FilesHandler(QFrame):
#Qt.WindowStaysOnTopHint | 
    def __init__(self, parent=None):#SplashScreen
        super(FilesHandler, self).__init__(None, Qt.SplashScreen)#, Qt.Popup | Qt.FramelessWindowHint
        # self.setAttribute(Qt.WA_TranslucentBackground)
        # self.setStyleSheet("background:transparent;")
        #self.setStyleSheet("background-color: rgb(25, 255, 60);")
        self.setWindowState(Qt.WindowActive)# | Qt.SplashScreen
        self.setAttribute(Qt.WA_AlwaysStackOnTop, False)
        # Create the QML user interface.
        self._main_container = parent.container#IDE.get_service('main_container')
        self.comboParent = parent
        # self.rawObj = raww(self)

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

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


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

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

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

        # self._root.setVisible(True)

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

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

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

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

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

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

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

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

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

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

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

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

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

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


    def hideEvent(self, event):
        print("hideEvent()", event)
        super(FilesHandler, self).hideEvent(event)
Пример #8
0
from PyQt5.QtCore import QStandardPaths, QDir, QUrl
from PyQt5.QtNetwork import QNetworkDiskCache, QNetworkAccessManager
from PyQt5.QtQml import QQmlNetworkAccessManagerFactory


class NetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory):
    def __init__(self):
        QQmlNetworkAccessManagerFactory.__init__(self)

    def create(self, parent):
        nam = QNetworkAccessManager(parent)
        diskCache = QNetworkDiskCache(nam)
        cachePath = QStandardPaths.displayName(QStandardPaths.CacheLocation)
        print "cache path:", cachePath
        diskCache.setCacheDirectory(cachePath)
        diskCache.setMaximumCacheSize(100 * 1024 * 1024)  # 设置100M缓存
        nam.setCache(diskCache)
        return nam


if __name__ == "__main__":
    import sys
    from PyQt5.QtWidgets import QApplication
    from PyQt5.QtQuickWidgets import QQuickWidget
    app = QApplication(sys.argv)
    widget = QQuickWidget()
    factory = NetworkAccessManagerFactory()
    widget.engine().setNetworkAccessManagerFactory(factory)
    widget.setSource(QUrl("test.qml"))
    widget.show()
    sys.exit(app.exec_())
class FilesHandler(QFrame):
    #Qt.WindowStaysOnTopHint |
    _changedForJava = pyqtSignal()

    def __init__(self, combofiles, Force_Free=False):  #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 = combofiles.container  #IDE.get_service('main_container')
        self.comboParent = combofiles
        self.Force_Free = combofiles.undocked or Force_Free
        # 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()
        cntx = self.view.rootContext()
        cntx.setProperty("tools", Tools())
        self._contextMenu_Incert = self._root.property("_window_")

        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        # {"name": model[i][0],
        # "path": model[i][1],
        # "checkers": model[i][2],
        # "modified": model[i][3],
        # "tempFile": model[i][4],
        # "project": "",
        # "itemVisible": true});

        self._ntup = ("name", "path", "checkers", "modified", "tempFile",
                      "project", "itemVisible")
        # self._Ndtup = namedtuple("_Ndtup", self._ntup)

        self._filePathPosition = {}
        self._filesModel = []
        self._temp_files = {}
        self._max_index = 0
        print("\n\nFilesHandler", self, self._contextMenu_Incert)

        # 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 old, now, this=self:  print("\n\n:focusChanged:", this.hide(), old, now) if old == 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):
        print("\n\n_open", path, "|", temp, "|", project, "|", self)
        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)
            print("nfile", nfile, neditable, self._temp_files, temp)
            self._main_container.current_comboEditor.set_current(neditable)
        else:
            # self._main_container.open_file(path)
            # self._main_container.open_file_from_nEditable(self.comboParent.get_editable_fromPath(path),\
            # self.comboParent.ParentalComboEditor)
            self.comboParent.ParentalComboEditor.set_current(\
                self.comboParent.get_editable_fromPath(path) )

            index = self._filePathPosition[path]
            self._max_index = max(self._max_index, index) + 1
            self._filePathPosition[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 getNewIndex(self):
        self._max_index += 1
        return self._max_index - 1

    def currentEditable(self):
        return self.comboParent.get_editable()

    def removeFile(self, nedit):
        self.removeFilePath(nedit.file_path)

    def removeFilePath(self, path):
        # del self._filesModel[self._filePathPosition[path]]
        del self._filePathPosition[path]
        self._changedForJava.emit()

    @pyqtProperty(QJsonValue, notify=_changedForJava)
    def fileModel(self):
        return self._filesModel

    def add_Data(self, dat):
        self._filesModel.append(dict(zip(self._tup, dat)))
        # sort by Path
        model = sorted(self._filesModel,\
            key=lambda x: self._filePathPosition.get(x[1], False), reverse=True)

        self._filesModel = model
        self._changedForJava.emit()

    def addFile(self, neditable):
        nfile = neditable.nfile
        current_editor = ninjaide.getCurrentEditor()

        current_path = current_editor.file_path if current_editor else ""
        model = []
        if nfile.file_path not in self._filePathPosition and nfile.file_path is not None:
            self._filePathPosition[
                nfile.file_path] = 0  # default position for NEW FILE

        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 ""

        if temp_file:
            self._temp_files[temp_file] = nfile

        self.add_Data( (nfile.file_name, filepath, checks, modified, temp_file,\
            "", current_path and current_path != nfile.file_path) )

    def _add_model(self):
        # print("_add_model:_add_model")
        ninjaide = IDE.getInstance()
        #files = ninjaide.opened_files# list<neditable>
        # if True:#self.Force_Free:
        #     files = self.comboParent.opened_files
        # else:
        #     files = ninjaide.opened_files

        files = self.comboParent.opened_files
        print("_add_model::", len(files))
        past = set(self._filePathPosition.keys())
        now = set([neditable.file_path for neditable in files])
        old = past - now
        # print("\n_model:past:", past)
        # print("\n_model:now:", now)
        # print("\n_model:old:", old)

        # Update model
        for item in old:
            # print("\n to Delete", item)
            del self._filePathPosition[item]

        current_editor = ninjaide.getCurrentEditor()
        # if current_editor.neditable != self.currentEditable():
        #     QMessageBox.critical(None, "current_editor", "el QSCiEditor que la aplicación dice que es el actual\n"\
        #         "NO coincide con el Editor de éste FilesHandler()")

        current_path = current_editor.file_path if current_editor else ""
        model = []
        # print("len(files)", len(files), [nfile.file_path for nfile in files], "\n\n")
        for neditable in files:
            nfile = neditable.nfile

            if nfile.file_path not in self._filePathPosition and nfile.file_path is not None:
                self._filePathPosition[nfile.file_path] = self.getNewIndex()

            # print("\n_add_model->", not self.Force_Free, type(nfile))
            # if not self.Force_Free:
            #     neditable = ninjaide.get_or_create_editable_EXTERNAL(nfile=nfile)

            # print("\n_add_model->->", neditable, self._filePathPosition, neditable.editor)

            checkers = neditable.sorted_checkers
            checks = []
            for items in checkers:
                checker, color, _ = items
                if checker.dirty:
                    # Colors needs to be reversed for QML
                    color = "#%s" % color[::-1][:-1]
                    checks.append({
                        "checker_text": checker.dirty_text,
                        "checker_color": color
                    })

            modified = neditable.editor.is_modified
            temp_file = str(uuid.uuid4()) if nfile.file_path is None else ""
            filepath = nfile.file_path if nfile.file_path is not None else ""
            model.append([
                nfile.file_name, filepath, checks, modified, temp_file, "",
                current_path and current_path != nfile.file_path
            ])
            if temp_file:
                self._temp_files[temp_file] = nfile

        # if current_path:
        #     index = self._filePathPosition[current_path]
        #     self._max_index = max(self._max_index, index) + 1
        #     self._filePathPosition[current_path] = self._max_index

        # print("\n\nmodel:1:", self._filePathPosition, "\n///", model)
        # sort by Path
        model = sorted(model,
                       key=lambda x: self._filePathPosition.get(x[1], False),
                       reverse=True)
        # print("\n\nmodel:2:", model)
        self._root.set_model(model)

    def showEvent(self, event):
        print("\nshowEvent:::showEvent", self.isVisible(),
              self.view.isVisible())
        self._add_model()
        widget = self.comboParent.ParentalComboEditor.currentEditor()
        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)

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

    def hideEvent(self, event):
        print("\nhideEvent:::", self.isVisible(), self.view.isVisible())
        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):
        print("\n\nFILESHANDLER.mousePressEvent",
              QApplication.instance().widgetAt(self.mapToGlobal(event.pos())))
        if QApplication.instance().widgetAt(self.mapToGlobal(
                event.pos())) == self.comboParent:
            print("TRUE!!!")
            # event.ignore()
            # self.comboParent.hidePopup()
            return
        super(FilesHandler, self).mousePressEvent(event)
Пример #10
0
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()