Skip to content
Snippets Groups Projects
Commit 36fa1110 authored by Oscar Gustafsson's avatar Oscar Gustafsson
Browse files

Format gui code and rename constants

parent d7361dec
No related branches found
No related tags found
No related merge requests found
Pipeline #104092 passed
Showing
with 304 additions and 296 deletions
......@@ -13,7 +13,6 @@ from simudator.core.processor import Processor
class BreakpointWindow(QWidget):
def __init__(self, cpu: Processor):
super().__init__()
self.cpu = cpu
......
......@@ -6,7 +6,7 @@ to edit.
from qtpy.QtGui import QColor
class ColorScheme():
class ColorScheme:
Window = QColor(125, 174, 163)
ModuleBackground = QColor(212, 190, 152)
ModuleOutline = QColor(0, 0, 0)
......
......@@ -13,6 +13,7 @@ class CpuGraphicsScene(QGraphicsScene):
and handels mouse inputs for interacting with these graphicsitems.
Can create a default layout on creation and can save/load new layouts.
"""
MODULE_SPACEING = 100
def __init__(self, cpu: Processor):
......@@ -44,20 +45,17 @@ class CpuGraphicsScene(QGraphicsScene):
is equal to the y value. Used to place all graphics items in a
diagonal.
"""
placement = len(self.module_graphics_items)*self.MODULE_SPACEING
placement = len(self.module_graphics_items) * self.MODULE_SPACEING
graphics_item.setPos(placement, placement)
self.addItem(graphics_item)
def replaceModuleGraphicsItem(self,
graphics_item: ModuleGraphicsItem,
pos_x: int,
pos_y: int
) -> None:
def replaceModuleGraphicsItem(
self, graphics_item: ModuleGraphicsItem, pos_x: int, pos_y: int
) -> None:
"""
Changes the postions of an existing modules graphics item.
"""
graphics_item.setPos(pos_x*self.MODULE_SPACEING,
pos_y*self.MODULE_SPACEING)
graphics_item.setPos(pos_x * self.MODULE_SPACEING, pos_y * self.MODULE_SPACEING)
def updateGraphicsItems(self):
"""
......@@ -97,7 +95,6 @@ class CpuGraphicsScene(QGraphicsScene):
port_1.toggled.connect(signal_w.toggleVisibility)
port_2.toggled.connect(signal_w.toggleVisibility)
def getModulesGraphicsItems(self) -> list[ModuleGraphicsItem]:
return list(self.module_graphics_items.values())
......@@ -121,7 +118,6 @@ class CpuGraphicsScene(QGraphicsScene):
# Go through each line in the file
for line in file.readlines():
# If no name currently saved then get name from current line
if graphics_item_name is None:
graphics_item_name = line.partition(":")[0]
......@@ -163,12 +159,10 @@ class CpuGraphicsScene(QGraphicsScene):
file.close()
def setAllSignalsVisibility(self, is_signals_visible: bool) -> None:
for item in self.signal_graphics_items:
item.setVisible(is_signals_visible)
def setPortNamesVisibility(self, is_ports_visible: bool) -> None:
for item in self.module_graphics_items.values():
for port in item.ports:
port.setNameVisibility(is_ports_visible)
......
......@@ -10,6 +10,5 @@ class CustomToolBar(QToolBar):
def __init__(self, text):
super().__init__(text)
def contextMenuEvent(self, event):
pass
......@@ -15,11 +15,12 @@ from qtpy.QtWidgets import (
class LambdaBreakpointDialog(QDialog):
accepted = pyqtSignal(str, str, name="accepted")
def __init__(self,
lambdas: list[str],
parent: Optional['QWidget'] = None,
flags: Qt.WindowFlags | Qt.WindowType = Qt.WindowFlags()
) -> None:
def __init__(
self,
lambdas: list[str],
parent: Optional['QWidget'] = None,
flags: Qt.WindowFlags | Qt.WindowType = Qt.WindowFlags(),
) -> None:
super().__init__(parent, flags)
self.lambdaSelectWidget = QComboBox()
......
......@@ -17,15 +17,16 @@ from simudator.core import Module
class MemoryContentDialog(QDialog):
accepted = pyqtSignal(str, str, str, name="accepted")
def __init__(self,
memory: Module,
parent: Optional['QWidget'] = None,
flags: Qt.WindowFlags | Qt.WindowType = Qt.WindowFlags()
) -> None:
def __init__(
self,
memory: Module,
parent: Optional['QWidget'] = None,
flags: Qt.WindowFlags | Qt.WindowType = Qt.WindowFlags(),
) -> None:
super().__init__(parent, flags)
self.memory = memory
self.memory_name =memory.get_state()['name']
self.memory_name = memory.get_state()['name']
adresses = [str(i) for i in range(len(memory.get_state()['memory']))]
......@@ -57,7 +58,6 @@ class MemoryContentDialog(QDialog):
value = memory_content[selectedAdress]
self.valuesWidget.setText(str(value))
def signalAccepted(self) -> None:
adress = self.adressSelectWidget.currentText()
enteredValues = self.valuesWidget.text()
......
......@@ -17,11 +17,12 @@ from simudator.core import Module
class ModuleStateDialog(QDialog):
accepted = pyqtSignal(str, str, str, name='okSignal')
def __init__(self,
module: Module,
parent: Optional['QWidget'] = None,
flags: Qt.WindowFlags | Qt.WindowType = Qt.WindowFlags()
) -> None:
def __init__(
self,
module: Module,
parent: Optional['QWidget'] = None,
flags: Qt.WindowFlags | Qt.WindowType = Qt.WindowFlags(),
) -> None:
super().__init__(parent, flags)
self.module = module
......
......@@ -42,6 +42,7 @@ class View(QGraphicsView):
This allows the users to navigate the view with their trackpads
and zoom in/out with their trackpads + ctrl.
"""
def __init__(self, QGraphicsScene):
super().__init__(QGraphicsScene)
self.scene = QGraphicsScene
......@@ -52,7 +53,6 @@ class View(QGraphicsView):
"""
modifiers = QtWidgets.QApplication.keyboardModifiers()
if modifiers == QtCore.Qt.ControlModifier:
# Factor above 1 zooms in, below zooms out
factor = 1.03
if event.angleDelta().y() < 0:
......@@ -63,10 +63,7 @@ class View(QGraphicsView):
return
view_pos = event.globalPosition()
scene_pos = self.mapToScene(
int(view_pos.x()),
int(view_pos.y())
)
scene_pos = self.mapToScene(int(view_pos.x()), int(view_pos.y()))
self.centerOn(scene_pos)
self.scale(factor, factor)
......@@ -79,7 +76,6 @@ class View(QGraphicsView):
self.centerOn(scene_pos - delta)
else:
# Default behaviour
super().wheelEvent(event)
......@@ -104,7 +100,7 @@ class GUI(QMainWindow):
self.setWindowTitle("SimuDator")
self.cpu_graphics_scene = CpuGraphicsScene(cpu)
self.graphics_view = View(self.cpu_graphics_scene)
#self.graphics_view.setDragMode(True)
# self.graphics_view.setDragMode(True)
self.moduleActions: dict[str, QAction] = {}
self.setCentralWidget(self.graphics_view)
......@@ -170,7 +166,9 @@ class GUI(QMainWindow):
# create load default layout action
load_default_layout_action = QAction("Load default layout", self)
load_default_layout_action.setStatusTip("Loads the default layout from file.")
load_default_layout_action.triggered.connect(self.loadDefaultLayoutToolBarButtonClick)
load_default_layout_action.triggered.connect(
self.loadDefaultLayoutToolBarButtonClick
)
# create save layout action
save_layout_action = QAction("Save layout", self)
......@@ -183,13 +181,13 @@ class GUI(QMainWindow):
self.lock_layout_action.triggered.connect(self.toggleLayoutLockMenuButtonClick)
# Create show signals actions
self.signal_vis_action= QAction("Show signals", self, checkable=True)
self.signal_vis_action = QAction("Show signals", self, checkable=True)
self.signal_vis_action.setChecked(True)
self.signal_vis_action.setStatusTip("Toggle the visibility of signal.")
self.signal_vis_action.triggered.connect(self.showSignalsMenuButtonClick)
# Create show port name actions
self.port_vis_action= QAction("Show port names", self, checkable=True)
self.port_vis_action = QAction("Show port names", self, checkable=True)
self.port_vis_action.setChecked(True)
self.port_vis_action.setStatusTip("Toggle the visibility of port names.")
self.port_vis_action.triggered.connect(self.showPortNamesBarButtonClick)
......@@ -204,7 +202,7 @@ class GUI(QMainWindow):
layout_menu.addAction(self.port_vis_action)
# Create breakpoint window action
self.breakpoint_action= QAction("Breakpoints", self)
self.breakpoint_action = QAction("Breakpoints", self)
self.breakpoint_action.setStatusTip("Open breakpoint window.")
self.breakpoint_action.triggered.connect(self.openBreakpointWindow)
......@@ -228,7 +226,7 @@ class GUI(QMainWindow):
# Add undo button on toolbar
backward_arrow_icon = self.style().standardIcon(QStyle.SP_MediaSeekBackward)
self.undo_action= QAction(backward_arrow_icon, "Undo", self)
self.undo_action = QAction(backward_arrow_icon, "Undo", self)
self.undo_action.setStatusTip("Undo the last processor tick")
self.undo_action.triggered.connect(self.undoToolBarButtonClick)
toolbar.addAction(self.undo_action)
......@@ -295,7 +293,6 @@ class GUI(QMainWindow):
self.cpu_graphics_scene.updateGraphicsItems()
self.clock_label.setText("Clockcycle: " + str(self.cpu.get_clock()))
def lambdaBreakpointDialog(self) -> None:
"""
Opens dialog window for user to create a breakpoint.
......@@ -317,6 +314,7 @@ class GUI(QMainWindow):
and specify a C++ signature for it, which is used most commonly
in order to select a particular overload.
"""
@Slot(str, str, str)
def editModuleState(self, module_name, state, value) -> None:
"""
......@@ -346,9 +344,9 @@ class GUI(QMainWindow):
except SyntaxError as e:
self.errorMessageWidget.showMessage(str(e))
except ValueError:
self.errorMessageWidget.showMessage("You must enter a hexadecimal"
"number preceeded by '0x' (e.g."
"0xc3).")
self.errorMessageWidget.showMessage(
"You must enter a hexadecimal" "number preceeded by '0x' (e.g." "0xc3)."
)
else:
module = self.cpu.get_module(module_name)
module_state = module.get_state()
......@@ -356,7 +354,6 @@ class GUI(QMainWindow):
module.set_state(module_state)
self.cpu_graphics_scene.updateGraphicsItems()
@Slot(str, str, str)
def addStateBreakpoint(self, module_name: str, state: str, value: str) -> None:
"""
......@@ -425,10 +422,7 @@ class GUI(QMainWindow):
self.cpu_running = True
self.setDisabledWhenRunning(True)
self.cpu.unstop()
simultaion_thread = RunThread(self.cpu,
self.halted_signal,
False,
steps)
simultaion_thread = RunThread(self.cpu, self.halted_signal, False, steps)
self.threadpool.start(simultaion_thread)
self.updateCpuListeners()
......@@ -482,7 +476,7 @@ class GUI(QMainWindow):
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.AnyFile)
dialog.setAcceptMode(QFileDialog.AcceptOpen)
dialog.setDirectory("~/simudator") # TODO: does this work when exported?
dialog.setDirectory("~/simudator") # TODO: does this work when exported?
# this is static so none of the above matters...
return dialog.getSaveFileName()[0]
......@@ -494,7 +488,7 @@ class GUI(QMainWindow):
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.AnyFile)
dialog.setAcceptMode(QFileDialog.AcceptOpen)
dialog.setDirectory("~/simudator") # TODO: does this work when exported?
dialog.setDirectory("~/simudator") # TODO: does this work when exported?
return dialog.getOpenFileName()[0]
def loadToolBarButtonClick(self) -> None:
......@@ -533,8 +527,9 @@ class GUI(QMainWindow):
if self.cpu_running:
return
answer = QMessageBox.question(self, "Reset Processor",
"Are you sure you want to reset the processor?")
answer = QMessageBox.question(
self, "Reset Processor", "Are you sure you want to reset the processor?"
)
if answer == QMessageBox.Yes:
self.cpu.reset()
......@@ -549,10 +544,11 @@ class GUI(QMainWindow):
if self.cpu_running:
return
cycles, ok = QInputDialog(self).getInt(self,
"Input number of cycles to run",
"Input number of cycles to run",
)
cycles, ok = QInputDialog(self).getInt(
self,
"Input number of cycles to run",
"Input number of cycles to run",
)
if ok:
if cycles < 1:
self.errorBox("Please input a number larger than 0.")
......@@ -617,9 +613,9 @@ class GUI(QMainWindow):
module_graphic = self.cpu_graphics_scene.module_graphics_items[key]
module_graphic.showPorts()
counter += 1
self.cpu_graphics_scene.replaceModuleGraphicsItem(module_graphic,
counter,
counter)
self.cpu_graphics_scene.replaceModuleGraphicsItem(
module_graphic, counter, counter
)
self.cpu_graphics_scene.resetSignals()
def loadLayoutFromFile(self, file) -> None:
......@@ -663,11 +659,12 @@ class GUI(QMainWindow):
fp.close()
def loadSignal(self,
graphic_signal: SignalGraphicsItem,
signal_points: list[tuple[float, float]],
visibility: bool
) -> None:
def loadSignal(
self,
graphic_signal: SignalGraphicsItem,
signal_points: list[tuple[float, float]],
visibility: bool,
) -> None:
"""
Changes the graphical signal to have the positions given
as argument.
......@@ -682,11 +679,12 @@ class GUI(QMainWindow):
graphic_signal.setPoints(qpoints)
graphic_signal.setVisible(visibility)
def loadGraphicsModule(self,
graphics_module: ModuleGraphicsItem,
graphics_module_x: float,
graphics_module_y: float,
) -> None:
def loadGraphicsModule(
self,
graphics_module: ModuleGraphicsItem,
graphics_module_x: float,
graphics_module_y: float,
) -> None:
"""
Changes the positions of graphical modules to the ones given
as argument.
......@@ -694,13 +692,14 @@ class GUI(QMainWindow):
graphics_module.setX(graphics_module_x)
graphics_module.setY(graphics_module_y)
def loadPort(self,
port: PortGraphicsItem,
x: float,
y: float,
orientation: Orientation,
visibility: bool
) -> None:
def loadPort(
self,
port: PortGraphicsItem,
x: float,
y: float,
orientation: Orientation,
visibility: bool,
) -> None:
port.setOrientation(orientation)
port.setX(x)
port.setY(y)
......@@ -736,22 +735,21 @@ class GUI(QMainWindow):
"""
Toggles showing port names in the graphics scene.
"""
self.cpu_graphics_scene.setPortNamesVisibility(
self.port_vis_action.isChecked())
self.cpu_graphics_scene.setPortNamesVisibility(self.port_vis_action.isChecked())
def showSignalsMenuButtonClick(self):
"""
Toggle shoing the signals in the graphics scene.
"""
self.cpu_graphics_scene.setAllSignalsVisibility(
self.signal_vis_action.isChecked())
self.signal_vis_action.isChecked()
)
def toggleLayoutLockMenuButtonClick(self):
"""
Toggles so the layout can not be edited.
"""
self.cpu_graphics_scene.setLayoutLock(
self.lock_layout_action.isChecked())
self.cpu_graphics_scene.setLayoutLock(self.lock_layout_action.isChecked())
def loadLayoutToolBarButtonClick(self) -> None:
"""
......@@ -760,7 +758,6 @@ class GUI(QMainWindow):
and the default layout will be loaded.
"""
path = self.folderLoadDialog()
# If no file was selected, do nothing
......
......@@ -22,7 +22,7 @@ class MemoryWindow(QWidget):
Widget for showing content of memory
"""
ROW_LENGTH = 5
_ROW_LENGTH = 5
def __init__(self, memory_module: Memory):
super().__init__()
......@@ -38,13 +38,12 @@ class MemoryWindow(QWidget):
def update(self):
memory_str = ""
for adress, value in enumerate(self.module.memory):
# Add adress and content to string
# Make sure its unifrom lenght so rows are consistent
memory_str += f"{adress}" + ": " + f"{value}" + " " + "\t"
# Make new line when we reach end of row
if adress % self.ROW_LENGTH == self.ROW_LENGTH-1:
if adress % self._ROW_LENGTH == self._ROW_LENGTH - 1:
memory_str += "\n"
self.text.setText(memory_str)
......@@ -55,48 +54,50 @@ class MemoryGraphicsItem(ModuleGraphicsItem):
Graphics module for a Memory module.
"""
RECT_WIDTH = 150
RECT_HEIGHT= 200
new_memory_breakpoint_signal = pyqtSignal(str, str, str)
def __init__(self, memory_module: Memory):
def __init__(self, memory_module: Memory, width: int = 150, height: int = 200):
self._width = width
self._height = height
super().__init__(memory_module)
self.memory_window = None
def draw_graphics_item(self) -> None:
# Create base backgrond rect
self.baserect = QGraphicsRectItem(0, 0, self.RECT_WIDTH, self.RECT_HEIGHT, self)
self.baserect = QGraphicsRectItem(0, 0, self._width, self._height, self)
# Make ports
self.input = PortGraphicsItem(self.module.get_input_signal(),
Orientation.RIGHT, self)
self.input.setPos(self.RECT_WIDTH, self.RECT_HEIGHT/8)
self.output = PortGraphicsItem(self.module.get_output_signal(),
Orientation.RIGHT, self)
self.output.setPos(self.RECT_WIDTH, self.RECT_HEIGHT/4)
self.adress = PortGraphicsItem(self.module.get_adress_signal(),
Orientation.DOWN, self)
self.adress.setPos(self.RECT_WIDTH/4, self.RECT_HEIGHT)
self.control = PortGraphicsItem(self.module.get_control_signal(),
Orientation.DOWN, self)
self.control.setPos(self.RECT_WIDTH*3/4, self.RECT_HEIGHT)
self.input = PortGraphicsItem(
self.module.get_input_signal(), Orientation.RIGHT, self
)
self.input.setPos(self._width, self._height / 8)
self.output = PortGraphicsItem(
self.module.get_output_signal(), Orientation.RIGHT, self
)
self.output.setPos(self._width, self._height / 4)
self.adress = PortGraphicsItem(
self.module.get_adress_signal(), Orientation.DOWN, self
)
self.adress.setPos(self._width / 4, self._height)
self.control = PortGraphicsItem(
self.module.get_control_signal(), Orientation.DOWN, self
)
self.control.setPos(self._width * 3 / 4, self._height)
self.ports = [self.input, self.output, self.adress, self.control]
# Create name lable
name_text = QGraphicsSimpleTextItem(self.state["name"], self)
name_text.setPos(self.RECT_WIDTH/2
- len(self.state["name"])*self.CHAR_LEN, 0)
name_text.setPos(self._width / 2 - len(self.state["name"]) * self._CHAR_LEN, 0)
# Create adress lable
self.adress_text = QGraphicsSimpleTextItem("adress: "
+ str(self.state["current_adress"]), self)
self.adress_text.setPos(self.RECT_WIDTH/20, self.RECT_HEIGHT/8)
self.adress_text = QGraphicsSimpleTextItem(
"adress: " + str(self.state["current_adress"]), self
)
self.adress_text.setPos(self._width / 20, self._height / 8)
def update(self):
"""
......@@ -107,7 +108,6 @@ class MemoryGraphicsItem(ModuleGraphicsItem):
if self.memory_window is not None:
self.memory_window.update()
def mousePressEvent(self, event):
"""
Show content window if module is right clicked
......@@ -163,13 +163,13 @@ class MemoryGraphicsItem(ModuleGraphicsItem):
"""
Opens dialog window for user to edit memory.
"""
self.memory_edit_dialog= MemoryContentDialog(self.module)
self.memory_edit_dialog = MemoryContentDialog(self.module)
self.memory_edit_dialog.accepted.connect(self.editMemoryAccepted)
@Slot(str, str, str)
def memoryBreakpointAccepted(self, module_name: str,
adress: str,
value: str) -> None:
def memoryBreakpointAccepted(
self, module_name: str, adress: str, value: str
) -> None:
"""
Takes the info from a breakpoint dialog and sends it to the gui
"""
......
......@@ -16,8 +16,18 @@ from simudator.gui.module_graphics_item.mia.pc_graphic import PcGraphicsItem
from simudator.gui.module_graphics_item.mia.supc_graphic import SupcGraphicsItem
from simudator.gui.module_graphics_item.mia.upc_graphic import uPcGraphicsItem
__all__ = ["MiaMemoryGraphicsItem", "MicroMemoryGraphicsItem", "ArGraphicsItem",
"PcGraphicsItem", "AsrGraphicsItem", "HrGraphicsItem",
"SupcGraphicsItem", "uPcGraphicsItem", "FlagGraphicsItem",
"BusGraphicsItem", "AluGraphicsItem", "GrxGraphicsItem", "IrGraphicsItem"
]
__all__ = [
"MiaMemoryGraphicsItem",
"MicroMemoryGraphicsItem",
"ArGraphicsItem",
"PcGraphicsItem",
"AsrGraphicsItem",
"HrGraphicsItem",
"SupcGraphicsItem",
"uPcGraphicsItem",
"FlagGraphicsItem",
"BusGraphicsItem",
"AluGraphicsItem",
"GrxGraphicsItem",
"IrGraphicsItem",
]
......@@ -13,23 +13,25 @@ class ArGraphicsItem(IntegerRegisterGraphicsItem):
def draw_graphics_item(self):
self.draw_rect()
width = len(self.text.text())*self.RECT_WIDTH_PER_CHAR + self.TEXT_WIDTH_MARGIN
width = (
len(self.text.text()) * self._RECT_WIDTH_PER_CHAR + self._TEXT_WIDTH_MARGIN
)
# Draw bus port
bus_port = PortGraphicsItem(self.module.output_s, parent = self)
bus_port.setPos(
width,
self.RECT_HEIGHT/2)
bus_port = PortGraphicsItem(self.module.output_s, parent=self)
bus_port.setPos(width, self._RECT_HEIGHT / 2)
self.ports.append(bus_port)
# Draw to alu port
to_alu_port = PortGraphicsItem(self.module.alu_output_signal,
Orientation.LEFT, parent = self)
to_alu_port.setPos(0, self.RECT_HEIGHT/2)
to_alu_port = PortGraphicsItem(
self.module.alu_output_signal, Orientation.LEFT, parent=self
)
to_alu_port.setPos(0, self._RECT_HEIGHT / 2)
self.ports.append(to_alu_port)
# Draw from alu port
from_alu_port = PortGraphicsItem(self.module.input_s,
Orientation.UP, parent = self)
from_alu_port.setPos(width/2, 0)
from_alu_port = PortGraphicsItem(
self.module.input_s, Orientation.UP, parent=self
)
from_alu_port.setPos(width / 2, 0)
self.ports.append(from_alu_port)
......@@ -11,21 +11,21 @@ class AsrGraphicsItem(IntegerRegisterGraphicsItem):
"""
def draw_graphics_item(self):
# Draw register rect
self.draw_rect()
width = len(self.text.text())*self.RECT_WIDTH_PER_CHAR + self.TEXT_WIDTH_MARGIN
width = (
len(self.text.text()) * self._RECT_WIDTH_PER_CHAR + self._TEXT_WIDTH_MARGIN
)
# Draw bus port
bus_port = PortGraphicsItem(self.module.input_s, parent = self)
bus_port.setPos(
width,
self.RECT_HEIGHT/2)
bus_port = PortGraphicsItem(self.module.input_s, parent=self)
bus_port.setPos(width, self._RECT_HEIGHT / 2)
self.ports.append(bus_port)
# Draw to memory port
to_memory_port = PortGraphicsItem(self.module.output_s,
Orientation.LEFT, parent = self)
to_memory_port.setPos(0, self.RECT_HEIGHT/2)
to_memory_port = PortGraphicsItem(
self.module.output_s, Orientation.LEFT, parent=self
)
to_memory_port.setPos(0, self._RECT_HEIGHT / 2)
self.ports.append(to_memory_port)
......@@ -20,15 +20,15 @@ class BusGraphicsItem(ModuleGraphicsItem):
PAIR_MARGIN = 60
PORT_MARGIN = 20
def __init__(self, module: Module, signal_pairs: [(Signal)] ):
def __init__(self, module: Module, signal_pairs: [(Signal)]):
self.signal_pairs = signal_pairs
super().__init__(module)
def draw_graphics_item(self) -> None:
# Calculate height according to number of signals and states
height = (math.ceil(len(self.signal_pairs)/2)
)*(self.PAIR_MARGIN+self.PORT_MARGIN)-self.PAIR_MARGIN
height = (math.ceil(len(self.signal_pairs) / 2)) * (
self.PAIR_MARGIN + self.PORT_MARGIN
) - self.PAIR_MARGIN
# Create base background rectangle
self.baserect = QGraphicsRectItem(0, 0, self.WIDTH, height, self)
......@@ -36,7 +36,6 @@ class BusGraphicsItem(ModuleGraphicsItem):
# add port pairs
for index, signals in enumerate(self.signal_pairs):
# x coordinates and orientation will be
# diffrent for every other signal pair
x_pos = self.WIDTH
......@@ -50,16 +49,18 @@ class BusGraphicsItem(ModuleGraphicsItem):
output_port = PortGraphicsItem(signals[0], orientation, self)
output_port.setPos(
x_pos,
(index//2)*(self.PAIR_MARGIN+self.PORT_MARGIN))
x_pos, (index // 2) * (self.PAIR_MARGIN + self.PORT_MARGIN)
)
self.ports.append(output_port)
if signals[1] is not None:
input_port = PortGraphicsItem(signals[1], orientation, self)
input_port.setPos(
x_pos,
(index//2)*(self.PAIR_MARGIN+self.PORT_MARGIN)+self.PORT_MARGIN)
x_pos,
(index // 2) * (self.PAIR_MARGIN + self.PORT_MARGIN)
+ self.PORT_MARGIN,
)
self.ports.append(input_port)
def update(self):
......
......@@ -12,18 +12,16 @@ class HrGraphicsItem(IntegerRegisterGraphicsItem):
def draw_graphics_item(self):
self.draw_rect()
width = len(self.text.text())*self.RECT_WIDTH_PER_CHAR + self.TEXT_WIDTH_MARGIN
width = (
len(self.text.text()) * self._RECT_WIDTH_PER_CHAR + self._TEXT_WIDTH_MARGIN
)
# Draw to bus port
to_bus_port = PortGraphicsItem(self.module.input_s, parent = self)
to_bus_port.setPos(
width,
self.RECT_HEIGHT/4)
to_bus_port = PortGraphicsItem(self.module.input_s, parent=self)
to_bus_port.setPos(width, self._RECT_HEIGHT / 4)
self.ports.append(to_bus_port)
# Draw from bus port
from_bus_port = PortGraphicsItem(self.module.output_s, parent = self)
from_bus_port.setPos(
width,
self.RECT_HEIGHT*3/4)
from_bus_port = PortGraphicsItem(self.module.output_s, parent=self)
from_bus_port.setPos(width, self._RECT_HEIGHT * 3 / 4)
self.ports.append(from_bus_port)
......@@ -9,33 +9,36 @@ class AluGraphicsItem(ModuleGraphicsItem):
"""
Graphics module for mia's ALU module.
"""
RECT_WIDTH = 120
RECT_HEIGHT = 60
def draw_graphics_item(self):
# Base rectangle
self.baserect = QGraphicsRectItem(0, 0, self.RECT_WIDTH, self.RECT_HEIGHT, self)
# Create name lable
name_text = QGraphicsSimpleTextItem(self.state["name"], self)
name_text.setPos(self.RECT_WIDTH/2-len(self.state["name"])*self.CHAR_LEN,
self.RECT_HEIGHT/2-len(self.state["name"])*self.CHAR_LEN)
name_text.setPos(
self.RECT_WIDTH / 2 - len(self.state["name"]) * self._CHAR_LEN,
self.RECT_HEIGHT / 2 - len(self.state["name"]) * self._CHAR_LEN,
)
# make port for input a
port_a = PortGraphicsItem(self.module.input_signal_a, Orientation.UP, self)
port_a.setPos(self.RECT_WIDTH*3/4, 0)
port_a.setPos(self.RECT_WIDTH * 3 / 4, 0)
self.ports.append(port_a)
# make port for input b
port_b = PortGraphicsItem(self.module.input_signal_b, Orientation.UP, self)
port_b.setPos(self.RECT_WIDTH/4, 0)
port_b.setPos(self.RECT_WIDTH / 4, 0)
self.ports.append(port_b)
# make port for output
output_port = PortGraphicsItem(self.module.output_signal,
Orientation.DOWN, self)
output_port.setPos(self.RECT_WIDTH/2, self.RECT_HEIGHT)
output_port = PortGraphicsItem(
self.module.output_signal, Orientation.DOWN, self
)
output_port.setPos(self.RECT_WIDTH / 2, self.RECT_HEIGHT)
self.ports.append(output_port)
def shouldIgnoreAction(self, action: QAction) -> bool:
......
......@@ -8,6 +8,7 @@ class FlagGraphicsItem(IntegerRegisterGraphicsItem):
"""
Graphics module for mia's flag module.
"""
def __init__(self, module: IntegerRegister):
super().__init__(module)
......
......@@ -34,7 +34,6 @@ class GrxGraphicsItem(ModuleGraphicsItem):
super().__init__(moudle)
def draw_graphics_item(self):
# The width of the register
# will be changed to fit text in registers but we
# need it here to get the position
......@@ -42,96 +41,101 @@ class GrxGraphicsItem(ModuleGraphicsItem):
# Draw each register
for index, register_value in enumerate(self.module.registers):
# Make text to display for register
name = "Gr" + str(index)
hex_length = math.ceil(self.state["bit_length"]/4)
hex_length = math.ceil(self.state["bit_length"] / 4)
value_text = f"0x{register_value:0{hex_length}x}"
full_text = name + ": " + value_text[2:]
# Make text label with text
text = QGraphicsSimpleTextItem(full_text, self)
text.setPos(self.TEXT_WIDTH_MARGIN,
self.TEXT_HEIGHT_MARGIN +
index*(self.REGISTER_MARGIN + self.RECT_HEIGHT))
text.setPos(
self.TEXT_WIDTH_MARGIN,
self.TEXT_HEIGHT_MARGIN
+ index * (self.REGISTER_MARGIN + self.RECT_HEIGHT),
)
self.register_text_labels.append(text)
rect_width = (len(full_text)*self.RECT_WIDTH_PER_CHAR
+ self.TEXT_WIDTH_MARGIN)
rect_width = (
len(full_text) * self.RECT_WIDTH_PER_CHAR + self.TEXT_WIDTH_MARGIN
)
# Make rect that fits text
QGraphicsRectItem(
# rect posisition
0,
index*(self.REGISTER_MARGIN + self.RECT_HEIGHT),
# rect size
rect_width,
self.RECT_HEIGHT, self)
# rect posisition
0,
index * (self.REGISTER_MARGIN + self.RECT_HEIGHT),
# rect size
rect_width,
self.RECT_HEIGHT,
self,
)
# Add line to mux part, is purely cosmetical
QGraphicsLineItem(
# set first point pos
rect_width,
index*(self.REGISTER_MARGIN + self.RECT_HEIGHT)+self.RECT_HEIGHT/2,
# set other point pos
rect_width+self.LINE_LENGTH,
index*(self.REGISTER_MARGIN + self.RECT_HEIGHT)+self.RECT_HEIGHT/2,
self)
# set first point pos
rect_width,
index * (self.REGISTER_MARGIN + self.RECT_HEIGHT)
+ self.RECT_HEIGHT / 2,
# set other point pos
rect_width + self.LINE_LENGTH,
index * (self.REGISTER_MARGIN + self.RECT_HEIGHT)
+ self.RECT_HEIGHT / 2,
self,
)
# Make mux polygon, is also purely cosmetical
mux_height = (len(self.register_text_labels)*self.RECT_HEIGHT +
(len(self.register_text_labels)-1)*self.REGISTER_MARGIN)
mux = QGraphicsPolygonItem(QPolygonF(
# top left corner
[QPointF(
0,
0),
# bottom left corner
QPointF(
0,
mux_height),
# bottom right corner
QPointF(
self.MUX_WIDTH,
mux_height-self.RECT_HEIGHT/2),
# top right corner
QPointF(
self.MUX_WIDTH,
self.RECT_HEIGHT/2)]), self)
mux_height = (
len(self.register_text_labels) * self.RECT_HEIGHT
+ (len(self.register_text_labels) - 1) * self.REGISTER_MARGIN
)
mux = QGraphicsPolygonItem(
QPolygonF(
# top left corner
[
QPointF(0, 0),
# bottom left corner
QPointF(0, mux_height),
# bottom right corner
QPointF(self.MUX_WIDTH, mux_height - self.RECT_HEIGHT / 2),
# top right corner
QPointF(self.MUX_WIDTH, self.RECT_HEIGHT / 2),
]
),
self,
)
# Move mux into position
mux.setPos(rect_width+self.LINE_LENGTH, 0)
mux.setPos(rect_width + self.LINE_LENGTH, 0)
# Have a invisible rect for ports bounding box
self.baserect = QGraphicsRectItem(0, 0, self.MUX_WIDTH, mux_height)
self.baserect.setPos(rect_width+self.LINE_LENGTH, 0)
self.baserect.setPos(rect_width + self.LINE_LENGTH, 0)
self.baserect.setVisible(False)
# Add mux label
name = "MUX"
mux_text = QGraphicsSimpleTextItem(name, self)
mux_text.setPos(rect_width+self.MUX_WIDTH/2+len(name)*self.RECT_WIDTH_PER_CHAR/2,
mux_height/2-self.CHAR_HEIGHT)
mux_text.setPos(
rect_width + self.MUX_WIDTH / 2 + len(name) * self.RECT_WIDTH_PER_CHAR / 2,
mux_height / 2 - self._CHAR_HEIGHT,
)
# Add ports to and from bus
from_bus_port = PortGraphicsItem(self.module.from_bus, Orientation.RIGHT, self)
from_bus_port.setPos(rect_width+self.LINE_LENGTH+self.MUX_WIDTH,
# Use the buses port margins so the ports align nicely
mux_height/2-BusGraphicsItem.PORT_MARGIN/2)
from_bus_port.setPos(
rect_width + self.LINE_LENGTH + self.MUX_WIDTH,
# Use the buses port margins so the ports align nicely
mux_height / 2 - BusGraphicsItem.PORT_MARGIN / 2,
)
to_bus_port = PortGraphicsItem(self.module.to_bus, Orientation.RIGHT, self)
to_bus_port.setPos(rect_width+self.LINE_LENGTH+self.MUX_WIDTH,
# Use the buses port margins so the ports align nicely
mux_height/2+BusGraphicsItem.PORT_MARGIN/2)
to_bus_port.setPos(
rect_width + self.LINE_LENGTH + self.MUX_WIDTH,
# Use the buses port margins so the ports align nicely
mux_height / 2 + BusGraphicsItem.PORT_MARGIN / 2,
)
self.ports.append(from_bus_port)
self.ports.append(to_bus_port)
......@@ -141,7 +145,7 @@ class GrxGraphicsItem(ModuleGraphicsItem):
for index, register_value in enumerate(self.module.registers):
text = self.register_text_labels[index]
name = "Gr" + str(index)
hex_length = math.ceil(self.state["bit_length"]/4)
hex_length = math.ceil(self.state["bit_length"] / 4)
value_text = f"0x{register_value:0{hex_length}x}"
full_text = name + ": " + value_text[2:]
......
......@@ -15,7 +15,7 @@ class IrGraphicsItem(ModuleGraphicsItem):
SMALL_RECT_WIDTH = 70
BIG_RECT_HEIGHT = 60
BIG_RECT_WIDTH = 180
BIG_RECT_WIDTH = 180
TEXT_WIDTH_MARGIN = 5
TEXT_HEIGHT_MARGIN = 8
......@@ -26,31 +26,27 @@ class IrGraphicsItem(ModuleGraphicsItem):
self.draw_ports()
def draw_graphics_item(self):
# Add small rect
QGraphicsRectItem(0, 0,
self.SMALL_RECT_WIDTH,
self.SMALL_RECT_HEIGHT, self)
QGraphicsRectItem(0, 0, self.SMALL_RECT_WIDTH, self.SMALL_RECT_HEIGHT, self)
# Add text for small rect
self.small_text = QGraphicsSimpleTextItem("", self)
self.small_text.setPos(self.TEXT_WIDTH_MARGIN,
self.TEXT_HEIGHT_MARGIN)
self.small_text.setPos(self.TEXT_WIDTH_MARGIN, self.TEXT_HEIGHT_MARGIN)
# Add big rect
self.baserect = QGraphicsRectItem(0, self.SMALL_RECT_HEIGHT,
self.BIG_RECT_WIDTH,
self.BIG_RECT_HEIGHT, self)
self.baserect = QGraphicsRectItem(
0, self.SMALL_RECT_HEIGHT, self.BIG_RECT_WIDTH, self.BIG_RECT_HEIGHT, self
)
# Add text verbose text for big rect
self.big_text = QGraphicsSimpleTextItem("", self)
self.big_text.setPos(self.TEXT_WIDTH_MARGIN,
self.SMALL_RECT_HEIGHT + self.BIG_TEXT_HEIGHT_MARGIN)
self.big_text.setPos(
self.TEXT_WIDTH_MARGIN, self.SMALL_RECT_HEIGHT + self.BIG_TEXT_HEIGHT_MARGIN
)
self.update()
def update(self):
# Update small text
instr = self.module.instruction
self.small_text.setText(f"IR: {instr:04x}")
......@@ -61,14 +57,16 @@ class IrGraphicsItem(ModuleGraphicsItem):
op_field = instr >> 12
grx_field = (instr >> 10) & 0b11
m_field = (instr >> 8) & 0b11
adr_field = instr & (2**8-1)
instr_text = ("op: " +
"grx: " +
"m: " +
"adr:\n" +
f"{op_field:04b} " +
f"{grx_field:02b} " +
f"{m_field:02b} " +
f"{adr_field:08b}")
adr_field = instr & (2**8 - 1)
instr_text = (
"op: "
+ "grx: "
+ "m: "
+ "adr:\n"
+ f"{op_field:04b} "
+ f"{grx_field:02b} "
+ f"{m_field:02b} "
+ f"{adr_field:08b}"
)
self.big_text.setText(instr_text)
......@@ -20,6 +20,7 @@ class HexValidator(QValidator):
A QValidator for constricting user input to a hex number that
lies within a specified (exclusive) range.
"""
def __init__(self, bottom: int, top: int) -> None:
super().__init__(None)
self.bottom = bottom
......@@ -51,15 +52,16 @@ class HexValidator(QValidator):
class MiaMemoryContentDialog(QDialog):
accepted = pyqtSignal(str, str, str, name="accepted")
def __init__(self,
memory: Module,
parent: Optional['QWidget'] = None,
flags: Qt.WindowFlags | Qt.WindowType = Qt.WindowFlags()
) -> None:
def __init__(
self,
memory: Module,
parent: Optional['QWidget'] = None,
flags: Qt.WindowFlags | Qt.WindowType = Qt.WindowFlags(),
) -> None:
super().__init__(parent, flags)
self.memory = memory
self.memory_name =memory.get_state()['name']
self.memory_name = memory.get_state()['name']
adresses = [hex(i) for i in range(len(memory.get_state()['memory']))]
adressValidator = HexValidator(0, len(adresses))
......@@ -93,7 +95,6 @@ class MiaMemoryContentDialog(QDialog):
value = memory_content[selectedAdress]
self.valuesWidget.setText(hex(value))
def signalAccepted(self) -> None:
adress = self.adressSelectWidget.currentText()
enteredValues = self.valuesWidget.text()
......
......@@ -40,13 +40,12 @@ class MiaMemoryWindow(QWidget):
def update(self):
memory_str = ""
for adress, value in enumerate(self.module.memory):
# Add adress and content to string
# Make sure its unifrom lenght so rows are consistent
memory_str += f"0x{adress:02x}" + ": " + f"0x{value:04x}" + " " + "\t"
# Make new line when we reach end of row
if adress % self.ROW_LENGTH == self.ROW_LENGTH-1:
if adress % self.ROW_LENGTH == self.ROW_LENGTH - 1:
memory_str += "\n"
self.text.setText(memory_str)
......@@ -57,45 +56,45 @@ class MiaMemoryGraphicsItem(MemoryGraphicsItem):
Graphics module for a Memory module.
"""
RECT_WIDTH = 150
RECT_HEIGHT= 200
def __init__(self, memory_module: Memory):
super().__init__(memory_module)
def __init__(self, memory_module: Memory, **kwargs):
super().__init__(memory_module, **kwargs)
self.memory_window = None
def draw_graphics_item(self) -> None:
# Same as normal memory but no control signal
# Create base backgrond rect
self.baserect = QGraphicsRectItem(0, 0, self.RECT_WIDTH, self.RECT_HEIGHT, self)
self.baserect = QGraphicsRectItem(0, 0, self._width, self._height, self)
self.baserect.setPen(CS.ModuleOutline)
self.baserect.setBrush(CS.ModuleBackground)
# Make ports
self.input = PortGraphicsItem(self.module.get_input_signal(),
Orientation.RIGHT, self)
self.input.setPos(self.RECT_WIDTH, self.RECT_HEIGHT/8)
self.input = PortGraphicsItem(
self.module.get_input_signal(), Orientation.RIGHT, self
)
self.input.setPos(self._width, self._height / 8)
self.output = PortGraphicsItem(self.module.get_output_signal(),
Orientation.RIGHT, self)
self.output.setPos(self.RECT_WIDTH, self.RECT_HEIGHT/4)
self.output = PortGraphicsItem(
self.module.get_output_signal(), Orientation.RIGHT, self
)
self.output.setPos(self._width, self._height / 4)
self.adress = PortGraphicsItem(self.module.get_adress_signal(),
Orientation.DOWN, self)
self.adress.setPos(self.RECT_WIDTH/4, self.RECT_HEIGHT)
self.adress = PortGraphicsItem(
self.module.get_adress_signal(), Orientation.DOWN, self
)
self.adress.setPos(self._width / 4, self._height)
self.ports = [self.input, self.output, self.adress]
# Create name lable
name_text = QGraphicsSimpleTextItem(self.state["name"], self)
name_text.setPos(self.RECT_WIDTH/2
- len(self.state["name"])*self.CHAR_LEN, 0)
name_text.setPos(self._width / 2 - len(self.state["name"]) * self._CHAR_LEN, 0)
# Create adress lable
self.adress_text = QGraphicsSimpleTextItem("adress: "
+ str(self.state["current_adress"]), self)
self.adress_text.setPos(self.RECT_WIDTH/20, self.RECT_HEIGHT/8)
self.adress_text = QGraphicsSimpleTextItem(
"adress: " + str(self.state["current_adress"]), self
)
self.adress_text.setPos(self._width / 20, self._height / 8)
def showMemoryContents(self) -> None:
"""
......@@ -113,24 +112,24 @@ class MiaMemoryGraphicsItem(MemoryGraphicsItem):
self.memory_br_dialog.accepted.connect(self.memoryBreakpointAccepted)
@Slot(str, str, str)
def memoryBreakpointAccepted(self, module_name: str,
adress: str,
value: str) -> None:
def memoryBreakpointAccepted(
self, module_name: str, adress: str, value: str
) -> None:
"""
Same as prent function but also prases data so it is hexadecimal.
"""
try:
parsed_adress = int(adress, 16)
parsed_value = ast.literal_eval(value)
self.new_memory_breakpoint_signal.emit(module_name,
str(parsed_adress),
str(parsed_value))
self.new_memory_breakpoint_signal.emit(
module_name, str(parsed_adress), str(parsed_value)
)
except SyntaxError as e:
self.errorMessageWidget.showMessage(str(e))
except ValueError:
self.errorMessageWidget.showMessage("You must enter a hexadecimal"
"number preceeded by '0x' (e.g."
"0xc3).")
self.errorMessageWidget.showMessage(
"You must enter a hexadecimal" "number preceeded by '0x' (e.g." "0xc3)."
)
@Slot(str, str, str)
def editMemoryAccepted(self, module_name: str, adress: str, value: str) -> None:
......@@ -143,9 +142,9 @@ class MiaMemoryGraphicsItem(MemoryGraphicsItem):
except SyntaxError as e:
self.errorMessageWidget.showMessage(str(e))
except ValueError:
self.errorMessageWidget.showMessage("You must enter a hexadecimal"
"number preceeded by '0x' (e.g."
"0xc3).")
self.errorMessageWidget.showMessage(
"You must enter a hexadecimal" "number preceeded by '0x' (e.g." "0xc3)."
)
else:
module_state = self.module.get_state()
module_state['memory'][parsed_adress] = parsed_value
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment