def __init__(self, title, message): super().__init__(title, message) # Set title label title_label = CustomLabel(self.title) title_label.setStyleSheet(style.NODE_LABEL_STYLE) title_label.setAlignment(Qt.AlignCenter) # Set message label mess_label = CustomLabel("\n" + self.content + "\n") mess_label.setAlignment(Qt.AlignCenter) self.confirm = False # Add buttons to close the dialog confirm_button = CustomButton("Yes") confirm_button.clicked.connect(self.ok) no_button = CustomButton("No") no_button.clicked.connect(self.deny) buttons_layout = QHBoxLayout() buttons_layout.addWidget(confirm_button) buttons_layout.addWidget(no_button) buttons = QWidget() buttons.setLayout(buttons_layout) # Compose widgets self.layout.addWidget(title_label) self.layout.addWidget(mess_label) self.layout.addWidget(buttons) self.render_layout()
def __init__(self, message: str): super().__init__("", message) # Override window title self.setWindowTitle("Wait...") # Set content label message_label = CustomLabel(self.content) message_label.setStyleSheet(style.LOADING_LABEL_STYLE) # Set loading bar progress_bar = ProgressBar(self, minimum=0, maximum=0, textVisible=False, objectName="ProgressBar") progress_bar.setStyleSheet(style.PROGRESS_BAR_STYLE) # Compose widgets self.layout.addWidget(message_label) self.layout.addWidget(progress_bar) self.render_layout() # Disable the dialog frame and close button self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False) self.setWindowFlags(Qt.FramelessWindowHint)
def __init__(self, block_id: str, p_type: str): super().__init__(block_id) self.property_type = p_type self.pre_condition = True self.smt_string = "" if p_type == "Generic SMT": self.label_string = "-" elif p_type == "Polyhedral": self.label_string = "Ax - b <= 0" self.condition_label = CustomLabel("PRE") self.property_label = CustomLabel(self.label_string) self.variables = [] self.init_layout() self.init_context_menu()
def init_layout(self) -> None: """ This method sets up the the property block main_layout with the property parameters. """ # Override title label self.title_label.setText(self.property_type) self.title_label.setStyleSheet(style.PROPERTY_TITLE_STYLE) self.condition_label.setStyleSheet(style.PROPERTY_CONDITION_STYLE) self.main_layout.addWidget(self.title_label) self.main_layout.addWidget(self.condition_label) self.init_grid() formula_label = CustomLabel("Formula") formula_label.setStyleSheet(style.PAR_NODE_STYLE) self.property_label.setStyleSheet(style.DIM_NODE_STYLE) self.content_layout.addWidget(formula_label, 1, 0) self.content_layout.addWidget(self.property_label, 1, 1)
def __init__(self, message): super().__init__("", message) # Set title label title_label = CustomLabel("Input required") title_label.setStyleSheet(style.NODE_LABEL_STYLE) title_label.setAlignment(Qt.AlignCenter) # Set message label mess_label = CustomLabel("\n" + self.content + "\n") mess_label.setAlignment(Qt.AlignCenter) # Set input reading self.input = None input_line = CustomTextBox() input_line.setValidator( QRegExpValidator( QRegExp(ArithmeticValidator.TENSOR.regExp().pattern() + "|" + ArithmeticValidator.TENSOR_LIST.regExp().pattern()))) # Add buttons to close the dialog confirm_button = CustomButton("Ok") confirm_button.clicked.connect(self.save_input()) cancel_button = CustomButton("Cancel") cancel_button.clicked.connect(self.cancel()) buttons = QWidget() buttons_layout = QHBoxLayout() buttons_layout.addWidget(confirm_button) buttons_layout.addWidget(cancel_button) buttons.setLayout(buttons_layout) # Compose widgets self.layout.addWidget(title_label) self.layout.addWidget(mess_label) self.layout.addWidget(input_line) self.layout.addWidget(buttons) self.render_layout()
def __init__(self): super(MainWindow, self).__init__() # Init window appearance self.SYSNAME = "CoCoNet" self.setWindowTitle(self.SYSNAME) self.setWindowIcon(QtGui.QIcon(ROOT_DIR + '/res/icons/logo_square.png')) self.setStyleSheet("background-color: " + style.GREY_1) # Navigation menu self.nav_menu_bar = self.menuBar() self.init_nav_menu_bar() # Blocks toolbar self.toolbar = BlocksToolbar(ROOT_DIR + '/res/json/blocks.json') # Parameters toolbar self.parameters = ParamToolbar() # Drawing Canvas self.canvas = Canvas(self.toolbar.blocks) # Status bar self.status_bar = QStatusBar() self.status_bar.setSizeGripEnabled(False) self.setStatusBar(self.status_bar) self.status_bar.setStyleSheet(style.STATUS_BAR_STYLE) self.status_bar_mode_label = CustomLabel() self.status_bar_mode_label.setStyleSheet(style.STATUS_BAR_WIDGET_STYLE) self.status_bar_selections_label = CustomLabel() self.status_bar_selections_label.setStyleSheet(style.STATUS_BAR_WIDGET_STYLE) self.status_bar.addPermanentWidget(self.status_bar_selections_label) self.status_bar.addPermanentWidget(self.status_bar_mode_label) # And adding them to the window self.addDockWidget(Qt.RightDockWidgetArea, self.parameters, Qt.Vertical) self.addToolBar(QtCore.Qt.ToolBarArea.LeftToolBarArea, self.toolbar) self.setCentralWidget(self.canvas.view) self.connect_events()
def __init__(self, block_id: str): super(GraphicBlock, self).__init__() self.block_id = block_id self.main_layout = QVBoxLayout() self.main_layout.setSpacing(0) self.title_label = CustomLabel("Graphic block") self.content_layout = QGridLayout() self.rect = None self.proxy_control = None self.context_actions = dict() self.setLayout(self.main_layout) # Set style and transparent background for the rounded corners self.setAttribute(Qt.WA_TranslucentBackground) self.setStyleSheet(style.GRAPHIC_BLOCK_STYLE)
def __init__(self, property_block: PropertyBlock): super().__init__("Edit property", "") self.property_block = property_block self.has_edits = False self.property_list = [] self.viewer = CustomTextArea() self.viewer.setReadOnly(True) self.viewer.setFixedHeight(100) grid = QGridLayout() # Build main_layout title_label = CustomLabel("Polyhedral property") title_label.setStyleSheet(style.NODE_LABEL_STYLE) title_label.setAlignment(Qt.AlignCenter) grid.addWidget(title_label, 0, 0, 1, 3) # Labels var_label = CustomLabel("Variable") var_label.setStyleSheet(style.IN_DIM_LABEL_STYLE) var_label.setAlignment(Qt.AlignRight) grid.addWidget(var_label, 1, 0) relop_label = CustomLabel("Operator") relop_label.setStyleSheet(style.IN_DIM_LABEL_STYLE) relop_label.setAlignment(Qt.AlignCenter) grid.addWidget(relop_label, 1, 1) value_label = CustomLabel("Value") value_label.setStyleSheet(style.IN_DIM_LABEL_STYLE) value_label.setAlignment(Qt.AlignLeft) grid.addWidget(value_label, 1, 2) self.var_cb = CustomComboBox() for v in property_block.variables: self.var_cb.addItem(v) grid.addWidget(self.var_cb, 2, 0) self.op_cb = CustomComboBox() operators = ["<=", "<", ">", ">="] for o in operators: self.op_cb.addItem(o) grid.addWidget(self.op_cb, 2, 1) self.val = CustomTextBox() self.val.setValidator(ArithmeticValidator.FLOAT) grid.addWidget(self.val, 2, 2) # "Add" button which adds the constraint add_button = CustomButton("Add") add_button.clicked.connect( lambda: self.add_entry(str(self.var_cb.currentText( )), str(self.op_cb.currentText()), self.val.text())) grid.addWidget(add_button, 3, 0) # "Save" button which saves the state save_button = CustomButton("Save") save_button.clicked.connect(self.save_property) grid.addWidget(save_button, 3, 1) # "Cancel" button which closes the dialog without saving cancel_button = CustomButton("Cancel") cancel_button.clicked.connect(self.close) grid.addWidget(cancel_button, 3, 2) grid.setColumnStretch(0, 1) grid.setColumnStretch(1, 1) grid.setColumnStretch(2, 1) self.layout.addLayout(grid) self.layout.addWidget(self.viewer, 3) self.render_layout()
def __init__(self, property_block: PropertyBlock): super().__init__("Edit property", "") self.property_block = property_block self.new_property = self.property_block.smt_string self.has_edits = False self.layout = QGridLayout() # Build main_layout title_label = CustomLabel("SMT property") title_label.setStyleSheet(style.NODE_LABEL_STYLE) title_label.setAlignment(Qt.AlignCenter) self.layout.addWidget(title_label, 0, 0, 1, 2) # Input box smt_label = CustomLabel("SMT-LIB definition") smt_label.setStyleSheet(style.IN_DIM_LABEL_STYLE) smt_label.setAlignment(Qt.AlignRight) self.layout.addWidget(smt_label, 1, 0) self.smt_box = CustomTextArea() self.smt_box.insertPlainText(self.new_property) self.layout.addWidget(self.smt_box, 1, 1) # "Apply" button which saves changes apply_button = CustomButton("Apply") apply_button.clicked.connect(self.save_data) self.layout.addWidget(apply_button, 2, 0) # "Cancel" button which closes the dialog without saving cancel_button = CustomButton("Cancel") cancel_button.clicked.connect(self.close) self.layout.addWidget(cancel_button, 2, 1) self.layout.setColumnStretch(0, 1) self.layout.setColumnStretch(1, 1) self.render_layout()
def append_node_params(self, node: NetworkNode, current_data: dict) -> int: """ This method adds to the dialog layer the editable parameters of the node, and returns the last row counter for the grid main_layout. Attributes ---------- node: NetworkNode The node whose parameters are displayed. current_data: dict The node current data. Returns ---------- int The last row counter. """ # Init column counter counter = 2 # Display parameter labels for param, value in node.param.items(): param_label = CustomLabel(param) if node.param[param]["editable"] == "false": param_label.setStyleSheet(style.UNEDITABLE_PARAM_LABEL_STYLE) param_label.setAlignment(Qt.AlignRight) # Set the tooltip of the input with the description param_label.setToolTip("<" + value["type"] + ">: " + value["description"]) self.layout.addWidget(param_label, counter, 0) # Display parameter values if value["type"] == "boolean": line = CustomComboBox() line.addItem("True") line.addItem("False") line.setPlaceholderText(str(current_data[param])) else: line = CustomTextBox() if node.param[param]["editable"] == "false": line.setReadOnly(True) if isinstance(current_data[param], Tensor) or isinstance( current_data[param], np.ndarray): line.setText( "(" + ','.join(map(str, current_data[param].shape)) + ")") elif isinstance(current_data[param], tuple): line.setText(','.join(map(str, current_data[param]))) else: line.setText(str(current_data[param])) # Set type validator validator = None if value["type"] == "int": validator = ArithmeticValidator.INT elif value["type"] == "float": validator = ArithmeticValidator.FLOAT elif value["type"] == "Tensor" or value[ "type"] == "list of ints": validator = ArithmeticValidator.TENSOR elif value["type"] == "list of Tensors": validator = ArithmeticValidator.TENSOR_LIST line.setValidator(validator) if node.param[param]["editable"] == "false": line.setStyleSheet(style.UNEDITABLE_VALUE_LABEL_STYLE) self.layout.addWidget(line, counter, 1) # Keep trace of CustomTextBox objects self.parameters[param] = line counter += 1 return counter
def __init__(self, node_block: NodeBlock): super().__init__(node_block.node.name, "") self.layout = QGridLayout() # Connect node self.node = node_block self.parameters = dict() self.edited_data = dict() self.has_edits = False # Build main_layout title_label = CustomLabel("Edit parameters") title_label.setStyleSheet(style.NODE_LABEL_STYLE) title_label.setAlignment(Qt.AlignCenter) self.layout.addWidget(title_label, 0, 0, 1, 2) # Input box in_dim_label = CustomLabel("Input") in_dim_label.setStyleSheet(style.IN_DIM_LABEL_STYLE) in_dim_label.setAlignment(Qt.AlignRight) self.layout.addWidget(in_dim_label, 1, 0) in_dim_box = CustomTextBox() in_dim_box.setText(','.join(map(str, node_block.in_dim))) in_dim_box.setValidator(ArithmeticValidator.TENSOR) self.layout.addWidget(in_dim_box, 1, 1) self.parameters["in_dim"] = in_dim_box if not node_block.is_head: in_dim_box.setReadOnly(True) # Display parameters if present counter = 2 if node_block.node.param: counter = self.append_node_params(node_block.node, node_block.block_data) # "Apply" button which saves changes apply_button = CustomButton("Apply") apply_button.clicked.connect(self.save_data) self.layout.addWidget(apply_button, counter, 0) # "Cancel" button which closes the dialog without saving cancel_button = CustomButton("Cancel") cancel_button.clicked.connect(self.close) self.layout.addWidget(cancel_button, counter, 1) self.layout.setColumnStretch(0, 1) self.layout.setColumnStretch(1, 1) self.render_layout()
def __init__(self, node_block: NodeBlock): super().__init__(node_block.node.name, "") self.layout = QGridLayout() # Connect node self.node = node_block self.new_in_dim = ','.join(map(str, node_block.in_dim)) self.in_dim_box = CustomTextBox() self.has_edits = False # Build main_layout title_label = CustomLabel("Edit network input") title_label.setStyleSheet(style.NODE_LABEL_STYLE) title_label.setAlignment(Qt.AlignCenter) self.layout.addWidget(title_label, 0, 0, 1, 2) # Input box in_dim_label = CustomLabel("Input shape") in_dim_label.setStyleSheet(style.IN_DIM_LABEL_STYLE) in_dim_label.setAlignment(Qt.AlignRight) self.layout.addWidget(in_dim_label, 1, 0) self.in_dim_box.setText(self.new_in_dim) self.in_dim_box.setValidator(ArithmeticValidator.TENSOR) self.layout.addWidget(self.in_dim_box, 1, 1) if not node_block.is_head: self.in_dim_box.setReadOnly(True) # "Apply" button which saves changes apply_button = CustomButton("Apply") apply_button.clicked.connect(self.save_data) self.layout.addWidget(apply_button, 2, 0) # "Cancel" button which closes the dialog without saving cancel_button = CustomButton("Cancel") cancel_button.clicked.connect(self.close) self.layout.addWidget(cancel_button, 2, 1) self.layout.setColumnStretch(0, 1) self.layout.setColumnStretch(1, 1) self.render_layout()
def __init__(self, message: str, message_type: MessageType): super().__init__("", message) # Set the dialog stile depending on message_type if message_type == MessageType.MESSAGE: title_label = CustomLabel("Message") title_label.setStyleSheet(style.NODE_LABEL_STYLE) else: title_label = CustomLabel("Error") title_label.setStyleSheet(style.ERROR_LABEL_STYLE) title_label.setAlignment(Qt.AlignCenter) # Set content label mess_label = CustomLabel("\n" + self.content + "\n") mess_label.setAlignment(Qt.AlignCenter) # Add a button to close the dialog ok_button = CustomButton("Ok") ok_button.clicked.connect(self.close) # Compose widgets self.layout.addWidget(title_label) self.layout.addWidget(mess_label) self.layout.addWidget(ok_button) self.render_layout()
class PropertyBlock(GraphicBlock): """ This class represents the widget associated to a SMTLIB property in CoCoNet. Attributes ---------- property_type : str The property type (SMT, Polyhedral...). smt_string : str The SMT-LIB expression of the property. property_label : CustomLabel The visible label of the property. condition_label : CustomLabel The POST or PRE label of the property. variables : list The list of admissible variables for the property. """ def __init__(self, block_id: str, p_type: str): super().__init__(block_id) self.property_type = p_type self.pre_condition = True self.smt_string = "" if p_type == "Generic SMT": self.label_string = "-" elif p_type == "Polyhedral": self.label_string = "Ax - b <= 0" self.condition_label = CustomLabel("PRE") self.property_label = CustomLabel(self.label_string) self.variables = [] self.init_layout() self.init_context_menu() def init_layout(self) -> None: """ This method sets up the the property block main_layout with the property parameters. """ # Override title label self.title_label.setText(self.property_type) self.title_label.setStyleSheet(style.PROPERTY_TITLE_STYLE) self.condition_label.setStyleSheet(style.PROPERTY_CONDITION_STYLE) self.main_layout.addWidget(self.title_label) self.main_layout.addWidget(self.condition_label) self.init_grid() formula_label = CustomLabel("Formula") formula_label.setStyleSheet(style.PAR_NODE_STYLE) self.property_label.setStyleSheet(style.DIM_NODE_STYLE) self.content_layout.addWidget(formula_label, 1, 0) self.content_layout.addWidget(self.property_label, 1, 1) def init_context_menu(self): """ This method sets up the context menu actions that are available for the block. """ block_actions = dict() block_actions["Define"] = QAction("Define...", self) self.set_context_menu(block_actions) def set_label(self): self.property_label.setText(self.label_string) def set_smt_label(self): self.property_label.setText(self.smt_string) def update_condition_label(self): if self.pre_condition: self.condition_label.setText("PRE") else: self.condition_label.setText("POST")
def init_layout(self) -> None: """ This method sets up the the node block main_layout with attributes and values. """ self.init_grid() # Iterate and display parameters, count rows par_labels = dict() count = 1 for name, param in self.node.param.items(): # Set the label par_labels[name] = CustomLabel(name) par_labels[name].setAlignment(Qt.AlignLeft) par_labels[name].setStyleSheet(style.PAR_NODE_STYLE) self.dim_labels[name] = CustomLabel() self.dim_labels[name].setAlignment(Qt.AlignCenter) self.dim_labels[name].setStyleSheet(style.DIM_NODE_STYLE) self.content_layout.addWidget(par_labels[name], count, 0) self.content_layout.addWidget(self.dim_labels[name], count, 1) count += 1 # Init block data with default values if "default" in param.keys() and param["default"] == "None": self.block_data[name] = None elif param["type"] == "Tensor": if "shape" in param.keys(): shape = self.text_to_tuple(param["shape"]) self.block_data[name] = Tensor( shape=shape, buffer=np.random.normal(size=shape)) else: self.block_data[name] = Tensor( shape=(1, 1), buffer=np.random.normal(size=(1, 1))) elif param["type"] == "int": if "default" in param.keys(): if param["default"] == "rand": self.block_data[name] = 1 else: self.block_data[name] = int(param["default"]) else: self.block_data[name] = 1 elif param["type"] == "list of ints": if "default" in param.keys(): self.block_data[name] = tuple( map(int, param["default"].split(', '))) else: self.block_data[name] = (1, 1) elif param["type"] == "float": if "default" in param.keys(): if param["default"] == "rand": self.block_data[name] = 1 else: self.block_data[name] = float(param["default"]) else: self.block_data[name] = 0.1 elif param["type"] == "boolean": if "default" in param.keys(): self.block_data[name] = bool(param["default"]) else: self.block_data[name] = False self.update_labels() self.edited.connect(lambda: self.update_labels())
class MainWindow(QtWidgets.QMainWindow): """ This class is the main window of the program, containing all the graphics objects such as the toolbar, the state bar, the menu and the canvas scene. Attributes ---------- SYSNAME : str The application name displayed in the window. nav_menu_bar : QMenuBar Menu bar of the window, containing different menus. status_bar : QStatusBar Status bar of the window. toolbar : BlocksToolbar Toolbar appearing on the left of the window, showing several buttons to add elements to the canvas. parameters : ParamToolbar Fixed toolbar on the right of the window, displaying details about a certain block. canvas : Canvas Central view of the window, containing a blank space in which the blocks appear. Methods ---------- connect_events() Connects to all signals of the elements. init_menu_bar() Sets all menus of the menu bar and their actions. update_status() Changes the status bar displaying on it the canvas mode and the selected items. change_draw_mode(DrawingMode) Changes the drawing mode of the canvas. create_from(NodeButton) Draws in the canvas the block corresponding to the button pressed. reset() Clears both graphical and logical network. open() Procedure to open an existing network. save(bool) Saves the current network in a new file or in the opened one. """ def __init__(self): super(MainWindow, self).__init__() # Init window appearance self.SYSNAME = "CoCoNet" self.setWindowTitle(self.SYSNAME) self.setWindowIcon(QtGui.QIcon(ROOT_DIR + '/res/icons/logo_square.png')) self.setStyleSheet("background-color: " + style.GREY_1) # Navigation menu self.nav_menu_bar = self.menuBar() self.init_nav_menu_bar() # Blocks toolbar self.toolbar = BlocksToolbar(ROOT_DIR + '/res/json/blocks.json') # Parameters toolbar self.parameters = ParamToolbar() # Drawing Canvas self.canvas = Canvas(self.toolbar.blocks) # Status bar self.status_bar = QStatusBar() self.status_bar.setSizeGripEnabled(False) self.setStatusBar(self.status_bar) self.status_bar.setStyleSheet(style.STATUS_BAR_STYLE) self.status_bar_mode_label = CustomLabel() self.status_bar_mode_label.setStyleSheet(style.STATUS_BAR_WIDGET_STYLE) self.status_bar_selections_label = CustomLabel() self.status_bar_selections_label.setStyleSheet(style.STATUS_BAR_WIDGET_STYLE) self.status_bar.addPermanentWidget(self.status_bar_selections_label) self.status_bar.addPermanentWidget(self.status_bar_mode_label) # And adding them to the window self.addDockWidget(Qt.RightDockWidgetArea, self.parameters, Qt.Vertical) self.addToolBar(QtCore.Qt.ToolBarArea.LeftToolBarArea, self.toolbar) self.setCentralWidget(self.canvas.view) self.connect_events() def connect_events(self): """ Associate the various events coming from button signals and other graphical objects to the correct actions. """ # Block buttons for b in itertools.chain(self.toolbar.b_buttons.values(), self.toolbar.p_buttons.values()): b.clicked.connect(self.create_from(b)) # Draw line button self.toolbar.f_buttons["draw_line"].clicked \ .connect(lambda: self.change_draw_mode(DrawingMode.DRAW_LINE)) # Insert block button self.toolbar.f_buttons["insert_block"].clicked \ .connect(lambda: self.change_draw_mode(DrawingMode.DRAW_BLOCK)) # Parameters box appearing self.canvas.param_requested \ .connect(lambda: self.parameters.display(self.canvas.block_to_show)) # State bar updating self.canvas.scene.has_changed_mode \ .connect(lambda: self.update_status()) self.canvas.scene.selectionChanged \ .connect(lambda: self.update_status()) def init_nav_menu_bar(self): """ This method creates the navigation bar by adding the menus and corresponding actions. """ self.nav_menu_bar.setStyleSheet(style.MENU_BAR_STYLE) self.setContextMenuPolicy(Qt.PreventContextMenu) # Create top-level menu menu_file = self.nav_menu_bar.addMenu("File") menu_file.setStyleSheet(style.MENU_BAR_STYLE) menu_edit = self.nav_menu_bar.addMenu("Edit") menu_edit.setStyleSheet(style.MENU_BAR_STYLE) menu_view = self.nav_menu_bar.addMenu("View") menu_view.setStyleSheet(style.MENU_BAR_STYLE) # File actions new_action = QAction("New...", self) new_action.setShortcut("Ctrl+N") new_action.triggered.connect(lambda: self.reset()) open_action = QAction("Open...", self) open_action.setShortcut("Ctrl+O") open_action.triggered.connect(lambda: self.open()) load_p_action = QAction("Load property...", self) load_p_action.triggered.connect(lambda: self.canvas.project.open_property()) save_action = QAction("Save", self) save_action.setShortcut("Ctrl+S") save_action.triggered.connect(lambda: self.save(False)) save_as_action = QAction("Save as...", self) save_as_action.setShortcut("Ctrl+Shift+S") save_as_action.triggered.connect(lambda: self.save()) close_action = QAction("Exit", self) close_action.triggered.connect(lambda: self.close()) # Edit actions copy_action = QAction("Copy", self) copy_action.setShortcut("Ctrl+C") copy_action.triggered.connect(lambda: self.canvas.copy_selected()) paste_action = QAction("Paste", self) paste_action.setShortcut("Ctrl+V") paste_action.triggered.connect(lambda: self.canvas.paste_selected()) cut_action = QAction("Cut", self) cut_action.setShortcut("Ctrl+X") cut_action.triggered.connect(lambda: self.canvas.cut_selected()) del_action = QAction("Delete", self) del_action.setShortcut("DEL") del_action.triggered.connect(lambda: self.canvas.delete_selected()) clear_action = QAction("Clear", self) clear_action.setShortcut("Ctrl+Shift+C") clear_action.triggered.connect(lambda: self.clear()) draw_line_action = QAction("Draw connection", self) draw_line_action.setShortcut("Ctrl+D") draw_line_action.triggered.connect(lambda: self.change_draw_mode(DrawingMode.DRAW_LINE)) insert_block_action = QAction("Insert block in connection", self) insert_block_action.setShortcut("Ctrl+I") insert_block_action.triggered.connect(lambda: self.change_draw_mode(DrawingMode.DRAW_BLOCK)) prop_action = QAction("Edit", self) prop_action.setShortcut("Ctrl+E") prop_action.triggered.connect(lambda: self.canvas.scene.edit_node(self.edit_action_validation())) # View actions z_in_action = QAction("Zoom in", self) z_in_action.setShortcut("Ctrl++") z_in_action.triggered.connect(lambda: self.canvas.zoom_in()) z_out_action = QAction("Zoom out", self) z_out_action.setShortcut("Ctrl+-") z_out_action.triggered.connect(lambda: self.canvas.zoom_out()) dims_action = QAction("Dimensions", self) dims_action.setCheckable(True) dims_action.setChecked(True) dims_action.toggled.connect(lambda: self.canvas.scene.switch_dim_visibility()) toolbar_action = QAction("Tools", self) toolbar_action.setCheckable(True) toolbar_action.setChecked(True) toolbar_action.toggled.connect(lambda: self.toolbar.change_tools_mode()) blocks_action = QAction("Blocks library", self) blocks_action.setCheckable(True) blocks_action.setChecked(True) blocks_action.toggled.connect(lambda: self.toolbar.change_blocks_mode()) details_action = QAction("Parameters", self) details_action.setShortcut("Ctrl+P") details_action.triggered.connect(lambda: self.canvas.show_parameters(self.parameters_action_validation())) # Build File menu menu_file.addAction(new_action) menu_file.addAction(open_action) menu_file.addAction(load_p_action) menu_file.addSeparator() menu_file.addAction(save_action) menu_file.addAction(save_as_action) menu_file.addAction(close_action) # Build Edit menu menu_edit.addSeparator() menu_edit.addAction(copy_action) menu_edit.addAction(paste_action) menu_edit.addAction(cut_action) menu_edit.addAction(del_action) menu_edit.addSeparator() menu_edit.addAction(clear_action) menu_edit.addSeparator() menu_edit.addAction(draw_line_action) menu_edit.addAction(insert_block_action) menu_edit.addSeparator() menu_edit.addAction(prop_action) # Build View menu menu_view.addAction(z_in_action) menu_view.addAction(z_out_action) menu_view.addSeparator() toolbars_menu = menu_view.addMenu("Show") toolbars_menu.addAction(toolbar_action) toolbars_menu.addAction(blocks_action) toolbars_menu.addAction(dims_action) menu_view.addSeparator() menu_view.addAction(details_action) # Help menu self.nav_menu_bar.addAction("Help", self.show_help) def create_from(self, button: CustomButton): """ This method draws on the canvas the block corresponding to the pressed BlockButton. Parameters ---------- button : CustomButton The pressed button. """ def pressed(): if isinstance(button, NodeButton): self.canvas.draw_node(button.node_type) elif isinstance(button, PropertyButton): if self.canvas.project.network.nodes: self.canvas.draw_property(button.name) return pressed def update_status(self): """ This method updates the widget in the status bar, displaying the items selected and the current drawing mode. """ # Show the canvas drawing mode if self.canvas.scene.mode == DrawingMode.DRAW_LINE: self.status_bar_mode_label.setText("GraphicLine drawing") elif self.canvas.scene.mode == DrawingMode.DRAW_BLOCK: self.status_bar_mode_label.setText("Block insertion") else: self.status_bar_mode_label.setText("") # Show the selected items, if any if not self.canvas.scene.selectedItems(): self.status_bar_selections_label.setText("") else: selections = "" semicolons = ["; " for _ in range(len(self.canvas.scene.selectedItems()))] semicolons[-1] = "" # No semicolon for the last element in the selections list for counter, item in enumerate(self.canvas.scene.selectedItems()): if type(item) is QGraphicsRectItem: # If the item is a rect, prev_node_id is written selections += self.canvas.scene.blocks[item].block_id selections += semicolons[counter] elif type(item) is GraphicLine: # If the item is a line, origin and destination ids are written origin = self.canvas.scene.blocks[item.origin].block_id destination = self.canvas.scene.blocks[item.destination].block_id selections += origin + "->" + destination selections += semicolons[counter] self.status_bar_selections_label.setText(selections) def change_draw_mode(self, newmode: DrawingMode = None): """ This method changes the drawing mode of the canvas when the user clicks on the corresponding button. The mode changes depending on the previous one. Parameters ---------- newmode : DrawingMode, optional Specifies the new DrawingMode to use. (Default: None) """ if newmode is None: self.canvas.scene.set_mode(DrawingMode.IDLE) else: curmode = self.canvas.scene.mode if newmode == curmode: self.canvas.scene.set_mode(DrawingMode.IDLE) else: self.canvas.scene.set_mode(newmode) def clear(self): """ Utility for deleting the content of the window. Before taking effect, it prompts the user to confirm. """ if self.canvas.num_nodes > 0: alert_dialog = ConfirmDialog("Clear workspace", "The network will be erased and your work will be lost.\n" "Do you wish to continue?") alert_dialog.exec() if alert_dialog.confirm: self.canvas.clear_scene() self.canvas.scene.has_changed_mode.connect(lambda: self.update_status()) self.canvas.scene.selectionChanged.connect(lambda: self.update_status()) self.update_status() self.setWindowTitle(self.SYSNAME) else: self.canvas.clear_scene() self.canvas.scene.has_changed_mode.connect(lambda: self.update_status()) self.canvas.scene.selectionChanged.connect(lambda: self.update_status()) self.update_status() self.setWindowTitle(self.SYSNAME) def reset(self): """ This method clears the scene and the network, stops to work on the file and restarts from scratch. """ self.clear() self.canvas.project.file_name = ("", "") self.setWindowTitle(self.SYSNAME) def open(self): """ This method handles the opening of a file. """ if self.canvas.renderer.disconnected_network: # If there is already a network in the canvas, it is asked to the # user if continuing with opening. confirm_dialog = ConfirmDialog("Open network", "A new network will be opened " "cancelling the current nodes.\n" "Do you wish to continue?") confirm_dialog.exec() # If the user clicks on "yes", the canvas is cleaned, a net is # opened and the window title is updated. if confirm_dialog is not None: if confirm_dialog.confirm: # The canvas is cleaned self.canvas.clear_scene() self.canvas.scene.has_changed_mode.connect(lambda: self.update_status()) self.canvas.scene.selectionChanged.connect(lambda: self.update_status()) self.update_status() # A file is opened self.canvas.project.open() if self.canvas.project.network is not None: self.setWindowTitle(self.SYSNAME + " - " + self.canvas.project.network.identifier) else: # If the canvas was already empty, the opening function is directly # called self.canvas.project.open() if self.canvas.project.network is not None: self.setWindowTitle(self.SYSNAME + " - " + self.canvas.project.network.identifier) def save(self, _as: bool = True): """ This method saves the current network if the format is correct Parameters ---------- _as : bool, optional This attribute distinguishes between "save" and "save as". If _as is True the network will be saved in a new file, while if _as is False the network will overwrite the current one. (Default: True) """ if len(self.canvas.renderer.NN.nodes) == 0 or \ len(self.canvas.renderer.NN.edges) == 0: # Limit case: one disconnected node -> new network with one node if len(self.canvas.renderer.disconnected_network) == 1: for node in self.canvas.renderer.disconnected_network: try: self.canvas.renderer.add_node_to_nn(node) self.canvas.project.save(_as) self.setWindowTitle(self.SYSNAME + " - " + self.canvas.project.network.identifier) except Exception as e: error_dialog = MessageDialog(str(e), MessageType.ERROR) error_dialog.exec() # More than one disconnected nodes cannot be saved elif len(self.canvas.renderer.disconnected_network) > 1: not_sequential_dialog = MessageDialog("The network is not sequential, and " "cannot be saved.", MessageType.ERROR) not_sequential_dialog.exec() else: # Network is empty message = MessageDialog("The network is empty!", MessageType.MESSAGE) message.exec() elif self.canvas.renderer.is_nn_sequential(): # If there are logical nodes, the network is sequential every_node_connected = True # every node has to be in the nodes dictionary for node in self.canvas.renderer.disconnected_network: if node not in self.canvas.project.network.nodes: every_node_connected = False break if every_node_connected: self.canvas.project.save(_as) self.setWindowTitle(self.SYSNAME + " - " + self.canvas.project.network.identifier) else: # If there are disconnected nodes, a message is displayed to the # user to choose if saving only the connected network confirm_dialog = ConfirmDialog("Save network", "All the nodes outside the " "sequential network will lost.\n" "Do you wish to continue?") confirm_dialog.exec() if confirm_dialog.confirm: self.canvas.project.save(_as) self.setWindowTitle(self.SYSNAME + " - " + self.canvas.project.network.identifier) else: # If the network is not sequential, it cannot be saved. not_sequential_dialog = MessageDialog("The network is not sequential and " "cannot be saved.", MessageType.ERROR) not_sequential_dialog.exec() def edit_action_validation(self) -> Optional[NodeBlock]: """ This method performs a check on the object on which the edit action is called, in order to prevent unwanted operations. Returns ---------- NodeBlock The graphic wrapper of the NetworkNode selected, if present. """ if self.canvas.scene.selectedItems(): if type(self.canvas.scene.selectedItems()[0]) is QGraphicsRectItem: # Return block graphic object return self.canvas.scene.blocks[self.canvas.scene.selectedItems()[0]] elif type(self.canvas.scene.selectedItems()[0]) is GraphicLine: msg_dialog = MessageDialog("Can't edit edges, please select a block instead.", MessageType.ERROR) msg_dialog.show() else: err_dialog = MessageDialog("No block selected.", MessageType.MESSAGE) err_dialog.show() def parameters_action_validation(self) -> Optional[NodeBlock]: """ This method performs a check on the object on which the parameters action is called, in order to prevent unwanted operations. Returns ---------- NodeBlock The graphic wrapper of the NetworkNode selected, if present. """ if self.canvas.scene.selectedItems(): if type(self.canvas.scene.selectedItems()[0]) is QGraphicsRectItem: # Return block graphic object return self.canvas.scene.blocks[self.canvas.scene.selectedItems()[0]] elif type(self.canvas.scene.selectedItems()[0]) is GraphicLine: msg_dialog = MessageDialog("No parameters available for connections.", MessageType.ERROR) msg_dialog.show() else: err_dialog = MessageDialog("No block selected.", MessageType.MESSAGE) err_dialog.show() @staticmethod def show_help(): help_dialog = HelpDialog() help_dialog.exec()