Beispiel #1
0
class MainWindow(QMainWindow, Ui_MainWindow):

    """Main window of kmol editor."""

    def __init__(self):
        super(MainWindow, self).__init__(None)
        self.setupUi(self)

        # Start new window.
        @pyqtSlot()
        def new_main_window():
            XStream.back()
            run = self.__class__()
            run.show()

        self.action_New_Window.triggered.connect(new_main_window)

        # Text editor
        self.text_editor = TextEditor(self)
        self.h_splitter.addWidget(self.text_editor)
        self.text_editor.word_changed.connect(self.__set_not_saved_title)
        self.edge_line_option.toggled.connect(self.text_editor.setEdgeMode)
        self.trailing_blanks_option.toggled.connect(self.text_editor.set_remove_trailing_blanks)

        # Highlighters
        self.highlighter_option.addItems(sorted(QSCIHIGHLIGHTERS))
        self.highlighter_option.setCurrentText("Markdown")
        self.highlighter_option.currentTextChanged.connect(
            self.text_editor.set_highlighter
        )

        # Tree widget context menu.
        self.tree_widget.customContextMenuRequested.connect(
            self.on_tree_widget_context_menu
        )
        self.popMenu_tree = QMenu(self)
        self.popMenu_tree.setSeparatorsCollapsible(True)
        self.popMenu_tree.addAction(self.action_new_project)
        self.popMenu_tree.addAction(self.action_open)
        self.tree_add = QAction("&Add Node", self)
        self.tree_add.triggered.connect(self.add_node)
        self.tree_add.setShortcut("Ctrl+I")
        self.tree_add.setShortcutContext(Qt.WindowShortcut)
        self.popMenu_tree.addAction(self.tree_add)

        self.popMenu_tree.addSeparator()

        self.tree_path = QAction("Set Path", self)
        self.tree_path.triggered.connect(self.set_path)
        self.popMenu_tree.addAction(self.tree_path)
        self.tree_refresh = QAction("&Refresh from Path", self)
        self.tree_refresh.triggered.connect(self.refresh_proj)
        self.popMenu_tree.addAction(self.tree_refresh)
        self.tree_openurl = QAction("&Open from Path", self)
        self.tree_openurl.triggered.connect(self.open_path)
        self.popMenu_tree.addAction(self.tree_openurl)
        self.action_save.triggered.connect(self.save_proj)
        self.popMenu_tree.addAction(self.action_save)
        self.tree_copy = QAction("Co&py", self)
        self.tree_copy.triggered.connect(self.copy_node)
        self.popMenu_tree.addAction(self.tree_copy)
        self.tree_clone = QAction("C&lone", self)
        self.tree_clone.triggered.connect(self.clone_node)
        self.popMenu_tree.addAction(self.tree_clone)
        self.tree_copy_tree = QAction("Recursive Copy", self)
        self.tree_copy_tree.triggered.connect(self.copy_node_recursive)
        self.popMenu_tree.addAction(self.tree_copy_tree)
        self.tree_clone_tree = QAction("Recursive Clone", self)
        self.tree_clone_tree.triggered.connect(self.clone_node_recursive)
        self.popMenu_tree.addAction(self.tree_clone_tree)

        self.popMenu_tree.addSeparator()

        self.tree_delete = QAction("&Delete", self)
        self.tree_delete.triggered.connect(self.delete_node)
        self.popMenu_tree.addAction(self.tree_delete)
        self.tree_close = QAction("&Close", self)
        self.tree_close.triggered.connect(self.close_file)
        self.popMenu_tree.addAction(self.tree_close)
        self.tree_main.header().setSectionResizeMode(QHeaderView.ResizeToContents)

        # Console
        self.console.setFont(self.text_editor.font)
        if not ARGUMENTS.debug_mode:
            XStream.stdout().messageWritten.connect(self.__append_to_console)
            XStream.stderr().messageWritten.connect(self.__append_to_console)
        for info in INFO:
            print(info)
        print('-' * 7)

        # Searching function.
        find_next = QShortcut(QKeySequence("F3"), self)
        find_next.activated.connect(self.find_next_button.click)
        find_previous = QShortcut(QKeySequence("F4"), self)
        find_previous.activated.connect(self.find_previous_button.click)
        find_tab = QShortcut(QKeySequence("Ctrl+F"), self)
        find_tab.activated.connect(lambda: self.panel_widget.setCurrentIndex(1))
        find_project = QShortcut(QKeySequence("Ctrl+Shift+F"), self)
        find_project.activated.connect(self.find_project_button.click)

        # Replacing function.
        replace = QShortcut(QKeySequence("Ctrl+R"), self)
        replace.activated.connect(self.replace_node_button.click)
        replace_project = QShortcut(QKeySequence("Ctrl+Shift+R"), self)
        replace_project.activated.connect(self.replace_project_button.click)

        # Translator.
        self.panel_widget.addTab(TranslatorWidget(self), "Translator")

        # Node edit function. (Ctrl + ArrowKey)
        move_up_node = QShortcut(QKeySequence("Ctrl+Up"), self)
        move_up_node.activated.connect(self.__move_up_node)
        move_down_node = QShortcut(QKeySequence("Ctrl+Down"), self)
        move_down_node.activated.connect(self.__move_down_node)
        move_right_node = QShortcut(QKeySequence("Ctrl+Right"), self)
        move_right_node.activated.connect(self.__move_right_node)
        move_left_node = QShortcut(QKeySequence("Ctrl+Left"), self)
        move_left_node.activated.connect(self.__move_left_node)

        # Run script button.
        run_sript = QShortcut(QKeySequence("F5"), self)
        run_sript.activated.connect(self.exec_button.click)
        self.macros_toolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        # Splitter
        self.h_splitter.setStretchFactor(0, 10)
        self.h_splitter.setStretchFactor(1, 60)
        self.v_splitter.setStretchFactor(0, 30)
        self.v_splitter.setStretchFactor(1, 10)

        # Data
        self.data = DataDict()
        self.data.not_saved.connect(self.__set_not_saved_title)
        self.data.all_saved.connect(self.__set_saved_title)
        self.env = QStandardPaths.writableLocation(QStandardPaths.DesktopLocation)

        for filename in ARGUMENTS.r:
            filename = QFileInfo(filename).canonicalFilePath()
            if not filename:
                return
            root_node = QTreeRoot(QFileInfo(filename).baseName(), filename, '')
            self.tree_main.addTopLevelItem(root_node)
            parse(root_node, self.data)
        self.__add_macros()

    def dragEnterEvent(self, event):
        """Drag file in to our window."""
        if event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event):
        """Drop file in to our window."""
        for url in event.mimeData().urls():
            filename = url.toLocalFile()
            root_node = QTreeRoot(QFileInfo(filename).baseName(), filename, '')
            self.tree_main.addTopLevelItem(root_node)
            parse(root_node, self.data)
            self.tree_main.setCurrentItem(root_node)
        self.__add_macros()
        event.acceptProposedAction()

    @pyqtSlot()
    def __set_not_saved_title(self):
        """Show star sign on window title."""
        if '*' not in self.windowTitle():
            self.setWindowTitle(self.windowTitle() + '*')

    @pyqtSlot()
    def __set_saved_title(self):
        """Remove star sign on window title."""
        self.setWindowTitle(self.windowTitle().replace('*', ''))

    @pyqtSlot(str)
    def __append_to_console(self, log):
        """After inserted the text, move cursor to end."""
        self.console.moveCursor(QTextCursor.End)
        self.console.insertPlainText(log)
        self.console.moveCursor(QTextCursor.End)

    @pyqtSlot(QPoint, name='on_tree_widget_context_menu')
    def __tree_context_menu(self, point: QPoint):
        """Operations."""
        self.__action_changed()
        self.popMenu_tree.exec_(self.tree_widget.mapToGlobal(point))

    @pyqtSlot(name='on_action_new_project_triggered')
    def new_proj(self):
        """New file."""
        filename, _ = QFileDialog.getSaveFileName(
            self,
            "New Project",
            self.env,
            SUPPORT_FILE_FORMATS
        )
        if not filename:
            return
        self.env = QFileInfo(filename).absolutePath()
        root_node = QTreeRoot(
            QFileInfo(filename).baseName(),
            filename,
            str(self.data.new_num())
        )
        suffix_text = file_suffix(filename)
        if suffix_text == 'md':
            root_node.setIcon(0, file_icon("markdown"))
        elif suffix_text == 'html':
            root_node.setIcon(0, file_icon("html"))
        elif suffix_text == 'kmol':
            root_node.setIcon(0, file_icon("kmol"))
        else:
            root_node.setIcon(0, file_icon("txt"))
        self.tree_main.addTopLevelItem(root_node)

    @pyqtSlot(name='on_action_open_triggered')
    def open_proj(self):
        """Open file."""
        file_names, ok = QFileDialog.getOpenFileNames(
            self,
            "Open Projects",
            self.env,
            SUPPORT_FILE_FORMATS
        )
        if not ok:
            return

        def in_widget(path: str) -> int:
            """Is name in tree widget."""
            for i in range(self.tree_main.topLevelItemCount()):
                if path == self.tree_main.topLevelItem(i).text(1):
                    return i
            return -1

        for file_name in file_names:
            self.env = QFileInfo(file_name).absolutePath()
            index = in_widget(file_name)
            if index == -1:
                root_node = QTreeRoot(QFileInfo(file_name).baseName(), file_name, '')
                self.tree_main.addTopLevelItem(root_node)
                parse(root_node, self.data)
                self.tree_main.setCurrentItem(root_node)
            else:
                self.tree_main.setCurrentItem(self.tree_main.topLevelItem(index))

        self.__add_macros()

    @pyqtSlot()
    def refresh_proj(self):
        """Re-parse the file node."""
        node = self.tree_main.currentItem()
        if not node.text(1):
            QMessageBox.warning(
                self,
                "No path",
                "Can only refresh from valid path."
            )
        parse(node, self.data)
        self.tree_main.setCurrentItem(node)
        self.text_editor.setText(self.data[int(node.text(2))])

    @pyqtSlot()
    def open_path(self):
        """Open path of current node."""
        node = self.tree_main.currentItem()
        filename = getpath(node)
        QDesktopServices.openUrl(QUrl(filename))
        print("Open: {}".format(filename))

    @pyqtSlot()
    def add_node(self):
        """Add a node at current item."""
        node = self.tree_main.currentItem()
        new_node = QTreeItem(
            "New node",
            "",
            str(self.data.new_num())
        )
        if node.childCount() or node.text(1):
            node.addChild(new_node)
            return
        parent = node.parent()
        if parent:
            parent.insertChild(parent.indexOfChild(node) + 1, new_node)
            return
        self.tree_main.indexOfTopLevelItem(
            self.tree_main.indexOfTopLevelItem(node) + 1,
            new_node
        )

    @pyqtSlot()
    def set_path(self):
        """Set file directory."""
        node = self.tree_main.currentItem()
        filename, ok = QFileDialog.getOpenFileName(
            self,
            "Open File",
            self.env,
            SUPPORT_FILE_FORMATS
        )
        if not ok:
            return
        self.env = QFileInfo(filename).absolutePath()
        project_path = QDir(_get_root(node).text(1))
        project_path.cdUp()
        node.setText(1, project_path.relativeFilePath(filename))

    @pyqtSlot()
    def copy_node(self):
        """Copy current node."""
        node_origin = self.tree_main.currentItem()
        parent = node_origin.parent()
        node = node_origin.clone()
        node.takeChildren()
        code = self.data.new_num()
        self.data[code] = self.data[int(node.text(2))]
        node.setText(2, str(code))
        parent.insertChild(parent.indexOfChild(node_origin) + 1, node)

    @pyqtSlot()
    def clone_node(self):
        """Copy current node with same pointer."""
        node_origin = self.tree_main.currentItem()
        parent = node_origin.parent()
        node = node_origin.clone()
        node.takeChildren()
        parent.insertChild(parent.indexOfChild(node_origin) + 1, node)

    @pyqtSlot()
    def copy_node_recursive(self):
        """Copy current node and its sub-nodes."""
        node_origin = self.tree_main.currentItem()
        parent = node_origin.parent()
        node_origin_copy = node_origin.clone()

        def new_pointer(node: QTreeWidgetItem):
            """Give a new pointer code for node."""
            code = self.data.new_num()
            self.data[code] = self.data[int(node.text(2))]
            node.setText(2, str(code))
            for i in range(node.childCount()):
                new_pointer(node.child(i))

        new_pointer(node_origin_copy)
        parent.insertChild(parent.indexOfChild(node_origin) + 1, node_origin_copy)

    @pyqtSlot()
    def clone_node_recursive(self):
        """Copy current node and its sub-nodes with same pointer."""
        node_origin = self.tree_main.currentItem()
        parent = node_origin.parent()
        parent.insertChild(parent.indexOfChild(node_origin) + 1, node_origin.clone())

    @pyqtSlot()
    def save_proj(self, index: Optional[int] = None, *, for_all: bool = False):
        """Save project and files."""
        if for_all:
            for row in range(self.tree_main.topLevelItemCount()):
                self.save_proj(row)
            return
        node = self.tree_main.currentItem()
        if not node:
            return
        if index is None:
            root = _get_root(node)
        else:
            root = self.tree_main.topLevelItem(index)
        self.__save_current()
        save_file(root, self.data)
        self.data.save_all()

    def __save_current(self):
        """Save the current text of editor."""
        self.text_editor.remove_trailing_blanks()
        item = self.tree_main.currentItem()
        if item:
            self.data[int(item.text(2))] = self.text_editor.text()

    @pyqtSlot()
    def delete_node(self):
        """Delete the current item."""
        node = self.tree_main.currentItem()
        parent = node.parent()
        self.tree_main.setCurrentItem(parent)
        self.__delete_node_data(node)
        parent.removeChild(node)

    def __delete_node_data(self, node: QTreeWidgetItem):
        """Delete data from data structure."""
        name = node.text(0)
        if name.startswith('@'):
            for action in self.macros_toolbar.actions():
                if action.text() == name[1:]:
                    self.macros_toolbar.removeAction(action)
        del self.data[int(node.text(2))]
        for i in range(node.childCount()):
            self.__delete_node_data(node.child(i))

    @pyqtSlot()
    def close_file(self):
        """Close project node."""
        if not self.data.is_all_saved():
            reply = QMessageBox.question(
                self,
                "Not saved",
                "Do you went to save the project?",
                QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel,
                QMessageBox.Save
            )
            if reply == QMessageBox.Save:
                self.save_proj()
            elif reply == QMessageBox.Cancel:
                return

        root = self.tree_main.currentItem()
        self.__delete_node_data(root)
        self.tree_main.takeTopLevelItem(self.tree_main.indexOfTopLevelItem(root))
        self.text_editor.clear()

    @pyqtSlot()
    def __move_up_node(self):
        """Move up current node."""
        node = self.tree_main.currentItem()
        if not node:
            return
        tree_main = node.treeWidget()
        parent = node.parent()
        if parent:
            # Is sub-node.
            index = parent.indexOfChild(node)
            if index == 0:
                return
            parent.removeChild(node)
            parent.insertChild(index - 1, node)
        else:
            # Is root.
            index = tree_main.indexOfTopLevelItem(node)
            if index == 0:
                return
            tree_main.takeTopLevelItem(index)
            tree_main.insertTopLevelItem(index - 1, node)
        tree_main.setCurrentItem(node)
        self.__root_unsaved()

    @pyqtSlot()
    def __move_down_node(self):
        """Move down current node."""
        node = self.tree_main.currentItem()
        if not node:
            return
        tree_main = node.treeWidget()
        parent = node.parent()
        if parent:
            # Is sub-node.
            index = parent.indexOfChild(node)
            if index == parent.childCount() - 1:
                return
            parent.removeChild(node)
            parent.insertChild(index + 1, node)
        else:
            # Is root.
            index = tree_main.indexOfTopLevelItem(node)
            if index == tree_main.topLevelItemCount() - 1:
                return
            tree_main.takeTopLevelItem(index)
            tree_main.insertTopLevelItem(index + 1, node)
        tree_main.setCurrentItem(node)
        self.__root_unsaved()

    @pyqtSlot()
    def __move_right_node(self):
        """Move right current node."""
        node = self.tree_main.currentItem()
        if not node:
            return
        tree_main = node.treeWidget()
        parent = node.parent()
        if parent:
            # Is sub-node.
            index = parent.indexOfChild(node)
            if index == 0:
                return
            parent.removeChild(node)
            parent.child(index - 1).addChild(node)
        else:
            # Is root.
            index = tree_main.indexOfTopLevelItem(node)
            if index == 0:
                return
            tree_main.takeTopLevelItem(index)
            tree_main.topLevelItem(index - 1).addChild(node)
        tree_main.setCurrentItem(node)
        self.__root_unsaved()

    @pyqtSlot()
    def __move_left_node(self):
        """Move left current node."""
        node = self.tree_main.currentItem()
        if not node:
            return
        tree_main = node.treeWidget()
        parent = node.parent()
        if not parent:
            return
        # Must be a sub-node.
        grand_parent = parent.parent()
        if not grand_parent:
            return
        index = grand_parent.indexOfChild(parent)
        parent.removeChild(node)
        grand_parent.insertChild(index + 1, node)
        tree_main.setCurrentItem(node)
        self.__root_unsaved()

    @pyqtSlot(name='on_action_about_qt_triggered')
    def __about_qt(self):
        """Qt about."""
        QMessageBox.aboutQt(self)

    @pyqtSlot(name='on_action_about_triggered')
    def __about(self):
        """Kmol editor about."""
        QMessageBox.about(self, "About Kmol Editor", '\n'.join(INFO + (
            '',
            "Author: " + __author__,
            "Email: " + __email__,
            __copyright__,
            "License: " + __license__,
        )))

    @pyqtSlot(name='on_action_mde_tw_triggered')
    def __mde_tw(self):
        """Mde website."""
        QDesktopServices.openUrl(QUrl("http://mde.tw"))

    @pyqtSlot(name='on_exec_button_clicked')
    def __exec(self):
        """Run the script from current text editor."""
        self.__exec_script(self.text_editor.text())

    def __exec_script(self, code: Union[int, str]):
        """Run a script in a new thread."""
        self.__save_current()

        variables = {
            # Qt file operation classes.
            'QStandardPaths': QStandardPaths,
            'QFileInfo': QFileInfo,
            'QDir': QDir,
        }
        node = self.tree_main.currentItem()
        variables['node'] = node
        if node:
            root = _get_root(node)
            variables['root'] = root
            variables['root_path'] = QFileInfo(root.text(1)).absoluteFilePath()
            variables['node_path'] = getpath(node)

        def chdir_tree(path: str):
            if QFileInfo(path).isDir():
                chdir(path)
            elif QFileInfo(path).isFile():
                chdir(QFileInfo(path).absolutePath())

        variables['chdir'] = chdir_tree
        thread = Thread(
            target=exec,
            args=(self.data[code] if type(code) == int else code, variables)
        )
        thread.start()

    @pyqtSlot(QTreeWidgetItem, QTreeWidgetItem, name='on_tree_main_currentItemChanged')
    def __switch_data(
        self,
        current: QTreeWidgetItem,
        previous: QTreeWidgetItem
    ):
        """Switch node function.

        + Auto collapse and expand function.
        + Important: Store the string data.
        """
        if self.auto_expand_option.isChecked():
            self.tree_main.expandItem(current)
        self.tree_main.scrollToItem(current)

        if previous:
            self.data[int(previous.text(2))] = self.text_editor.text()
        if current:
            # Auto highlight.
            path = current.text(1)
            filename = QFileInfo(path).fileName()
            suffix = QFileInfo(filename).suffix()
            if current.text(0).startswith('@'):
                self.highlighter_option.setCurrentText("Python")
            else:
                self.highlighter_option.setCurrentText("Markdown")
            if path:
                for name_m, suffix_m in HIGHLIGHTER_SUFFIX.items():
                    if suffix in suffix_m:
                        self.highlighter_option.setCurrentText(name_m)
                        break
                else:
                    for name_m, filename_m in HIGHLIGHTER_FILENAME.items():
                        if filename in filename_m:
                            self.highlighter_option.setCurrentText(name_m)
                            break
            self.text_editor.setText(self.data[int(current.text(2))])

        self.__action_changed()

    @pyqtSlot(QTreeWidgetItem, int, name='on_tree_main_itemChanged')
    def __reload_nodes(self, node: QTreeWidgetItem, _: int):
        """Mark edited node as unsaved."""
        name = node.text(0)
        code = int(node.text(2))
        if name.startswith('@'):
            self.__add_macro(name[1:], code)
        self.__root_unsaved()

    def __root_unsaved(self):
        """Let tree to re-save."""
        node = self.tree_main.currentItem()
        if node:
            self.data.set_saved(int(_get_root(node).text(2)), False)

    def __action_changed(self):
        node = self.tree_main.currentItem()
        has_item = bool(node)
        is_root = (not node.parent()) if has_item else False
        for action in (
            self.action_open,
            self.action_new_project,
        ):
            action.setVisible(is_root or not has_item)
        self.tree_close.setVisible(has_item and is_root)
        for action in (
            self.tree_add,
            self.tree_refresh,
            self.tree_openurl,
            self.action_save,
        ):
            action.setVisible(has_item)
        for action in (
            self.tree_copy,
            self.tree_clone,
            self.tree_copy_tree,
            self.tree_clone_tree,
            self.tree_path,
            self.tree_delete,
        ):
            action.setVisible(has_item and not is_root)

    def __add_macros(self):
        """Add macro buttons from data structure."""
        for name, code in self.data.macros():
            self.__add_macro(name, code)

    def __add_macro(self, name: str, code: Union[int, Hashable]):
        """Add macro button."""
        for action in self.macros_toolbar.actions():
            if action.text() == name:
                break
        else:
            action = self.macros_toolbar.addAction(QIcon(QPixmap(":icons/python.png")), name)
            action.triggered.connect(lambda: self.__exec_script(code))

    def __find_text(self, forward: bool):
        """Find text by options."""
        if not self.search_bar.text():
            self.search_bar.setText(self.search_bar.placeholderText())
        pos = self.text_editor.positionFromLineIndex(
            *self.text_editor.getCursorPosition()
        )
        if not self.text_editor.findFirst(
            self.search_bar.text(),
            self.re_option.isChecked(),
            self.match_case_option.isChecked(),
            self.whole_word_option.isChecked(),
            self.wrap_around.isChecked(),
            forward,
            *self.text_editor.lineIndexFromPosition(pos if forward else pos - 1)
        ):
            QMessageBox.information(
                self,
                "Text not found.",
                "\"{}\" is not in current document".format(
                    self.search_bar.text()
                )
            )

    @pyqtSlot(name='on_find_next_button_clicked')
    def __find_next(self):
        """Find to next."""
        self.__find_text(True)

    @pyqtSlot(name='on_find_previous_button_clicked')
    def __find_previous(self):
        """Find to previous."""
        self.__find_text(False)

    @pyqtSlot(name='on_replace_node_button_clicked')
    def __replace(self):
        """Replace current text by replace bar."""
        self.text_editor.replace(self.replace_bar.text())
        self.text_editor.findNext()

    @pyqtSlot(name='on_find_project_button_clicked')
    def __find_project(self):
        """Find in all project."""
        self.find_list.clear()
        node_current = self.tree_main.currentItem()
        if not node_current:
            return
        root = _get_root(node_current)
        if not self.search_bar.text():
            self.search_bar.setText(self.search_bar.placeholderText())
        text = self.search_bar.text()
        flags = re.MULTILINE
        if not self.re_option.isChecked():
            text = re.escape(text)
        if self.whole_word_option.isChecked():
            text = r'\b' + text + r'\b'
        if not self.match_case_option.isChecked():
            flags |= re.IGNORECASE

        def add_find_result(code: int, last_name: str, start: int, end: int):
            """Add result to list."""
            item = QListWidgetItem("{}: [{}, {}]".format(code, start, end))
            item.setToolTip(last_name)
            self.find_list.addItem(item)

        def find_in_nodes(node: QTreeWidgetItem, last_name: str = ''):
            """Find the word in all nodes."""
            last_name += node.text(0)
            if node.childCount():
                last_name += '->'
            code = int(node.text(2))
            doc = self.data[code]
            pattern = re.compile(text, flags)
            for m in pattern.finditer(doc):
                add_find_result(code, last_name, *m.span())
            for i in range(node.childCount()):
                find_in_nodes(node.child(i), last_name)

        find_in_nodes(root)

    @pyqtSlot(
        QListWidgetItem,
        QListWidgetItem,
        name='on_find_list_currentItemChanged')
    def __find_results(self, *_: QListWidgetItem):
        """TODO: Switch to target node."""
Beispiel #2
0
class NumberAndTypeSynthesis(QWidget, Ui_Form):
    
    """Number and type synthesis widget."""
    
    def __init__(self, parent):
        super(NumberAndTypeSynthesis, self).__init__(parent)
        self.setupUi(self)
        self.outputTo = parent.outputTo
        self.saveReplyBox = parent.saveReplyBox
        self.inputFrom = parent.inputFrom
        self.splitter.setStretchFactor(0, 2)
        self.splitter.setStretchFactor(1, 15)
        self.answer = []
        self.save_edges_auto_label.setStatusTip(self.save_edges_auto.statusTip())
        self.NL_input.valueChanged.connect(self.adjust_NJ_NL_dof)
        self.NJ_input.valueChanged.connect(self.adjust_NJ_NL_dof)
        self.graph_engine.addItems(EngineList)
        self.graph_engine.setCurrentIndex(2)
        self.graph_link_as_node.clicked.connect(self.on_reload_atlas_clicked)
        self.graph_engine.currentIndexChanged.connect(
            self.on_reload_atlas_clicked
        )
        self.Topologic_result.customContextMenuRequested.connect(
            self.Topologic_result_context_menu
        )
        """Context menu
        
        + Add to collections
        + Copy edges
        + Copy image
        """
        self.popMenu_topo = QMenu(self)
        self.add_collection = QAction(
            QIcon(QPixmap(":/icons/collections.png")),
            "Add to collections",
            self
        )
        self.copy_edges = QAction("Copy edges", self)
        self.copy_image = QAction("Copy image", self)
        self.popMenu_topo.addActions([
            self.add_collection,
            self.copy_edges,
            self.copy_image
        ])
        self.jointDataFunc = parent.Entities_Point.data
        self.linkDataFunc = parent.Entities_Link.data
        self.clear()
    
    def clear(self):
        """Clear all sub-widgets."""
        self.answer.clear()
        self.Expression_edges.clear()
        self.Expression_number.clear()
        self.Topologic_result.clear()
        self.time_label.setText("")
        self.NL_input.setValue(0)
        self.NJ_input.setValue(0)
        self.NL_input_old_value = 0
        self.NJ_input_old_value = 0
        self.DOF.setValue(1)
    
    @pyqtSlot()
    def on_ReloadMechanism_clicked(self):
        """Reload button: Auto-combine the mechanism from the workbook."""
        jointData = self.jointDataFunc()
        linkData = self.linkDataFunc()
        if jointData and linkData:
            self.Expression_edges.setText(str(v_to_graph(jointData, linkData)))
        else:
            self.Expression_edges.setText("")
        keep_dof_checked = self.keep_dof.isChecked()
        self.keep_dof.setChecked(False)
        self.NL_input.setValue(
            sum(len(vlink.points)>1 for vlink in linkData)+
            sum(
                len(vpoint.links)-1 for vpoint in jointData
                if (vpoint.type == 2) and (len(vpoint.links) > 1)
            )
        )
        self.NJ_input.setValue(sum(
            (len(vpoint.links)-1 + int(vpoint.type == 2))
            for vpoint in jointData if len(vpoint.links)>1
        ))
        self.keep_dof.setChecked(keep_dof_checked)
    
    def adjust_NJ_NL_dof(self):
        """Update NJ and NL values.
        
        If user don't want to keep the DOF:
        Change the DOF then exit.
        """
        if not self.keep_dof.isChecked():
            self.DOF.setValue(
                3 * (self.NL_input.value() - 1) -
                2 * self.NJ_input.value()
            )
            return
        """Prepare the input value.
        
        + N2: Get the user's adjusted value.
        + NL_func: Get the another value of parameters (N1) by
            degrees of freedom formula.
        + is_above: Is value increase or decrease?
        """
        if self.sender() == self.NJ_input:
            N2 = self.NJ_input.value()
            NL_func = lambda: float(((self.DOF.value() + 2*N2) / 3) + 1)
            is_above = N2 > self.NJ_input_old_value
        else:
            N2 = self.NL_input.value()
            NL_func = lambda: float((3*(N2-1) - self.DOF.value()) / 2)
            is_above = N2 > self.NL_input_old_value
        N1 = NL_func()
        while not N1.is_integer():
            N2 += 1 if is_above else -1
            N1 = NL_func()
            if (N1 == 0) or (N2 == 0):
                break
        """Return the result values.
        
        + Value of widgets.
        + Setting old value record.
        """
        if self.sender() == self.NL_input:
            self.NJ_input.setValue(N1)
            self.NL_input.setValue(N2)
            self.NJ_input_old_value = N1
            self.NL_input_old_value = N2
        else:
            self.NJ_input.setValue(N2)
            self.NL_input.setValue(N1)
            self.NJ_input_old_value = N2
            self.NL_input_old_value = N1
    
    @pyqtSlot()
    def on_Combine_number_clicked(self):
        """Show number of links with different number of joints."""
        self.Expression_number.clear()
        NS_result = NumberSynthesis(self.NL_input.value(), self.NJ_input.value())
        if type(NS_result) == str:
            item = QListWidgetItem(NS_result)
            item.links = None
            self.Expression_number.addItem(item)
        else:
            for result in NS_result:
                item = QListWidgetItem(", ".join(
                    "NL{} = {}".format(i+2, result[i])
                    for i in range(len(result))
                ))
                item.links = result
                self.Expression_number.addItem(item)
        self.Expression_number.setCurrentRow(0)
    
    @pyqtSlot()
    def on_Combine_type_clicked(self):
        """Type synthesis.
        
        If there has no data of number synthesis,
        execute number synthesis first.
        """
        row = self.Expression_number.currentRow()
        if not row>-1:
            self.on_Combine_number_clicked()
            row = self.Expression_number.currentRow()
        if self.Expression_number.currentItem() is None:
            return
        answer = self.combineType(row)
        if answer:
            self.answer = answer
            self.on_reload_atlas_clicked()
    
    @pyqtSlot()
    def on_Combine_type_all_clicked(self):
        """Type synthesis - find all.
        
        If the data of number synthesis has multiple results,
        execute type synthesis one by one.
        """
        if not self.Expression_number.currentRow()>-1:
            self.on_Combine_number_clicked()
        if self.Expression_number.currentItem().links is None:
            return
        answers = []
        break_point = False
        for row in range(self.Expression_number.count()):
            answer = self.combineType(row)
            if answer:
                answers += answer
            else:
                break_point = True
                break
        if not answers:
            return
        if break_point:
            reply = QMessageBox.question(self,
                "Type synthesis - abort",
                "Do you want to keep the results?"
            )
            if reply != QMessageBox.Yes:
                return
        self.answer = answers
        self.on_reload_atlas_clicked()
    
    def combineType(self, row: int):
        """Combine and show progress dialog."""
        item = self.Expression_number.item(row)
        progdlg = QProgressDialog(
            "Analysis of the topology...",
            "Cancel",
            0,
            100,
            self
        )
        progdlg.setWindowTitle("Type synthesis - ({})".format(item.text()))
        progdlg.setMinimumSize(QSize(500, 120))
        progdlg.setModal(True)
        progdlg.show()
        #Call in every loop.
        def stopFunc():
            QCoreApplication.processEvents()
            progdlg.setValue(progdlg.value() + 1)
            return progdlg.wasCanceled()
        def setjobFunc(job, maximum):
            progdlg.setLabelText(job)
            progdlg.setValue(0)
            progdlg.setMaximum(maximum+1)
        answer, time = topo(
            item.links,
            not self.graph_degenerate.isChecked(),
            setjobFunc,
            stopFunc
        )
        self.time_label.setText("{}[min] {:.2f}[s]".format(
            int(time // 60),
            time % 60
        ))
        progdlg.setValue(progdlg.maximum())
        if answer:
            return [Graph(G.edges) for G in answer]
    
    @pyqtSlot()
    @pyqtSlot(str)
    def on_reload_atlas_clicked(self, p0=None):
        """Reload the atlas. Regardless there has any old data."""
        self.engine = self.graph_engine.currentText().split(" - ")[1]
        self.Topologic_result.clear()
        if self.answer:
            progdlg = QProgressDialog(
                "Drawing atlas...",
                "Cancel",
                0,
                len(self.answer),
                self
            )
            progdlg.setWindowTitle("Type synthesis")
            progdlg.resize(400, progdlg.height())
            progdlg.setModal(True)
            progdlg.show()
            for i, G in enumerate(self.answer):
                QCoreApplication.processEvents()
                if progdlg.wasCanceled():
                    return
                if self.drawAtlas(i, G):
                    progdlg.setValue(i+1)
                else:
                    break
            progdlg.setValue(progdlg.maximum())
    
    def drawAtlas(self, i: int, G: Graph) -> bool:
        """Draw atlas and return True if done."""
        item = QListWidgetItem("No. {}".format(i + 1))
        try:
            item.setIcon(graph(
                G,
                self.Topologic_result.iconSize().width(),
                self.engine,
                self.graph_link_as_node.isChecked()
            ))
        except EngineError as e:
            QMessageBox.warning(self,
                str(e),
                "Please install and make sure Graphviz is working."
            )
            return False
        else:
            item.setToolTip(str(G.edges))
            self.Topologic_result.addItem(item)
            return True
    
    def atlas_image(self, row: int =None) -> QImage:
        """Capture a result item icon to image."""
        w = self.Topologic_result
        if row is None:
            item = w.currentItem()
        else:
            item = w.item(row)
        return item.icon().pixmap(w.iconSize()).toImage()
    
    @pyqtSlot(QPoint)
    def Topologic_result_context_menu(self, point):
        """Context menu for the type synthesis results."""
        index = self.Topologic_result.currentIndex().row()
        self.add_collection.setEnabled(index>-1)
        self.copy_edges.setEnabled(index>-1)
        self.copy_image.setEnabled(index>-1)
        action = self.popMenu_topo.exec_(self.Topologic_result.mapToGlobal(point))
        if not action:
            return
        clipboard = QApplication.clipboard()
        if action==self.add_collection:
            self.addCollection(self.answer[index].edges)
        elif action==self.copy_edges:
            clipboard.setText(str(self.answer[index].edges))
        elif action==self.copy_image:
            #Turn the transparent background to white.
            image1 = self.atlas_image()
            image2 = QImage(image1.size(), image1.format())
            image2.fill(QColor(Qt.white).rgb())
            painter = QPainter(image2)
            painter.drawImage(QPointF(0, 0), image1)
            painter.end()
            pixmap = QPixmap()
            pixmap.convertFromImage(image2)
            clipboard.setPixmap(pixmap)
    
    @pyqtSlot()
    def on_Expression_copy_clicked(self):
        """Copy expression button."""
        string = self.Expression_edges.text()
        if string:
            QApplication.clipboard().setText(string)
            self.Expression_edges.selectAll()
    
    @pyqtSlot()
    def on_Expression_add_collection_clicked(self):
        """Add this expression to collections widget."""
        string = self.Expression_edges.text()
        if string:
            self.addCollection(eval(string))
    
    @pyqtSlot()
    def on_save_atlas_clicked(self):
        """Saving all the atlas to image file.
        
        We should turn transparent background to white first.
        Then using QImage class to merge into one image.
        """
        fileName = ""
        lateral = 0
        if self.save_edges_auto.isChecked():
            lateral, ok = QInputDialog.getInt(self,
                "Atlas",
                "The number of lateral:",
                5, 1, 10
            )
            if not ok:
                return
            fileName = self.outputTo("Atlas image", Qt_images)
            if fileName:
                reply = QMessageBox.question(self,
                    "Type synthesis",
                    "Do you want to Re-synthesis?",
                    (QMessageBox.Yes | QMessageBox.YesToAll | QMessageBox.Cancel),
                    QMessageBox.YesToAll
                )
                if reply == QMessageBox.Yes:
                    self.on_Combine_type_clicked()
                elif reply == QMessageBox.YesToAll:
                    self.on_Combine_type_all_clicked()
        count = self.Topologic_result.count()
        if not count:
            return
        if not lateral:
            lateral, ok = QInputDialog.getInt(self,
                "Atlas",
                "The number of lateral:",
                5, 1, 10
            )
        if not ok:
            return
        if not fileName:
            fileName = self.outputTo("Atlas image", Qt_images)
        if not fileName:
            return
        width = self.Topologic_result.iconSize().width()
        image_main = QImage(
            QSize(
                lateral * width if count>lateral else count * width,
                ((count // lateral) + bool(count % lateral)) * width
            ),
            self.atlas_image(0).format()
        )
        image_main.fill(QColor(Qt.white).rgb())
        painter = QPainter(image_main)
        for row in range(count):
            image = self.atlas_image(row)
            painter.drawImage(QPointF(
                row % lateral * width,
                row // lateral * width
            ), image)
        painter.end()
        pixmap = QPixmap()
        pixmap.convertFromImage(image_main)
        pixmap.save(fileName, format=QFileInfo(fileName).suffix())
        self.saveReplyBox("Atlas", fileName)
    
    @pyqtSlot()
    def on_save_edges_clicked(self):
        """Saving all the atlas to text file."""
        fileName = ""
        if self.save_edges_auto.isChecked():
            fileName = self.outputTo(
                "Atlas edges expression",
                ["Text file (*.txt)"]
            )
            if not fileName:
                return
            reply = QMessageBox.question(self,
                "Type synthesis",
                "Do you want to Re-synthesis?",
                (QMessageBox.Yes | QMessageBox.YesToAll | QMessageBox.Cancel),
                QMessageBox.YesToAll
            )
            if reply == QMessageBox.Yes:
                self.on_Combine_type_clicked()
            elif reply == QMessageBox.YesToAll:
                self.on_Combine_type_all_clicked()
        count = self.Topologic_result.count()
        if not count:
            return
        if not fileName:
            fileName = self.outputTo(
                "Atlas edges expression",
                ["Text file (*.txt)"]
            )
        if not fileName:
            return
        with open(fileName, 'w') as f:
            f.write('\n'.join(str(G.edges) for G in self.answer))
        self.saveReplyBox("edges expression", fileName)
    
    @pyqtSlot()
    def on_Edges_to_altas_clicked(self):
        """Turn the text files into a atlas image.
        
        This opreation will load all edges to list widget first.
        """
        fileNames = self.inputFrom(
            "Edges data",
            ["Text File (*.txt)"],
            multiple=True
        )
        if not fileNames:
            return
        read_data = []
        for fileName in fileNames:
            with open(fileName, 'r') as f:
                read_data += f.read().split('\n')
        answer = []
        for edges in read_data:
            try:
                answer.append(Graph(eval(edges)))
            except:
                QMessageBox.warning(self,
                    "Wrong format",
                    "Please check the edges text format."
                )
                return
        if not answer:
            return
        self.answer = answer
        self.on_reload_atlas_clicked()
        check_status = self.save_edges_auto.isChecked()
        self.save_edges_auto.setChecked(False)
        self.on_save_atlas_clicked()
        self.save_edges_auto.setChecked(check_status)
Beispiel #3
0
class StructureSynthesis(QWidget, Ui_Form):
    """Number and type synthesis widget.

    Calculate the combinations of mechanism family and show the atlas.
    """
    def __init__(self, parent: 'mw.MainWindow'):
        """Reference names:

        + IO functions from main window.
        + Table data from PMKS expression.
        + Graph data function from main window.
        """
        super(StructureSynthesis, self).__init__(parent)
        self.setupUi(self)
        self.save_edges_auto_label.setStatusTip(
            self.save_edges_auto.statusTip())

        # Function references
        self.outputTo = parent.outputTo
        self.saveReplyBox = parent.saveReplyBox
        self.inputFrom = parent.inputFrom
        self.jointDataFunc = parent.EntitiesPoint.dataTuple
        self.linkDataFunc = parent.EntitiesLink.dataTuple
        self.getGraph = parent.getGraph

        # Splitters
        self.splitter.setStretchFactor(0, 2)
        self.splitter.setStretchFactor(1, 15)

        # Answer list.
        self.answer: List[Graph] = []

        # Signals
        self.NL_input.valueChanged.connect(self.__adjust_structure_data)
        self.NJ_input.valueChanged.connect(self.__adjust_structure_data)
        self.graph_engine.addItems(engines)
        self.structure_list.customContextMenuRequested.connect(
            self.__topologic_result_context_menu)
        """Context menu

        + Add to collections
        + Copy edges
        + Copy image
        """
        self.pop_menu_topo = QMenu(self)
        self.add_collection = QAction(
            QIcon(QPixmap(":/icons/collections.png")), "Add to collections",
            self)
        self.copy_edges = QAction("Copy edges", self)
        self.copy_image = QAction("Copy image", self)
        self.pop_menu_topo.addActions(
            [self.add_collection, self.copy_edges, self.copy_image])

        self.NL_input_old_value = 0
        self.NJ_input_old_value = 0
        self.clear()

    def clear(self):
        """Clear all sub-widgets."""
        self.answer.clear()
        self.edges_text.clear()
        self.l_a_list.clear()
        self.__clear_structure_list()
        self.NL_input.setValue(0)
        self.NJ_input.setValue(0)
        self.NL_input_old_value = 0
        self.NJ_input_old_value = 0
        self.DOF.setValue(1)

    @pyqtSlot(name='on_structure_list_clear_button_clicked')
    def __clear_structure_list(self):
        """Clear the structure list."""
        self.structure_list.clear()
        self.time_label.setText("")

    @pyqtSlot(name='on_from_mechanism_button_clicked')
    def __from_mechanism(self):
        """Reload button: Auto-combine the mechanism from the workbook."""
        joint_data = self.jointDataFunc()
        link_data = self.linkDataFunc()
        if joint_data and link_data:
            graph = Graph(self.getGraph())
            self.edges_text.setText(str(graph.edges))
        else:
            graph = Graph([])
            self.edges_text.setText("")
        keep_dof_checked = self.keep_dof.isChecked()
        self.keep_dof.setChecked(False)
        self.NL_input.setValue(
            sum(len(vlink.points) > 1 for vlink in link_data) + sum(
                len(vpoint.links) - 2 for vpoint in joint_data
                if (vpoint.type == VPoint.RP) and (len(vpoint.links) > 1)))
        self.NJ_input.setValue(
            sum((len(vpoint.links) - 1 + int(vpoint.type == VPoint.RP))
                for vpoint in joint_data if (len(vpoint.links) > 1)))
        self.keep_dof.setChecked(keep_dof_checked)

        # Auto synthesis.
        if not graph.edges:
            return
        self.l_a_list.setCurrentRow(
            compare_assortment(tuple(l_a(graph)), self.__l_a_synthesis()))
        self.c_l_a_list.setCurrentRow(
            compare_assortment(tuple(c_l_a(graph)), self.__c_l_a_synthesis()))

    def __adjust_structure_data(self):
        """Update NJ and NL values.

        If user don't want to keep the DOF:
        Change the DOF then exit.
        """
        if not self.keep_dof.isChecked():
            self.DOF.setValue(3 * (self.NL_input.value() - 1) -
                              2 * self.NJ_input.value())
            return
        """Prepare the input value.

        + N2: Get the user's adjusted value.
        + NL_func: Get the another value of parameters (N1) by
            degrees of freedom formula.
        + is_above: Is value increase or decrease?
        """
        if self.sender() == self.NJ_input:
            n2 = self.NJ_input.value()

            def nl_func() -> float:
                return ((self.DOF.value() + 2 * n2) / 3) + 1

            is_above = n2 > self.NJ_input_old_value
        else:
            n2 = self.NL_input.value()

            def nl_func() -> float:
                return (3 * (n2 - 1) - self.DOF.value()) / 2

            is_above = n2 > self.NL_input_old_value
        n1 = nl_func()
        while not n1.is_integer():
            n2 += 1 if is_above else -1
            n1 = nl_func()
            if (n1 == 0) or (n2 == 0):
                break
        """Return the result values.

        + Value of widgets.
        + Setting old value record.
        """
        if self.sender() == self.NL_input:
            self.NJ_input.setValue(n1)
            self.NL_input.setValue(n2)
            self.NJ_input_old_value = n1
            self.NL_input_old_value = n2
        else:
            self.NJ_input.setValue(n2)
            self.NL_input.setValue(n1)
            self.NJ_input_old_value = n2
            self.NL_input_old_value = n1

    @pyqtSlot(name='on_number_synthesis_button_clicked')
    def __l_a_synthesis(self) -> List[Tuple[int, ...]]:
        """Synthesis of link assortments."""
        self.l_a_list.clear()
        self.c_l_a_list.clear()
        try:
            results = number_synthesis(self.NL_input.value(),
                                       self.NJ_input.value())
        except Exception as e:
            item = QListWidgetItem(str(e))
            self.l_a_list.addItem(item)
            return []
        else:
            for result in results:
                self.l_a_list.addItem(
                    QListWidgetItem(", ".join(f"NL{i + 2} = {result[i]}"
                                              for i in range(len(result)))))
            self.l_a_list.setCurrentRow(0)
            return results

    @pyqtSlot(int, name='on_l_a_list_currentRowChanged')
    def __c_l_a_synthesis(self, index: int = 0) -> List[Tuple[int, ...]]:
        """Synthesis of contracted link assortments."""
        self.c_l_a_list.clear()
        item = self.l_a_list.item(index)
        if item is None:
            return []
        results = contracted_link(_link_assortments(item.text()))
        for c_j in results:
            self.c_l_a_list.addItem(
                QListWidgetItem(", ".join(f"Nc{i + 1} = {c_j[i]}"
                                          for i in range(len(c_j)))))
        self.c_l_a_list.setCurrentRow(0)
        return results

    def __set_time_count(self, t: float, count: int):
        """Set time and count digit to label."""
        self.time_label.setText(f"{t:.04f} s ({count})")

    @pyqtSlot(name='on_structure_synthesis_button_clicked')
    def __structure_synthesis(self):
        """Structural synthesis - find by contracted links."""
        self.__clear_structure_list()
        row = self.l_a_list.currentRow()
        if row == -1:
            self.__l_a_synthesis()
            self.__c_l_a_synthesis()
        item_l_a: QListWidgetItem = self.l_a_list.currentItem()
        item_c_l_a: QListWidgetItem = self.c_l_a_list.currentItem()
        try:
            job_l_a = _link_assortments(item_l_a.text())
            job_c_l_a = _link_assortments(item_c_l_a.text())
        except ValueError:
            return

        self.__structural_combine([(job_l_a, job_c_l_a)], 1)

    @pyqtSlot(name='on_structure_synthesis_links_button_clicked')
    def __structure_synthesis_links(self):
        """Structural synthesis - find by links."""
        self.__clear_structure_list()
        row = self.l_a_list.currentRow()
        if row == -1:
            self.__l_a_synthesis()
            self.__c_l_a_synthesis()
        item_l_a: QListWidgetItem = self.l_a_list.currentItem()
        try:
            job_l_a = _link_assortments(item_l_a.text())
        except ValueError:
            return

        jobs = contracted_link(job_l_a)

        def jobs_iterator(
            _l_a: Sequence[int], _jobs: Sequence[Sequence[int]]
        ) -> Iterator[Tuple[Sequence[int], Sequence[int]]]:
            for _c_l_a in _jobs:
                yield _l_a, _c_l_a

        self.__structural_combine(jobs_iterator(job_l_a, jobs), len(jobs))

    @pyqtSlot(name='on_structure_synthesis_all_button_clicked')
    def __structure_synthesis_all(self):
        """Structural synthesis - find all."""
        self.__clear_structure_list()
        if self.l_a_list.currentRow() == -1:
            self.__l_a_synthesis()
        item: QListWidgetItem = self.c_l_a_list.currentItem()
        try:
            _link_assortments(item.text())
        except ValueError:
            return

        job_count = 0
        jobs = []
        for row in range(self.l_a_list.count()):
            item: QListWidgetItem = self.l_a_list.item(row)
            job_l_a = _link_assortments(item.text())
            job_c_l_as = contracted_link(job_l_a)
            job_count += len(job_c_l_as)
            jobs.append((job_l_a, job_c_l_as))

        def jobs_iterator(
            _jobs: Sequence[Tuple[Sequence[int], Sequence[Sequence[int]]]]
        ) -> Iterator[Tuple[Sequence[int], Sequence[int]]]:
            for _l_a, _c_l_as in _jobs:
                for _c_l_a in _c_l_as:
                    yield _l_a, _c_l_a

        self.__structural_combine(jobs_iterator(jobs), job_count)

    def __structural_combine(self, jobs: Iterable[Tuple[Sequence[int],
                                                        Sequence[int]]],
                             job_count: int):
        """Structural combine by iterator."""
        dlg = SynthesisProgressDialog("Structural Synthesis", "", job_count,
                                      self)
        dlg.show()

        answers = []
        break_point = False
        t0 = 0.
        c0 = 0
        for job_l_a, job_c_l_a in jobs:
            answer, t1 = topo(job_l_a, job_c_l_a,
                              self.graph_degenerate.currentIndex(),
                              dlg.stop_func)
            dlg.next()
            if answer is not None:
                answers.extend(answer)
                t0 += t1
                c0 += len(answer)
            else:
                break_point = True
                break

        if not answers:
            return

        if break_point:
            reply = QMessageBox.question(self, "Type synthesis - abort",
                                         "Do you want to keep the results?")
            if reply != QMessageBox.Yes:
                return

        # Save the answer list.
        self.answer = answers
        self.__set_time_count(t0, c0)
        self.__reload_atlas()

    @pyqtSlot(name='on_graph_link_as_node_clicked')
    @pyqtSlot(name='on_reload_atlas_clicked')
    @pyqtSlot(int, name='on_graph_engine_currentIndexChanged')
    def __reload_atlas(self, *_: int):
        """Reload the atlas."""
        scroll_bar: QScrollBar = self.structure_list.verticalScrollBar()
        scroll_pos = scroll_bar.sliderPosition()
        self.structure_list.clear()

        if not self.answer:
            return

        dlg = SynthesisProgressDialog("Type synthesis", "Drawing atlas...",
                                      len(self.answer), self)
        dlg.show()
        for i, G in enumerate(self.answer):
            QCoreApplication.processEvents()
            if dlg.wasCanceled():
                return
            if self.__draw_atlas(i, G):
                dlg.setValue(i + 1)
            else:
                break
        dlg.setValue(dlg.maximum())
        scroll_bar.setSliderPosition(scroll_pos)

    def __draw_atlas(self, i: int, g: Graph) -> bool:
        """Draw atlas and return True if done."""
        item = QListWidgetItem(f"No. {i + 1}")
        item.setIcon(
            to_graph(g,
                     self.structure_list.iconSize().width(),
                     self.graph_engine.currentText(),
                     self.graph_link_as_node.isChecked()))
        item.setToolTip(f"Edge Set: {list(g.edges)}\n"
                        f"Link Assortments: {l_a(g)}\n"
                        f"Contracted Link Assortments: {c_l_a(g)}")
        self.structure_list.addItem(item)
        return True

    def __atlas_image(self, row: int = None) -> QImage:
        """Capture a result item icon to image."""
        w = self.structure_list
        if row is None:
            item = w.currentItem()
        else:
            item = w.item(row)
        return item.icon().pixmap(w.iconSize()).toImage()

    @pyqtSlot(QPoint)
    def __topologic_result_context_menu(self, point):
        """Context menu for the type synthesis results."""
        index = self.structure_list.currentIndex().row()
        self.add_collection.setEnabled(index > -1)
        self.copy_edges.setEnabled(index > -1)
        self.copy_image.setEnabled(index > -1)
        action = self.pop_menu_topo.exec_(
            self.structure_list.mapToGlobal(point))
        if not action:
            return
        clipboard = QApplication.clipboard()
        if action == self.add_collection:
            self.addCollection(self.answer[index].edges)
        elif action == self.copy_edges:
            clipboard.setText(str(self.answer[index].edges))
        elif action == self.copy_image:
            # Turn the transparent background to white.
            image1 = self.__atlas_image()
            image2 = QImage(image1.size(), image1.format())
            image2.fill(QColor(Qt.white).rgb())
            painter = QPainter(image2)
            painter.drawImage(QPointF(0, 0), image1)
            painter.end()
            pixmap = QPixmap()
            pixmap.convertFromImage(image2)
            clipboard.setPixmap(pixmap)

    @pyqtSlot(name='on_expr_copy_clicked')
    def __copy_expr(self):
        """Copy expression button."""
        string = self.edges_text.text()
        if string:
            QApplication.clipboard().setText(string)
            self.edges_text.selectAll()

    @pyqtSlot(name='on_expr_add_collection_clicked')
    def __add_collection(self):
        """Add this expression to collections widget."""
        string = self.edges_text.text()
        if string:
            self.addCollection(eval(string))

    @pyqtSlot(name='on_save_atlas_clicked')
    def __save_atlas(self):
        """Saving all the atlas to image file.

        We should turn transparent background to white first.
        Then using QImage class to merge into one image.
        """
        file_name = ""
        lateral = 0
        if self.save_edges_auto.isChecked():
            lateral, ok = QInputDialog.getInt(self, "Atlas",
                                              "The number of lateral:", 5, 1,
                                              10)
            if not ok:
                return
            file_name = self.outputTo("Atlas image", qt_image_format)
            if file_name:
                reply = QMessageBox.question(
                    self, "Type synthesis", "Do you want to Re-synthesis?",
                    (QMessageBox.Yes | QMessageBox.YesToAll
                     | QMessageBox.Cancel), QMessageBox.Yes)
                if reply == QMessageBox.Yes:
                    self.__structure_synthesis()
                elif reply == QMessageBox.YesToAll:
                    self.__structure_synthesis_all()
        count = self.structure_list.count()
        if not count:
            return
        if not lateral:
            lateral, ok = QInputDialog.getInt(self, "Atlas",
                                              "The number of lateral:", 5, 1,
                                              10)
            if not ok:
                return
        if not file_name:
            file_name = self.outputTo("Atlas image", qt_image_format)
        if not file_name:
            return
        width = self.structure_list.iconSize().width()
        image_main = QImage(
            QSize(lateral * width if count > lateral else count * width,
                  ((count // lateral) + bool(count % lateral)) * width),
            self.__atlas_image(0).format())
        image_main.fill(QColor(Qt.white).rgb())
        painter = QPainter(image_main)
        for row in range(count):
            image = self.__atlas_image(row)
            painter.drawImage(
                QPointF(row % lateral * width, row // lateral * width), image)
        painter.end()
        pixmap = QPixmap()
        pixmap.convertFromImage(image_main)
        pixmap.save(file_name, format=QFileInfo(file_name).suffix())
        self.saveReplyBox("Atlas", file_name)

    @pyqtSlot(name='on_save_edges_clicked')
    def __save_edges(self):
        """Saving all the atlas to text file."""
        file_name = ""
        if self.save_edges_auto.isChecked():
            file_name = self.outputTo("Atlas edges expression",
                                      ["Text file (*.txt)"])
            if not file_name:
                return
            reply = QMessageBox.question(
                self, "Type synthesis", "Do you want to Re-synthesis?",
                (QMessageBox.Yes | QMessageBox.YesToAll | QMessageBox.Cancel),
                QMessageBox.Yes)
            if reply == QMessageBox.Yes:
                self.__structure_synthesis()
            elif reply == QMessageBox.YesToAll:
                self.__structure_synthesis_all()
        count = self.structure_list.count()
        if not count:
            return
        if not file_name:
            file_name = self.outputTo("Atlas edges expression",
                                      ["Text file (*.txt)"])
        if not file_name:
            return
        with open(file_name, 'w') as f:
            f.write('\n'.join(str(G.edges) for G in self.answer))
        self.saveReplyBox("edges expression", file_name)

    @pyqtSlot(name='on_edges2atlas_button_clicked')
    def __edges2atlas(self):
        """Turn the text files into a atlas image.

        This operation will load all edges to list widget first.
        """
        file_names = self.inputFrom("Edges data", ["Text file (*.txt)"],
                                    multiple=True)
        if not file_names:
            return
        read_data = []

        for file_name in file_names:
            with open(file_name) as f:
                for line in f:
                    read_data.append(line)

        answer = []
        for edges in read_data:
            try:
                g = Graph(eval(edges))
            except (SyntaxError, TypeError):
                QMessageBox.warning(self, "Wrong format",
                                    "Please check text format.")
            else:
                answer.append(g)

        if not answer:
            QMessageBox.information(self, "No data",
                                    "The graph data is empty.")
            return

        self.answer = answer
        self.__reload_atlas()
        self.save_edges_auto.setChecked(False)
        self.__save_atlas()
        self.save_edges_auto.setChecked(self.save_edges_auto.isChecked())
Beispiel #4
0
class InputsWidget(QWidget, Ui_Form):
    """There has following functions:
    
    + Function of mechanism variables settings.
    + Path recording.
    """
    def __init__(self, parent):
        super(InputsWidget, self).__init__(parent)
        self.setupUi(self)
        #parent's pointer.
        self.freemode_button = parent.freemode_button
        self.EntitiesPoint = parent.EntitiesPoint
        self.EntitiesLink = parent.EntitiesLink
        self.MainCanvas = parent.MainCanvas
        self.resolve = parent.resolve
        self.reloadCanvas = parent.reloadCanvas
        self.outputTo = parent.outputTo
        self.ConflictGuide = parent.ConflictGuide
        self.DOF = lambda: parent.DOF
        self.rightInput = parent.rightInput
        self.CommandStack = parent.CommandStack
        #self widgets.
        self.dial = QDial()
        self.dial.setEnabled(False)
        self.dial.valueChanged.connect(self.__updateVar)
        self.dial_spinbox.valueChanged.connect(self.__setVar)
        self.inputs_dial_layout.addWidget(RotatableView(self.dial))
        self.variable_stop.clicked.connect(self.variableValueReset)
        self.inputs_playShaft = QTimer(self)
        self.inputs_playShaft.setInterval(10)
        self.inputs_playShaft.timeout.connect(self.__changeIndex)
        self.variable_list.currentRowChanged.connect(self.__dialOk)
        '''Inputs record context menu
        
        + Copy data from Point{}
        + ...
        '''
        self.record_list.customContextMenuRequested.connect(
            self.on_record_list_context_menu)
        self.popMenu_record_list = QMenu(self)
        self.pathData = {}

    def clear(self):
        self.pathData.clear()
        for i in range(self.record_list.count() - 1):
            self.record_list.takeItem(1)
        self.variable_list.clear()

    @pyqtSlot(tuple)
    def setSelection(self, selections):
        """Set one selection from canvas."""
        self.joint_list.setCurrentRow(selections[0] if selections[0] in self.
                                      EntitiesPoint.selectedRows() else -1)

    @pyqtSlot()
    def clearSelection(self):
        """Clear the points selection."""
        self.joint_list.setCurrentRow(-1)

    @pyqtSlot(int)
    def on_joint_list_currentRowChanged(self, row: int):
        """Change the point row from input widget."""
        self.base_link_list.clear()
        if not row > -1:
            return
        if row not in self.EntitiesPoint.selectedRows():
            self.EntitiesPoint.setSelections((row, ), False)
        for linkName in self.EntitiesPoint.item(row, 1).text().split(','):
            if not linkName:
                continue
            self.base_link_list.addItem(linkName)

    @pyqtSlot(int)
    def on_base_link_list_currentRowChanged(self, row: int):
        """Set the drive links from base link."""
        self.drive_link_list.clear()
        if not row > -1:
            return
        inputs_point = self.joint_list.currentRow()
        linkNames = self.EntitiesPoint.item(inputs_point, 1).text().split(',')
        for linkName in linkNames:
            if linkName == self.base_link_list.currentItem().text():
                continue
            self.drive_link_list.addItem(linkName)

    @pyqtSlot(int)
    def on_drive_link_list_currentRowChanged(self, row: int):
        """Set enable of 'add variable' button."""
        if not row > -1:
            self.variable_list_add.setEnabled(False)
            return
        typeText = self.joint_list.currentItem().text().split()[0]
        self.variable_list_add.setEnabled(typeText == '[R]')

    @pyqtSlot()
    def on_variable_list_add_clicked(self):
        """Add inputs variable from click button."""
        self.__addInputsVariable(self.joint_list.currentRow(),
                                 self.base_link_list.currentItem().text(),
                                 self.drive_link_list.currentItem().text())

    def __addInputsVariable(self, point: int, base_link: str, drive_link: str):
        """Add variable with '->' sign."""
        if not self.DOF() > 0:
            return
        for vlink in self.EntitiesLink.data():
            if (vlink.name in {base_link, drive_link
                               }) and (len(vlink.points) < 2):
                return
        name = 'Point{}'.format(point)
        vars = [
            name, base_link, drive_link,
            "{:.02f}".format(self.__getLinkAngle(point, drive_link))
        ]
        for n, base, drive, a in self.getInputsVariables():
            if {base_link, drive_link} == {base, drive}:
                return
        self.CommandStack.beginMacro("Add variable of {}".format(name))
        self.CommandStack.push(AddVariable('->'.join(vars),
                                           self.variable_list))
        self.CommandStack.endMacro()

    def addInputsVariables(self, variables: Tuple[Tuple[int, str, str]]):
        """Add from database."""
        for variable in variables:
            self.__addInputsVariable(*variable)

    @pyqtSlot(int)
    def __dialOk(self, p0=None):
        """Set the angle of base link and drive link."""
        row = self.variable_list.currentRow()
        enabled = row > -1
        rotatable = (enabled and not self.freemode_button.isChecked()
                     and self.rightInput())
        self.dial.setEnabled(rotatable)
        self.dial_spinbox.setEnabled(rotatable)
        self.oldVar = self.dial.value() / 100.
        self.variable_play.setEnabled(rotatable)
        self.variable_speed.setEnabled(rotatable)
        self.dial.setValue(
            float(self.variable_list.currentItem().text().split('->')[-1]) *
            100 if enabled else 0)

    def variableExcluding(self, row: int = None):
        """Remove variable if the point was been deleted.
        
        Default: all.
        """
        one_row = row is not None
        for i, variable in enumerate(self.getInputsVariables()):
            row_ = variable[0]
            #If this is not origin point any more.
            if one_row and (row != row_):
                continue
            self.CommandStack.beginMacro(
                "Remove variable of Point{}".format(row))
            self.CommandStack.push(DeleteVariable(i, self.variable_list))
            self.CommandStack.endMacro()

    @pyqtSlot()
    def on_variable_remove_clicked(self):
        """Remove and reset angle."""
        row = self.variable_list.currentRow()
        if not row > -1:
            return
        reply = QMessageBox.question(self, "Remove variable",
                                     "Do you want to remove this variable?")
        if reply != QMessageBox.Yes:
            return
        self.variable_stop.click()
        self.CommandStack.beginMacro("Remove variable of Point{}".format(row))
        self.CommandStack.push(DeleteVariable(row, self.variable_list))
        self.CommandStack.endMacro()
        self.EntitiesPoint.getBackPosition()
        self.resolve()

    def __getLinkAngle(self, row: int, link: str) -> float:
        """Get the angle of base link and drive link."""
        points = self.EntitiesPoint.dataTuple()
        links = self.EntitiesLink.dataTuple()
        link_names = [vlink.name for vlink in links]
        relate = links[link_names.index(link)].points
        base = points[row]
        drive = points[relate[relate.index(row) - 1]]
        return base.slopeAngle(drive)

    def getInputsVariables(self) -> Tuple[int, str, str, float]:
        """A generator use to get variables.
        
        [0]: point num
        [1]: base link
        [2]: drive link
        [3]: angle
        """
        for row in range(self.variable_list.count()):
            variable = self.variable_list.item(row).text().split('->')
            variable[0] = int(variable[0].replace('Point', ''))
            variable[3] = float(variable[3])
            yield tuple(variable)

    def inputCount(self) -> int:
        """Use to show input variable count."""
        return self.variable_list.count()

    def inputPair(self) -> Tuple[int, int]:
        """Back as point number code."""
        vlinks = {
            vlink.name: set(vlink.points)
            for vlink in self.EntitiesLink.data()
        }
        for vars in self.getInputsVariables():
            points = vlinks[vars[2]].copy()
            points.remove(vars[0])
            yield (vars[0], points.pop())

    def variableReload(self):
        """Auto check the points and type."""
        self.joint_list.clear()
        for i in range(self.EntitiesPoint.rowCount()):
            text = "[{}] Point{}".format(
                self.EntitiesPoint.item(i, 2).text(), i)
            self.joint_list.addItem(text)
        self.variableValueReset()

    @pyqtSlot(float)
    def __setVar(self, value):
        self.dial.setValue(int(value % 360 * 100))

    @pyqtSlot(int)
    def __updateVar(self, value):
        """Update the value when rotating QDial."""
        item = self.variable_list.currentItem()
        value /= 100.
        self.dial_spinbox.setValue(value)
        if item:
            itemText = item.text().split('->')
            itemText[-1] = "{:.02f}".format(value)
            item.setText('->'.join(itemText))
            self.resolve()
        if (self.record_start.isChecked()
                and abs(self.oldVar - value) > self.record_interval.value()):
            self.MainCanvas.recordPath()
            self.oldVar = value

    def variableValueReset(self):
        """Reset the value of QDial."""
        if self.inputs_playShaft.isActive():
            self.variable_play.setChecked(False)
            self.inputs_playShaft.stop()
        self.EntitiesPoint.getBackPosition()
        for i, variable in enumerate(self.getInputsVariables()):
            point = variable[0]
            text = '->'.join([
                'Point{}'.format(point), variable[1], variable[2],
                "{:.02f}".format(self.__getLinkAngle(point, variable[2]))
            ])
            self.variable_list.item(i).setText(text)
        self.__dialOk()
        self.resolve()

    @pyqtSlot(bool)
    def on_variable_play_toggled(self, toggled):
        """Triggered when play button was changed."""
        self.dial.setEnabled(not toggled)
        self.dial_spinbox.setEnabled(not toggled)
        if toggled:
            self.inputs_playShaft.start()
        else:
            self.inputs_playShaft.stop()

    @pyqtSlot()
    def __changeIndex(self):
        """QTimer change index."""
        index = self.dial.value()
        speed = self.variable_speed.value()
        extremeRebound = (self.ConflictGuide.isVisible()
                          and self.extremeRebound.isChecked())
        if extremeRebound:
            speed *= -1
            self.variable_speed.setValue(speed)
        index += int(speed * 6 * (3 if extremeRebound else 1))
        index %= self.dial.maximum()
        self.dial.setValue(index)

    @pyqtSlot(bool)
    def on_record_start_toggled(self, toggled):
        """Save to file path data."""
        if toggled:
            self.MainCanvas.recordStart(int(360 /
                                            self.record_interval.value()))
            return
        path = self.MainCanvas.getRecordPath()
        name, ok = QInputDialog.getText(self, "Recording completed!",
                                        "Please input name tag:")
        if (not name) or (name in self.pathData):
            i = 0
            while "Record_{}".format(i) in self.pathData:
                i += 1
            QMessageBox.information(self, "Record",
                                    "The name tag is being used or empty.")
            name = "Record_{}".format(i)
        self.addPath(name, path)

    def addPath(self, name: str, path: Tuple[Tuple[float, float]]):
        """Add path function."""
        self.CommandStack.beginMacro("Add {{Path: {}}}".format(name))
        self.CommandStack.push(
            AddPath(self.record_list, name, self.pathData, path))
        self.CommandStack.endMacro()
        self.record_list.setCurrentRow(self.record_list.count() - 1)

    def loadPaths(self, paths: Tuple[Tuple[Tuple[float, float]]]):
        """Add multiple path."""
        for name, path in paths.items():
            self.addPath(name, path)

    @pyqtSlot()
    def on_record_remove_clicked(self):
        """Remove path data."""
        row = self.record_list.currentRow()
        if not row > 0:
            return
        self.CommandStack.beginMacro("Delete {{Path: {}}}".format(
            self.record_list.item(row).text()))
        self.CommandStack.push(DeletePath(row, self.record_list,
                                          self.pathData))
        self.CommandStack.endMacro()
        self.record_list.setCurrentRow(self.record_list.count() - 1)
        self.reloadCanvas()

    @pyqtSlot(QListWidgetItem)
    def on_record_list_itemDoubleClicked(self, item):
        """View path data."""
        name = item.text().split(":")[0]
        try:
            data = self.pathData[name]
        except KeyError:
            return
        reply = QMessageBox.question(
            self, "Path data", "This path data including {}.".format(", ".join(
                "Point{}".format(i) for i in range(len(data)) if data[i])),
            (QMessageBox.Save | QMessageBox.Close), QMessageBox.Close)
        if reply != QMessageBox.Save:
            return
        file_name = self.outputTo(
            "path data",
            ["Comma-Separated Values (*.csv)", "Text file (*.txt)"])
        if not file_name:
            return
        with open(file_name, 'w', newline='') as stream:
            writer = csv.writer(stream)
            for point in data:
                for coordinate in point:
                    writer.writerow(coordinate)
                writer.writerow(())
        print("Output path data: {}".format(file_name))

    @pyqtSlot(QPoint)
    def on_record_list_context_menu(self, point):
        """Show the context menu.
        
        Show path [0], [1], ...
        Or copy path coordinates.
        """
        row = self.record_list.currentRow()
        if row > -1:
            action = self.popMenu_record_list.addAction("Show all")
            action.index = -1
            name = self.record_list.item(row).text().split(":")[0]
            try:
                data = self.pathData[name]
            except KeyError:
                return
            for action_text in ("Show", "Copy data from"):
                self.popMenu_record_list.addSeparator()
                for i in range(len(data)):
                    if data[i]:
                        action = self.popMenu_record_list.addAction(
                            "{} Point{}".format(action_text, i))
                        action.index = i
        action = self.popMenu_record_list.exec_(
            self.record_list.mapToGlobal(point))
        if action:
            if "Copy data from" in action.text():
                QApplication.clipboard().setText('\n'.join(
                    "{},{}".format(x, y) for x, y in data[action.index]))
            elif "Show" in action.text():
                if action.index == -1:
                    self.record_show.setChecked(True)
                self.MainCanvas.setPathShow(action.index)
        self.popMenu_record_list.clear()

    @pyqtSlot()
    def on_record_show_clicked(self):
        """Show all paths or hide."""
        if self.record_show.isChecked():
            show = -1
        else:
            show = -2
        self.MainCanvas.setPathShow(show)

    @pyqtSlot(int)
    def on_record_list_currentRowChanged(self, row):
        """Reload the canvas when switch the path."""
        if self.record_show.isChecked():
            self.MainCanvas.setPathShow(-1)
        self.reloadCanvas()

    def currentPath(self):
        """Return current path data to main canvas.
        
        + No path.
        + Show path data.
        + Auto preview.
        """
        row = self.record_list.currentRow()
        if row == -1:
            self.MainCanvas.setAutoPath(False)
            return ()
        elif row > 0:
            self.MainCanvas.setAutoPath(False)
            name = self.record_list.item(row).text()
            return self.pathData.get(name.split(':')[0], ())
        elif row == 0:
            self.MainCanvas.setAutoPath(True)
            return ()
Beispiel #5
0
class InputsWidget(QWidget, Ui_Form):

    """There has following functions:

    + Function of mechanism variables settings.
    + Path recording.
    """

    aboutToResolve = pyqtSignal()

    def __init__(self, parent: 'mw.MainWindow'):
        super(InputsWidget, self).__init__(parent)
        self.setupUi(self)

        # parent's function pointer.
        self.free_move_button = parent.free_move_button
        self.EntitiesPoint = parent.EntitiesPoint
        self.EntitiesLink = parent.EntitiesLink
        self.MainCanvas = parent.MainCanvas
        self.solve = parent.solve
        self.reloadCanvas = parent.reloadCanvas
        self.outputTo = parent.outputTo
        self.conflict = parent.conflict
        self.DOF = lambda: parent.DOF
        self.rightInput = parent.rightInput
        self.CommandStack = parent.CommandStack
        self.setCoordsAsCurrent = parent.setCoordsAsCurrent

        # QDial: Angle panel.
        self.dial = QDial()
        self.dial.setStatusTip("Input widget of rotatable joint.")
        self.dial.setEnabled(False)
        self.dial.valueChanged.connect(self.__update_var)
        self.dial_spinbox.valueChanged.connect(self.__set_var)
        self.inputs_dial_layout.addWidget(RotatableView(self.dial))

        # QDial ok check.
        self.variable_list.currentRowChanged.connect(self.__dial_ok)

        # Play button.
        action = QShortcut(QKeySequence("F5"), self)
        action.activated.connect(self.variable_play.click)
        self.variable_stop.clicked.connect(self.variableValueReset)

        # Timer for play button.
        self.inputs_playShaft = QTimer(self)
        self.inputs_playShaft.setInterval(10)
        self.inputs_playShaft.timeout.connect(self.__change_index)

        # Change the point coordinates with current position.
        self.update_pos.clicked.connect(self.setCoordsAsCurrent)

        """Inputs record context menu
        
        + Copy data from Point0
        + Copy data from Point1
        + ...
        """
        self.pop_menu_record_list = QMenu(self)
        self.record_list.customContextMenuRequested.connect(
            self.__record_list_context_menu
        )
        self.__path_data: Dict[str, Sequence[Tuple[float, float]]] = {}

    def clear(self):
        """Clear function to reset widget status."""
        self.__path_data.clear()
        for i in range(self.record_list.count() - 1):
            self.record_list.takeItem(1)
        self.variable_list.clear()

    def __set_angle_mode(self):
        """Change to angle input."""
        self.dial.setMinimum(0)
        self.dial.setMaximum(36000)
        self.dial_spinbox.setMinimum(0)
        self.dial_spinbox.setMaximum(360)

    def __set_unit_mode(self):
        """Change to unit input."""
        self.dial.setMinimum(-50000)
        self.dial.setMaximum(50000)
        self.dial_spinbox.setMinimum(-500)
        self.dial_spinbox.setMaximum(500)

    def pathData(self):
        """Return current path data."""
        return self.__path_data

    @pyqtSlot(tuple)
    def setSelection(self, selections: Tuple[int]):
        """Set one selection from canvas."""
        self.joint_list.setCurrentRow(selections[0])

    @pyqtSlot()
    def clearSelection(self):
        """Clear the points selection."""
        self.driver_list.clear()
        self.joint_list.setCurrentRow(-1)

    @pyqtSlot(int, name='on_joint_list_currentRowChanged')
    def __update_relate_points(self, _: int):
        """Change the point row from input widget."""
        self.driver_list.clear()

        item: Optional[QListWidgetItem] = self.joint_list.currentItem()
        if item is None:
            return
        p0 = _variable_int(item.text())

        vpoints = self.EntitiesPoint.dataTuple()
        type_int = vpoints[p0].type
        if type_int == VPoint.R:
            for i, vpoint in enumerate(vpoints):
                if i == p0:
                    continue
                if vpoints[p0].same_link(vpoint):
                    if vpoints[p0].grounded() and vpoint.grounded():
                        continue
                    self.driver_list.addItem(f"[{vpoint.typeSTR}] Point{i}")
        elif type_int in {VPoint.P, VPoint.RP}:
            self.driver_list.addItem(f"[{vpoints[p0].typeSTR}] Point{p0}")

    @pyqtSlot(int, name='on_driver_list_currentRowChanged')
    def __set_add_var_enabled(self, _: int):
        """Set enable of 'add variable' button."""
        driver = self.driver_list.currentIndex()
        self.variable_add.setEnabled(driver != -1)

    @pyqtSlot(name='on_variable_add_clicked')
    def __add_inputs_variable(self, p0: Optional[int] = None, p1: Optional[int] = None):
        """Add variable with '->' sign."""
        if p0 is None:
            item: Optional[QListWidgetItem] = self.joint_list.currentItem()
            if item is None:
                return
            p0 = _variable_int(item.text())
        if p1 is None:
            item: Optional[QListWidgetItem] = self.driver_list.currentItem()
            if item is None:
                return
            p1 = _variable_int(item.text())

        # Check DOF.
        if self.DOF() <= self.inputCount():
            QMessageBox.warning(
                self,
                "Wrong DOF",
                "The number of variable must no more than degrees of freedom."
            )
            return

        # Check same link.
        vpoints = self.EntitiesPoint.dataTuple()
        if not vpoints[p0].same_link(vpoints[p1]):
            QMessageBox.warning(
                self,
                "Wrong pair",
                "The base point and driver point should at the same link."
            )
            return

        # Check repeated pairs.
        for p0_, p1_, a in self.inputPairs():
            if {p0, p1} == {p0_, p1_} and vpoints[p0].type == VPoint.R:
                QMessageBox.warning(
                    self,
                    "Wrong pair",
                    "There already have a same pair."
                )
                return

        name = f'Point{p0}'
        self.CommandStack.beginMacro(f"Add variable of {name}")
        if p0 == p1:
            # One joint by offset.
            value = vpoints[p0].true_offset()
        else:
            # Two joints by angle.
            value = vpoints[p0].slope_angle(vpoints[p1])
        self.CommandStack.push(AddVariable('->'.join((
            name,
            f'Point{p1}',
            f"{value:.02f}",
        )), self.variable_list))
        self.CommandStack.endMacro()

    def addInputsVariables(self, variables: Sequence[Tuple[int, int]]):
        """Add from database."""
        for p0, p1 in variables:
            self.__add_inputs_variable(p0, p1)

    @pyqtSlot()
    def __dial_ok(self):
        """Set the angle of base link and drive link."""
        row = self.variable_list.currentRow()
        enabled = row > -1
        rotatable = (
            enabled and
            not self.free_move_button.isChecked() and
            self.rightInput()
        )
        self.dial.setEnabled(rotatable)
        self.dial_spinbox.setEnabled(rotatable)
        self.oldVar = self.dial.value() / 100.
        self.variable_play.setEnabled(rotatable)
        self.variable_speed.setEnabled(rotatable)
        item: Optional[QListWidgetItem] = self.variable_list.currentItem()
        if item is None:
            return
        expr = item.text().split('->')
        p0 = int(expr[0].replace('Point', ''))
        p1 = int(expr[1].replace('Point', ''))
        value = float(expr[2])
        if p0 == p1:
            self.__set_unit_mode()
        else:
            self.__set_angle_mode()
        self.dial.setValue(value * 100 if enabled else 0)

    def variableExcluding(self, row: Optional[int] = None):
        """Remove variable if the point was been deleted. Default: all."""
        one_row: bool = row is not None
        for i, (b, d, a) in enumerate(self.inputPairs()):
            # If this is not origin point any more.
            if one_row and (row != b):
                continue
            self.CommandStack.beginMacro(f"Remove variable of Point{row}")
            self.CommandStack.push(DeleteVariable(i, self.variable_list))
            self.CommandStack.endMacro()

    @pyqtSlot(name='on_variable_remove_clicked')
    def __remove_var(self):
        """Remove and reset angle."""
        row = self.variable_list.currentRow()
        if not row > -1:
            return
        reply = QMessageBox.question(
            self,
            "Remove variable",
            "Do you want to remove this variable?"
        )
        if reply != QMessageBox.Yes:
            return
        self.variable_stop.click()
        self.CommandStack.beginMacro(f"Remove variable of Point{row}")
        self.CommandStack.push(DeleteVariable(row, self.variable_list))
        self.CommandStack.endMacro()
        self.EntitiesPoint.getBackPosition()
        self.solve()

    def interval(self) -> float:
        """Return interval value."""
        return self.record_interval.value()

    def inputCount(self) -> int:
        """Use to show input variable count."""
        return self.variable_list.count()

    def inputPairs(self) -> Iterator[Tuple[int, int, float]]:
        """Back as point number code."""
        for row in range(self.variable_list.count()):
            var = self.variable_list.item(row).text().split('->')
            p0 = int(var[0].replace('Point', ''))
            p1 = int(var[1].replace('Point', ''))
            angle = float(var[2])
            yield (p0, p1, angle)

    def variableReload(self):
        """Auto check the points and type."""
        self.joint_list.clear()
        for i in range(self.EntitiesPoint.rowCount()):
            type_text = self.EntitiesPoint.item(i, 2).text()
            self.joint_list.addItem(f"[{type_text}] Point{i}")
        self.variableValueReset()

    @pyqtSlot(float)
    def __set_var(self, value: float):
        self.dial.setValue(int(value * 100 % self.dial.maximum()))

    @pyqtSlot(int)
    def __update_var(self, value: int):
        """Update the value when rotating QDial."""
        item = self.variable_list.currentItem()
        value /= 100.
        self.dial_spinbox.blockSignals(True)
        self.dial_spinbox.setValue(value)
        self.dial_spinbox.blockSignals(False)
        if item:
            item_text = item.text().split('->')
            item_text[-1] = f"{value:.02f}"
            item.setText('->'.join(item_text))
            self.aboutToResolve.emit()
        if (
            self.record_start.isChecked() and
            abs(self.oldVar - value) > self.record_interval.value()
        ):
            self.MainCanvas.recordPath()
            self.oldVar = value

    def variableValueReset(self):
        """Reset the value of QDial."""
        if self.inputs_playShaft.isActive():
            self.variable_play.setChecked(False)
            self.inputs_playShaft.stop()
        self.EntitiesPoint.getBackPosition()
        vpoints = self.EntitiesPoint.dataTuple()
        for i, (p0, p1, a) in enumerate(self.inputPairs()):
            self.variable_list.item(i).setText('->'.join([
                f'Point{p0}',
                f'Point{p1}',
                f"{vpoints[p0].slope_angle(vpoints[p1]):.02f}",
            ]))
        self.__dial_ok()
        self.solve()

    @pyqtSlot(bool, name='on_variable_play_toggled')
    def __play(self, toggled: bool):
        """Triggered when play button was changed."""
        self.dial.setEnabled(not toggled)
        self.dial_spinbox.setEnabled(not toggled)
        if toggled:
            self.inputs_playShaft.start()
        else:
            self.inputs_playShaft.stop()
            if self.update_pos_option.isChecked():
                self.setCoordsAsCurrent()

    @pyqtSlot()
    def __change_index(self):
        """QTimer change index."""
        index = self.dial.value()
        speed = self.variable_speed.value()
        extreme_rebound = (
            self.conflict.isVisible() and
            self.extremeRebound.isChecked()
        )
        if extreme_rebound:
            speed = -speed
            self.variable_speed.setValue(speed)
        index += int(speed * 6 * (3 if extreme_rebound else 1))
        index %= self.dial.maximum()
        self.dial.setValue(index)

    @pyqtSlot(bool, name='on_record_start_toggled')
    def __start_record(self, toggled: bool):
        """Save to file path data."""
        if toggled:
            self.MainCanvas.recordStart(int(
                self.dial_spinbox.maximum() / self.record_interval.value()
            ))
            return
        path = self.MainCanvas.getRecordPath()
        name, ok = QInputDialog.getText(
            self,
            "Recording completed!",
            "Please input name tag:"
        )
        i = 0
        name = name or f"Record_{i}"
        while name in self.__path_data:
            name = f"Record_{i}"
            i += 1
        QMessageBox.information(
            self,
            "Record",
            "The name tag is being used or empty."
        )
        self.addPath(name, path)

    def addPath(self, name: str, path: Sequence[Tuple[float, float]]):
        """Add path function."""
        self.CommandStack.beginMacro(f"Add {{Path: {name}}}")
        self.CommandStack.push(AddPath(
            self.record_list,
            name,
            self.__path_data,
            path
        ))
        self.CommandStack.endMacro()
        self.record_list.setCurrentRow(self.record_list.count() - 1)

    def loadPaths(self, paths: Dict[str, Sequence[Tuple[float, float]]]):
        """Add multiple path."""
        for name, path in paths.items():
            self.addPath(name, path)

    @pyqtSlot(name='on_record_remove_clicked')
    def __remove_path(self):
        """Remove path data."""
        row = self.record_list.currentRow()
        if not row > 0:
            return
        name = self.record_list.item(row).text()
        self.CommandStack.beginMacro(f"Delete {{Path: {name}}}")
        self.CommandStack.push(DeletePath(
            row,
            self.record_list,
            self.__path_data
        ))
        self.CommandStack.endMacro()
        self.record_list.setCurrentRow(self.record_list.count() - 1)
        self.reloadCanvas()

    @pyqtSlot(QListWidgetItem, name='on_record_list_itemDoubleClicked')
    def __path_dlg(self, item: QListWidgetItem):
        """View path data."""
        name = item.text().split(":")[0]
        try:
            data = self.__path_data[name]
        except KeyError:
            return
        points_text = ", ".join(f"Point{i}" for i in range(len(data)))
        reply = QMessageBox.question(
            self,
            "Path data",
            f"This path data including {points_text}.",
            (QMessageBox.Save | QMessageBox.Close),
            QMessageBox.Close
        )
        if reply != QMessageBox.Save:
            return
        file_name = self.outputTo(
            "path data",
            ["Comma-Separated Values (*.csv)", "Text file (*.txt)"]
        )
        if not file_name:
            return
        with open(file_name, 'w', newline='') as stream:
            writer = csv.writer(stream)
            for point in data:
                for coordinate in point:
                    writer.writerow(coordinate)
                writer.writerow(())
        print(f"Output path data: {file_name}")

    @pyqtSlot(QPoint)
    def __record_list_context_menu(self, point):
        """Show the context menu.

        Show path [0], [1], ...
        Or copy path coordinates.
        """
        row = self.record_list.currentRow()
        if not row > -1:
            return
        showall_action = self.pop_menu_record_list.addAction("Show all")
        showall_action.index = -1
        copy_action = self.pop_menu_record_list.addAction("Copy as new")
        name = self.record_list.item(row).text().split(':')[0]
        try:
            data = self.__path_data[name]
        except KeyError:
            # Auto preview path.
            data = self.MainCanvas.Path.path
            showall_action.setEnabled(False)
        else:
            for action_text in ("Show", "Copy data from"):
                self.pop_menu_record_list.addSeparator()
                for i in range(len(data)):
                    if data[i]:
                        action = self.pop_menu_record_list.addAction(
                            f"{action_text} Point{i}"
                        )
                        action.index = i
        action_exec = self.pop_menu_record_list.exec_(
            self.record_list.mapToGlobal(point)
        )
        if action_exec:
            if action_exec == copy_action:
                # Copy path data.
                num = 0
                name_copy = f"{name}_{num}"
                while name_copy in self.__path_data:
                    name_copy = f"{name}_{num}"
                    num += 1
                self.addPath(name_copy, data)
            elif "Copy data from" in action_exec.text():
                # Copy data to clipboard.
                QApplication.clipboard().setText('\n'.join(
                    f"{x},{y}" for x, y in data[action_exec.index]
                ))
            elif "Show" in action_exec.text():
                # Switch points enabled status.
                if action_exec.index == -1:
                    self.record_show.setChecked(True)
                self.MainCanvas.setPathShow(action_exec.index)
        self.pop_menu_record_list.clear()

    @pyqtSlot(bool, name='on_record_show_toggled')
    def __set_path_show(self, toggled: bool):
        """Show all paths or hide."""
        self.MainCanvas.setPathShow(-1 if toggled else -2)

    @pyqtSlot(int, name='on_record_list_currentRowChanged')
    def __set_path(self, _: int):
        """Reload the canvas when switch the path."""
        if not self.record_show.isChecked():
            self.record_show.setChecked(True)
        self.reloadCanvas()

    def currentPath(self):
        """Return current path data to main canvas.

        + No path.
        + Show path data.
        + Auto preview.
        """
        row = self.record_list.currentRow()
        if row in {0, -1}:
            return ()
        path_name = self.record_list.item(row).text().split(':')[0]
        return self.__path_data.get(path_name, ())

    @pyqtSlot(name='on_variable_up_clicked')
    @pyqtSlot(name='on_variable_down_clicked')
    def __set_variable_priority(self):
        row = self.variable_list.currentRow()
        if not row > -1:
            return
        item = self.variable_list.currentItem()
        self.variable_list.insertItem(
            row + (-1 if self.sender() == self.variable_up else 1),
            self.variable_list.takeItem(row)
        )
        self.variable_list.setCurrentItem(item)