예제 #1
0
 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)
예제 #2
0
    def __undo_redo(self):
        """Undo list settings.

        + Undo stack.
        + Undo view widget.
        + Hot keys.
        """
        self.command_stack = QUndoStack(self)
        self.command_stack.setUndoLimit(self.undo_limit_option.value())
        self.undo_limit_option.valueChanged.connect(
            self.command_stack.setUndoLimit)
        self.command_stack.indexChanged.connect(self.command_reload)
        self.undo_view = QUndoView(self.command_stack)
        self.undo_view.setEmptyLabel("~ Start Pyslvs")
        self.undo_redo_layout.addWidget(self.undo_view)
        self.action_redo = self.command_stack.createRedoAction(self, "Redo")
        self.action_undo = self.command_stack.createUndoAction(self, "Undo")
        self.action_redo.setShortcuts([
            QKeySequence("Ctrl+Shift+Z"),
            QKeySequence("Ctrl+Y"),
        ])
        self.action_redo.setStatusTip("Backtracking undo action.")
        self.action_redo.setIcon(QIcon(QPixmap(":/icons/redo.png")))
        self.action_undo.setShortcut("Ctrl+Z")
        self.action_undo.setStatusTip("Recover last action.")
        self.action_undo.setIcon(QIcon(QPixmap(":/icons/undo.png")))
        self.menu_edit.addAction(self.action_undo)
        self.menu_edit.addAction(self.action_redo)
예제 #3
0
 def build_actions(self):
     self.toolBar.addAction(QIcon(QPixmap(':/core/icons/open-icon.png')),
                            "Openfile")
     self.toolBar.addAction(QIcon(QPixmap(':/core/icons/save-icon.png')),
                            "Savefile")
     self.toolBar.addAction(
         QIcon(QPixmap(':/core/icons/Settings-icon.png')), "Setting")
     self.toolBar.addAction(
         QIcon(QPixmap(':/core/icons/Actions-process-stop-icon.png')),
         "Stop")
예제 #4
0
 def __init__(self, mode, parent):
     super(SolutionsDialog, self).__init__(parent)
     self.setupUi(self)
     self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
     self.setWindowTitle("{} solution".format(mode))
     if mode=='PLAP':
         self.main_label.setText(
             "Two known points A (Driver) and B, " +
             "with angle β and length L0 to find out the coordinate of point C."
         )
         for row in range(parent.Driver_list.count()):
             self.point_A.addItem(parent.Driver_list.item(row).text())
     elif mode=='PLLP':
         self.main_label.setText(
             "Two known points A and B, " +
             "with length L0 and R0 to find out the coordinate of point C."
         )
         self.graph_label.setPixmap(QPixmap(":/icons/preview/PLLP.png"))
     for node, status in parent.PreviewWindow.status.items():
         if not status:
             continue
         if node in parent.PreviewWindow.same:
             continue
         if mode=='PLLP':
             self.point_A.addItem('P{}'.format(node))
         self.point_B.addItem('P{}'.format(node))
     self.point_A.currentIndexChanged.connect(self.isOk)
     self.point_B.currentIndexChanged.connect(self.isOk)
     self.isOk()
예제 #5
0
    def __free_move(self):
        """Menu of free move mode."""
        free_move_mode_menu = QMenu(self)

        def free_move_mode_func(j: int, icon_qt: QIcon):
            @pyqtSlot()
            def func():
                self.free_move_button.setIcon(icon_qt)
                self.MainCanvas.setFreeMove(j)
                self.EntitiesTab.setCurrentIndex(0)
                self.InputsWidget.variable_stop.click()

            return func

        for i, (text, icon, tip) in enumerate((
            ("View mode", "free_move_off", "Disable free move mode."),
            ("Translate mode", "translate", "Edit by 2 DOF moving."),
            ("Rotate mode", "rotate", "Edit by 1 DOF moving."),
            ("Reflect mode", "reflect", "Edit by flip axis."),
        )):
            action = QAction(QIcon(QPixmap(f":/icons/{icon}.png")), text, self)
            action.triggered.connect(free_move_mode_func(i, action.icon()))
            action.setShortcut(QKeySequence(f"Ctrl+{i + 1}"))
            action.setShortcutContext(Qt.WindowShortcut)
            action.setStatusTip(tip)
            free_move_mode_menu.addAction(action)
            if i == 0:
                self.free_move_disable = action
        self.free_move_button.setMenu(free_move_mode_menu)

        # Link free move by expression table.
        self.link_free_move_slider.sliderReleased.connect(
            self.MainCanvas.emit_free_move_all)
예제 #6
0
    def __free_move(self):
        """Menu of free move mode."""
        free_move_mode_menu = QMenu(self)

        def free_move_mode_func(j: int, icon_qt: QIcon):
            @Slot()
            def func() -> None:
                self.free_move_button.setIcon(icon_qt)
                self.main_canvas.set_free_move(j)
                self.entities_tab.setCurrentIndex(0)
                self.inputs_widget.variable_stop.click()

            return func

        for i, (text, icon, tip) in enumerate([
            ("View mode", "free_move_off", "Disable free move mode."),
            ("Translate mode", "translate", "Edit by 2 DOF moving."),
            ("Rotate mode", "rotate", "Edit by 1 DOF moving."),
            ("Reflect mode", "reflect", "Edit by flip axis."),
        ]):
            action = QAction(QIcon(QPixmap(f":/icons/{icon}.png")), text, self)
            action.triggered.connect(free_move_mode_func(i, action.icon()))
            action.setShortcut(QKeySequence(f"Ctrl+{i + 1}"))
            action.setShortcutContext(Qt.WindowShortcut)
            action.setStatusTip(tip)
            free_move_mode_menu.addAction(action)
            if i == 0:
                self.free_move_disable = action
        self.free_move_button.setMenu(free_move_mode_menu)

        # "Link adjust" function
        self.link_free_move_confirm.clicked.connect(
            self.main_canvas.emit_free_move_all)
예제 #7
0
    def __init__(
        self,
        vpoints: List[VPoint],
        vlinks: List[VLink],
        pos: bool,
        parent: QWidget,
    ):
        """Input data reference from main window.

        + Needs VPoints and VLinks information.
        + If row is false: Create action.
        """
        super(EditPointDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        icon = self.windowIcon()
        self.link_icon = QIcon(QPixmap(":/icons/link.png"))
        self.vpoints = vpoints
        self.vlinks = vlinks
        vpoints_count = len(vpoints)
        for i, e in enumerate(color_names):
            self.color_box.insertItem(i, color_icon(e), e)
        for vlink in vlinks:
            self.noSelected.addItem(QListWidgetItem(self.link_icon,
                                                    vlink.name))
        if pos is False:
            self.name_box.addItem(icon, f'Point{vpoints_count}')
            self.name_box.setEnabled(False)
            self.color_box.setCurrentIndex(self.color_box.findText('Green'))
        else:
            for i in range(vpoints_count):
                self.name_box.insertItem(i, icon, f'Point{i}')
            self.name_box.setCurrentIndex(pos)
예제 #8
0
    def __init__(self, vpoints: List[VPoint], vlinks: List[VLink],
                 row: Union[int, bool], parent: QWidget):
        """Input data reference from main window.

        + Needs VPoints and VLinks information.
        + If row is false: Create action.
        """
        super(EditLinkDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.vpoints = vpoints
        self.vlinks = vlinks
        icon = self.windowIcon()
        self.point_icon = QIcon(QPixmap(":/icons/bearing.png"))
        for i, e in enumerate(colorNames):
            self.color_box.insertItem(i, color_icon(e), e)
        for i in range(len(self.vpoints)):
            self.noSelected.addItem(
                QListWidgetItem(self.point_icon, f'Point{i}'))
        if row is False:
            self.name_box.addItem(icon, "New link")
            self.name_box.setEnabled(False)
            self.color_box.setCurrentIndex(self.color_box.findText('Blue'))
        else:
            for i, vlink in enumerate(self.vlinks):
                self.name_box.insertItem(i, icon, vlink.name)
            self.name_box.setCurrentIndex(row)
        self.name_edit.textChanged.connect(self.__is_ok)
        self.__is_ok()
예제 #9
0
 def __init__(self,
              points: List[VPoint],
              links: List[VLink],
              pos: bool = False,
              parent=None):
     super(EditPointDialog, self).__init__(parent)
     self.setupUi(self)
     self.setWindowFlags(self.windowFlags()
                         & ~Qt.WindowContextHelpButtonHint)
     icon = self.windowIcon()
     self.LinkIcon = QIcon(QPixmap(":/icons/link.png"))
     self.points = points
     self.links = links
     for i, e in enumerate(colorName):
         self.Color.insertItem(i, colorIcons(e), e)
     for vlink in links:
         self.noSelected.addItem(QListWidgetItem(self.LinkIcon, vlink.name))
     if pos is False:
         self.Point.addItem(icon, 'Point{}'.format(len(points)))
         self.Point.setEnabled(False)
         self.Color.setCurrentIndex(self.Color.findText('Green'))
     else:
         for i in range(len(points)):
             self.Point.insertItem(i, icon, 'Point{}'.format(i))
         self.Point.setCurrentIndex(pos)
예제 #10
0
def _math_tex_to_qpixmap(math_tex: str, fs: int):
    # set up a mpl figure instance
    fig = Figure()
    fig.patch.set_facecolor('none')
    fig.set_canvas(FigureCanvasAgg(fig))
    renderer = fig.canvas.get_renderer()

    # plot the math_tex expression
    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    ax.patch.set_facecolor('none')
    t = ax.text(0, 0, math_tex, ha='left', va='bottom', fontsize=fs)

    # fit figure size to text artist
    f_width, f_height = fig.get_size_inches()
    fig_bbox = fig.get_window_extent(renderer)
    text_bbox = t.get_window_extent(renderer)
    tight_fwidth = text_bbox.width * f_width / fig_bbox.width
    tight_fheight = text_bbox.height * f_height / fig_bbox.height
    fig.set_size_inches(tight_fwidth, tight_fheight)

    # convert mpl figure to QPixmap
    buf, size = fig.canvas.print_to_buffer()

    return QPixmap(QImage.rgbSwapped(QImage(buf, size[0], size[1], QImage.Format_ARGB32)))
예제 #11
0
 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))
예제 #12
0
 def __addResult(self, result: Dict[str, Any]):
     """Add result items, except add to the list."""
     item = QListWidgetItem(result['Algorithm'])
     interrupt = result['interrupted']
     if interrupt == 'False':
         item.setIcon(QIcon(QPixmap(":/icons/task-completed.png")))
     elif interrupt == 'N/A':
         item.setIcon(QIcon(QPixmap(":/icons/question-mark.png")))
     else:
         item.setIcon(QIcon(QPixmap(":/icons/interrupted.png")))
     text = "{} ({})".format(
         result['Algorithm'], "No interrupt."
         if interrupt == 'False' else "Interrupt at {}".format(interrupt))
     if interrupt == 'N/A':
         text += "\n※Completeness is not clear."
     item.setToolTip(text)
     self.Result_list.addItem(item)
예제 #13
0
def graph(G: Graph,
          width: int,
          engine: [str, Dict[int, Tuple[float, float]]],
          node_mode: bool = False,
          except_node: int = None) -> QIcon:
    """Draw a linkage graph."""
    try:
        pos = engine_picker(G, engine, node_mode)
    except EngineError as e:
        raise e
    width_ = -inf
    for x, y in pos.values():
        if abs(x) > width_:
            width_ = x
        if abs(y) > width_:
            width_ = y
    width_ *= 2 * 1.2
    image = QImage(QSize(width_, width_), QImage.Format_ARGB32_Premultiplied)
    image.fill(Qt.transparent)
    painter = QPainter(image)
    painter.translate(image.width() / 2, image.height() / 2)
    pen = QPen()
    r = width_ / 50
    pen.setWidth(r)
    painter.setPen(pen)
    if node_mode:
        for l1, l2 in G.edges:
            painter.drawLine(QPointF(pos[l1][0], -pos[l1][1]),
                             QPointF(pos[l2][0], -pos[l2][1]))
    else:
        painter.setBrush(QBrush(QColor(226, 219, 190, 150)))
        for link in G.nodes:
            if link == except_node:
                continue
            #Distance sorted function from canvas
            painter.drawPolygon(*convex_hull([(pos[n][0], -pos[n][1])
                                              for n, edge in edges_view(G)
                                              if link in edge]))
    for k, (x, y) in pos.items():
        if node_mode:
            color = colorNum(len(list(G.neighbors(k))) - 1)
        else:
            if except_node in tuple(G.edges)[k]:
                color = colorQt('Green')
            else:
                color = colorQt('Blue')
        pen.setColor(color)
        painter.setPen(pen)
        painter.setBrush(QBrush(color))
        painter.drawEllipse(QPointF(x, -y), r, r)
    painter.end()
    icon = QIcon(QPixmap.fromImage(image).scaledToWidth(width))
    return icon
예제 #14
0
    def __save_atlas(self):
        """Save function as same as type synthesis widget."""
        count = self.collection_list.count()
        if not count:
            return

        lateral, ok = QInputDialog.getInt(self, "Atlas",
                                          "The number of lateral:", 5, 1)
        if not ok:
            return

        file_name = self.output_to("Atlas image", qt_image_format)
        if not file_name:
            return

        icon_size = self.collection_list.iconSize()
        width = icon_size.width()
        image_main = QImage(
            QSize(lateral * width if count > lateral else count * width,
                  ((count // lateral) + bool(count % lateral)) * width),
            self.collection_list.item(0).icon().pixmap(
                icon_size).toImage().format())
        image_main.fill(Qt.transparent)
        painter = QPainter(image_main)
        for row in range(count):
            image = self.collection_list.item(row).icon().pixmap(
                icon_size).toImage()
            painter.drawImage(
                QPointF(row % lateral * width, row // lateral * width), image)
        painter.end()
        pixmap = QPixmap()
        pixmap.convertFromImage(image_main)
        pixmap.save(file_name)
        self.save_reply_box("Atlas", file_name)
예제 #15
0
 def on_save_atlas_clicked(self):
     """Save function as same as type synthesis widget."""
     count = self.collection_list.count()
     if not count:
         return
     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 not fileName:
         return
     icon_size = self.collection_list.iconSize()
     width = icon_size.width()
     image_main = QImage(
         QSize(lateral * width if count > lateral else count * width,
               ((count // lateral) + bool(count % lateral)) * width),
         self.collection_list.item(0).icon().pixmap(
             icon_size).toImage().format())
     image_main.fill(QColor(Qt.white).rgb())
     painter = QPainter(image_main)
     for row in range(count):
         image = self.collection_list.item(row).icon().pixmap(
             icon_size).toImage()
         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)
예제 #16
0
    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()
예제 #17
0
    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)
예제 #18
0
 def __init__(self, format_name: str, format_icon: str,
              assembly_description: str, frame_description: str, env: str,
              file_name: str, vpoints: Sequence[VPoint],
              v_to_slvs: Callable[[],
                                  Sequence[Tuple[int,
                                                 int]]], parent: QWidget):
     """Comes in environment variable and workbook name."""
     super(_OutputDialog, self).__init__(parent)
     self.setupUi(self)
     self.setWindowFlags(self.windowFlags()
                         & ~Qt.WindowContextHelpButtonHint)
     self.setWindowTitle(f"Export {format_name} module project")
     self.setWindowIcon(QIcon(QPixmap(f":/icons/{format_icon}")))
     self.assembly_label.setText(assembly_description)
     self.frame_label.setText(frame_description)
     self.path_edit.setPlaceholderText(env)
     self.filename_edit.setPlaceholderText(file_name)
     self.vpoints = vpoints
     self.v_to_slvs = v_to_slvs
예제 #19
0
 def __init__(self, parent=None):
     super(Collections, self).__init__(parent)
     layout = QVBoxLayout(self)
     tabWidget = QTabWidget(self)
     layout.addWidget(tabWidget)
     self.setWindowIcon(QIcon(QPixmap(":/icons/collections.png")))
     self.CollectionsStructure = CollectionsStructure(parent)
     self.CollectionsTriangularIteration = CollectionsTriangularIteration(
         parent)
     self.CollectionsTriangularIteration.addToCollection = self.CollectionsStructure.addCollection
     tabWidget.addTab(self.CollectionsStructure,
                      self.CollectionsStructure.windowIcon(), "Structure")
     tabWidget.addTab(self.CollectionsTriangularIteration,
                      self.CollectionsTriangularIteration.windowIcon(),
                      "Triangular iteration")
     self.CollectionsStructure.triangle_button.clicked.connect(
         lambda: tabWidget.setCurrentIndex(1))
     self.CollectionsStructure.layout_sender.connect(
         self.CollectionsTriangularIteration.setGraph)
예제 #20
0
 def __init__(self, parent: QWidget):
     """Create two widget page and using main window to make their parent."""
     super(Collections, self).__init__(parent)
     layout = QVBoxLayout(self)
     tab_widget = QTabWidget(self)
     layout.addWidget(tab_widget)
     self.setWindowIcon(QIcon(QPixmap(":/icons/collections.png")))
     self.StructureWidget = StructureWidget(parent)
     self.TriangularIterationWidget = TriangularIterationWidget(
         self.StructureWidget.addCollection, parent)
     tab_widget.addTab(self.StructureWidget,
                       self.StructureWidget.windowIcon(), "Structures")
     tab_widget.addTab(self.TriangularIterationWidget,
                       self.TriangularIterationWidget.windowIcon(),
                       "Triangular iteration")
     self.StructureWidget.triangle_button.clicked.connect(
         lambda: tab_widget.setCurrentIndex(1))
     self.StructureWidget.layout_sender.connect(
         self.TriangularIterationWidget.setGraph)
예제 #21
0
 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()
예제 #22
0
 def __init__(self, parent: MainWindowBase):
     """Create two widget page and using main window to make their parent."""
     super(Collections, self).__init__(parent)
     layout = QVBoxLayout(self)
     self.tab_widget = QTabWidget(self)
     layout.addWidget(self.tab_widget)
     self.setWindowIcon(QIcon(QPixmap(":/icons/collections.png")))
     self.structure_widget = StructureWidget(parent)
     self.configure_widget = ConfigureWidget(
         self.structure_widget.add_collection, parent)
     self.tab_widget.addTab(self.structure_widget,
                            self.structure_widget.windowIcon(),
                            "Structures")
     self.tab_widget.addTab(self.configure_widget,
                            self.configure_widget.windowIcon(),
                            "Configuration")
     self.structure_widget.configure_button.clicked.connect(
         lambda: self.tab_widget.setCurrentIndex(1))
     self.structure_widget.layout_sender.connect(
         self.configure_widget.set_graph)
예제 #23
0
 def __add_result(self, result: Dict[str, Any]):
     """Add result items, except add to the list."""
     item = QListWidgetItem(result['Algorithm'])
     interrupt = result['interrupted']
     if interrupt == 'False':
         interrupt_icon = "task_completed.png"
     elif interrupt == 'N/A':
         interrupt_icon = "question.png"
     else:
         interrupt_icon = "interrupted.png"
     item.setIcon(QIcon(QPixmap(f":/icons/{interrupt_icon}")))
     if interrupt == 'False':
         interrupt_text = "No interrupt."
     else:
         interrupt_text = f"Interrupt at: {interrupt}"
     text = f"{result['Algorithm']} ({interrupt_text})"
     if interrupt == 'N/A':
         text += "\n※Completeness is unknown."
     item.setToolTip(text)
     self.result_list.addItem(item)
예제 #24
0
 def __init__(self, Points, Links, pos=False, parent=None):
     super(edit_link_show, self).__init__(parent)
     self.setupUi(self)
     self.setWindowFlags(self.windowFlags()
                         & ~Qt.WindowContextHelpButtonHint)
     self.Points = Points
     self.Links = Links
     icon = self.windowIcon()
     self.PointIcon = QIcon(QPixmap(":/icons/bearing.png"))
     for i, e in enumerate(colorName()):
         self.Color.insertItem(i, colorIcons(e), e)
     for i in range(len(self.Points)):
         self.noSelected.addItem(
             QListWidgetItem(self.PointIcon, 'Point{}'.format(i)))
     if pos is False:
         self.Link.addItem(icon, "New link")
         self.Link.setEnabled(False)
         self.Color.setCurrentIndex(self.Color.findText('Blue'))
     else:
         for vlink in self.Links:
             self.Link.insertItem(i, icon, vlink.name)
         self.Link.setCurrentIndex(pos)
     self.name_edit.textChanged.connect(self.isOk)
     self.isOk()
예제 #25
0
def to_graph(graph: Graph,
             width: int,
             engine: Union[str, Dict[int, Tuple[float, float]]],
             node_mode: bool = False,
             except_node: int = None) -> QIcon:
    """Draw a generalized chain graph."""
    pos: Pos = engine_picker(graph, engine, node_mode)
    width_bound = -float('inf')
    for x, y in pos.values():
        if abs(x) > width_bound:
            width_bound = x
        if abs(y) > width_bound:
            width_bound = y
    width_bound *= 2.2
    image = QImage(QSize(int(width_bound), int(width_bound)),
                   QImage.Format_ARGB32_Premultiplied)
    image.fill(Qt.transparent)
    painter = QPainter(image)
    painter.translate(image.width() / 2, image.height() / 2)
    pen = QPen()
    r = width_bound / 50
    pen.setWidth(int(r))
    painter.setPen(pen)

    # Draw edges.
    if node_mode:
        for l1, l2 in graph.edges:
            if except_node in {l1, l2}:
                pen.setColor(color_qt('Gray'))
            else:
                pen.setColor(color_qt('Black'))
            painter.setPen(pen)

            painter.drawLine(QPointF(pos[l1][0], -pos[l1][1]),
                             QPointF(pos[l2][0], -pos[l2][1]))
    else:
        painter.setBrush(QBrush(QColor(226, 219, 190, 150)))
        for link in graph.nodes:
            if link == except_node:
                pen.setColor(color_qt('Gray'))
            else:
                pen.setColor(color_qt('Black'))
            painter.setPen(pen)

            painter.drawPolygon(*convex_hull([(pos[n][0], -pos[n][1])
                                              for n, edge in edges_view(graph)
                                              if link in edge],
                                             as_qpoint=True))

    # Draw nodes.
    for k, (x, y) in pos.items():
        if node_mode:
            color = color_num(len(list(graph.neighbors(k))) - 1)
            if k == except_node:
                color.setAlpha(150)
        else:
            if except_node in dict(edges_view(graph))[k]:
                color = color_qt('Green')
            else:
                color = color_qt('Blue')
        pen.setColor(color)
        painter.setPen(pen)
        painter.setBrush(QBrush(color))
        painter.drawEllipse(QPointF(x, -y), r, r)
    painter.end()
    icon = QIcon(QPixmap.fromImage(image).scaledToWidth(width))
    return icon
예제 #26
0
 def undo(self):
     """Create a new item and recover expression."""
     item = QListWidgetItem(self.name)
     item.expr = self.mechanism
     item.setIcon(QIcon(QPixmap(":/icons/mechanism.png")))
     self.widget.insertItem(self.row, item)
예제 #27
0
def colorIcons(name: str, size: int = 20) -> QIcon:
    """Get color block as QIcon by name."""
    colorBlock = QPixmap(QSize(size, size))
    colorBlock.fill(colorQt(name))
    return QIcon(colorBlock)
예제 #28
0
def file_icon(file_type: str) -> QIcon:
    """Return icon by file format."""
    return QIcon(QPixmap(f":/icons/{file_type}.png"))
예제 #29
0
    def __appearance(self):
        """Start up and initialize custom widgets."""
        # Version label
        self.version_label.setText(__version__)

        # Entities tables
        self.entities_tab.tabBar().setStatusTip(
            "Switch the tabs to change to another view mode.")

        self.entities_point = PointTableWidget(self.entities_point_widget)
        self.entities_point.cellDoubleClicked.connect(self.edit_point)
        self.entities_point.delete_request.connect(self.delete_selected_points)
        self.entities_point_layout.addWidget(self.entities_point)

        self.entities_link = LinkTableWidget(self.entities_link_widget)
        self.entities_link.cellDoubleClicked.connect(self.edit_link)
        self.entities_link.delete_request.connect(self.delete_selected_links)
        self.entities_link_layout.addWidget(self.entities_link)

        self.entities_expr = ExprTableWidget(self.EntitiesExpr_widget)
        self.entities_expr_layout.insertWidget(0, self.entities_expr)

        # Select all button on the Point and Link tab as corner widget.
        select_all_button = QPushButton()
        select_all_button.setIcon(QIcon(QPixmap(":/icons/select_all.png")))
        select_all_button.setToolTip("Select all")
        select_all_button.setStatusTip("Select all item of point table.")

        @Slot()
        def table_select_all():
            """Distinguish table by tab index."""
            tables: List[BaseTableWidget] = [
                self.entities_point,
                self.entities_link,
                self.entities_expr,
            ]
            tables[self.entities_tab.currentIndex()].selectAll()

        select_all_button.clicked.connect(table_select_all)
        self.entities_tab.setCornerWidget(select_all_button)
        select_all_action = QAction("Select all point", self)
        select_all_action.triggered.connect(table_select_all)
        select_all_action.setShortcut("Ctrl+A")
        select_all_action.setShortcutContext(Qt.WindowShortcut)
        self.addAction(select_all_action)

        # QPainter canvas window
        self.main_canvas = DynamicCanvas(self)
        select_tips = QLabel(self, Qt.ToolTip)
        self.entities_tab.currentChanged.connect(
            self.main_canvas.set_selection_mode)

        @Slot(QPoint, str)
        def show_select_tips(pos: QPoint, text: str):
            select_tips.setText(text)
            select_tips.move(pos - QPoint(0, select_tips.height()))
            select_tips.show()

        self.main_canvas.selected_tips.connect(show_select_tips)
        self.main_canvas.selected_tips_hide.connect(select_tips.hide)

        @Slot(tuple, bool)
        def table_set_selection(selections: Sequence[int], key_detect: bool):
            """Distinguish table by tab index."""
            tables: List[BaseTableWidget] = [
                self.entities_point,
                self.entities_link,
                self.entities_expr,
            ]
            tables[self.entities_tab.currentIndex()].set_selections(
                selections, key_detect)

        self.main_canvas.selected.connect(table_set_selection)
        self.entities_point.row_selection_changed.connect(
            self.main_canvas.set_selection)

        @Slot()
        def table_clear_selection():
            """Distinguish table by tab index."""
            tables: List[BaseTableWidget] = [
                self.entities_point,
                self.entities_link,
                self.entities_expr,
            ]
            tables[self.entities_tab.currentIndex()].clearSelection()

        self.main_canvas.noselected.connect(table_clear_selection)

        clean_selection_action = QAction("Clean selection", self)
        clean_selection_action.triggered.connect(table_clear_selection)
        clean_selection_action.setShortcut("Esc")
        clean_selection_action.setShortcutContext(Qt.WindowShortcut)
        self.addAction(clean_selection_action)

        self.main_canvas.free_moved.connect(self.set_free_move)
        self.main_canvas.alt_add.connect(self.q_add_normal_point)
        self.main_canvas.doubleclick_edit.connect(self.edit_point)
        self.main_canvas.zoom_changed.connect(self.zoom_bar.setValue)
        self.main_canvas.tracking.connect(self.set_mouse_pos)
        self.canvas_splitter.insertWidget(0, self.main_canvas)
        self.canvas_splitter.setSizes([600, 10, 30])

        # Selection label on status bar right side
        selection_label = SelectionLabel(self)
        self.entities_point.selectionLabelUpdate.connect(
            selection_label.update_select_point)
        self.main_canvas.browse_tracking.connect(
            selection_label.update_mouse_position)
        self.status_bar.addPermanentWidget(selection_label)

        # FPS label on status bar right side
        fps_label = FPSLabel(self)
        self.main_canvas.fps_updated.connect(fps_label.update_text)
        self.status_bar.addPermanentWidget(fps_label)

        # Inputs widget
        self.inputs_widget = InputsWidget(self)
        self.inputs_tab_layout.addWidget(self.inputs_widget)
        self.free_move_button.toggled.connect(
            self.inputs_widget.variable_value_reset)
        self.inputs_widget.about_to_resolve.connect(self.resolve)

        @Slot(tuple, bool)
        def inputs_set_selection(selections: Sequence[int], _: bool):
            """Distinguish table by tab index."""
            self.inputs_widget.clear_selection()
            if self.entities_tab.currentIndex() == 0:
                self.inputs_widget.set_selection(selections)

        self.main_canvas.selected.connect(inputs_set_selection)
        self.main_canvas.noselected.connect(self.inputs_widget.clear_selection)
        self.inputs_widget.update_preview_button.clicked.connect(
            self.main_canvas.update_preview_path)

        # Number and type synthesis
        self.structure_synthesis = StructureSynthesis(self)
        self.synthesis_tab_widget.addTab(self.structure_synthesis,
                                         self.structure_synthesis.windowIcon(),
                                         "Structural")

        # Synthesis collections
        self.collection_tab_page = Collections(self)
        self.synthesis_tab_widget.addTab(self.collection_tab_page,
                                         self.collection_tab_page.windowIcon(),
                                         "Collections")
        self.structure_synthesis.addCollection = (
            self.collection_tab_page.structure_widget.add_collection)

        # Dimensional synthesis
        self.dimensional_synthesis = DimensionalSynthesis(self)
        self.main_canvas.set_target_point.connect(
            self.dimensional_synthesis.set_point)
        self.synthesis_tab_widget.addTab(
            self.dimensional_synthesis,
            self.dimensional_synthesis.windowIcon(), "Dimensional")

        @Slot()
        def set_design_progress():
            """Synthesis progress bar."""
            pos = self.synthesis_tab_widget.currentIndex()
            if pos == 1:
                pos += self.collection_tab_page.tab_widget.currentIndex()
            elif pos == 2:
                pos += 1
            self.synthesis_progress.setValue(pos)

        self.synthesis_tab_widget.currentChanged.connect(set_design_progress)
        self.collection_tab_page.tab_widget.currentChanged.connect(
            set_design_progress)

        # File widget settings
        self.database_widget = DatabaseWidget(self)
        self.vc_layout.addWidget(self.database_widget)
        self.database_widget.commit_add.clicked.connect(self.commit)
        self.database_widget.branch_add.clicked.connect(self.commit_branch)
        self.action_stash.triggered.connect(self.database_widget.stash)

        # YAML editor
        self.yaml_editor = YamlEditor(self)

        # Console dock will hide when startup
        self.console_widget.hide()
        # Connect to GUI button
        self.console_disconnect_button.setEnabled(not ARGUMENTS.debug_mode)
        self.console_connect_button.setEnabled(ARGUMENTS.debug_mode)

        # Splitter stretch factor
        self.main_splitter.setStretchFactor(0, 4)
        self.main_splitter.setStretchFactor(1, 15)
        self.mechanism_panel_splitter.setSizes([500, 200])

        # Enable mechanism menu actions when shows.
        self.menu_mechanism.aboutToShow.connect(self.enable_mechanism_actions)

        @Slot()
        def new_main_window():
            """Start a new window."""
            run = self.__class__()
            run.show()

        self.action_new_window.triggered.connect(new_main_window)
예제 #30
0
 def __init__(self, parent=None):
     super(PyslvsSplash, self).__init__(parent,
                                        QPixmap(":/icons/Splash.png"))
     self.showMessage("Version {}.{}.{}({})".format(*VERSION),
                      (Qt.AlignBottom | Qt.AlignRight))