class View(QMainWindow): def __init__(self, model, controller): super().__init__() self._model = model self._controller = controller self.segmentcursor = False self.togglecolors = {"#1f77b4": "m", "m": "#1f77b4"} ################################################################# # define GUI layout and connect input widgets to external slots # ################################################################# self.setWindowTitle("biopeaks") self.setGeometry(50, 50, 1750, 750) self.setWindowIcon(QIcon(":/python_icon.png")) # figure0 for signal self.figure0 = Figure() self.canvas0 = FigureCanvas(self.figure0) # Enforce minimum height, otherwise resizing with self.splitter causes # mpl to throw an error because figure is resized to height 0. The # widget can still be fully collapsed with self.splitter- self.canvas0.setMinimumHeight(1) # in pixels self.ax00 = self.figure0.add_subplot(1, 1, 1) self.ax00.set_frame_on(False) self.figure0.subplots_adjust(left=0.04, right=0.98, bottom=0.25) self.line00 = None self.scat = None self.segmentspan = None # figure1 for marker self.figure1 = Figure() self.canvas1 = FigureCanvas(self.figure1) self.canvas1.setMinimumHeight(1) self.ax10 = self.figure1.add_subplot(1, 1, 1, sharex=self.ax00) self.ax10.get_xaxis().set_visible(False) self.ax10.set_frame_on(False) self.figure1.subplots_adjust(left=0.04, right=0.98) self.line10 = None # figure2 for statistics self.figure2 = Figure() self.canvas2 = FigureCanvas(self.figure2) self.canvas2.setMinimumHeight(1) self.ax20 = self.figure2.add_subplot(3, 1, 1, sharex=self.ax00) self.ax20.get_xaxis().set_visible(False) self.ax20.set_frame_on(False) self.line20 = None self.ax21 = self.figure2.add_subplot(3, 1, 2, sharex=self.ax00) self.ax21.get_xaxis().set_visible(False) self.ax21.set_frame_on(False) self.line21 = None self.ax22 = self.figure2.add_subplot(3, 1, 3, sharex=self.ax00) self.ax22.get_xaxis().set_visible(False) self.ax22.set_frame_on(False) self.line22 = None self.figure2.subplots_adjust(left=0.04, right=0.98) # navigation bar self.navitools = CustomNavigationToolbar(self.canvas0, self) # peak editing self.editcheckbox = QCheckBox("editable", self) self.editcheckbox.stateChanged.connect(self._model.set_peakseditable) # peak saving batch self.savecheckbox = QCheckBox("save during batch processing", self) self.savecheckbox.stateChanged.connect(self._model.set_savebatchpeaks) # peak auto-correction batch self.correctcheckbox = QCheckBox("correct during batch processing", self) self.correctcheckbox.stateChanged.connect( self._model.set_correctbatchpeaks) # selecting stats for saving self.periodcheckbox = QCheckBox("period", self) self.periodcheckbox.stateChanged.connect( lambda: self.select_stats("period")) self.ratecheckbox = QCheckBox("rate", self) self.ratecheckbox.stateChanged.connect( lambda: self.select_stats("rate")) self.tidalampcheckbox = QCheckBox("tidal amplitude", self) self.tidalampcheckbox.stateChanged.connect( lambda: self.select_stats("tidalamp")) # channel selection self.sigchanmenulabel = QLabel("biosignal") self.sigchanmenu = QComboBox(self) self.sigchanmenu.addItem("A1") self.sigchanmenu.addItem("A2") self.sigchanmenu.addItem("A3") self.sigchanmenu.addItem("A4") self.sigchanmenu.addItem("A5") self.sigchanmenu.addItem("A6") self.sigchanmenu.currentTextChanged.connect(self._model.set_signalchan) # initialize with default value self._model.set_signalchan(self.sigchanmenu.currentText()) self.markerchanmenulabel = QLabel("marker") self.markerchanmenu = QComboBox(self) self.markerchanmenu.addItem("none") self.markerchanmenu.addItem("I1") self.markerchanmenu.addItem("I2") self.markerchanmenu.addItem("A1") self.markerchanmenu.addItem("A2") self.markerchanmenu.addItem("A3") self.markerchanmenu.addItem("A4") self.markerchanmenu.addItem("A5") self.markerchanmenu.addItem("A6") self.markerchanmenu.currentTextChanged.connect( self._model.set_markerchan) # initialize with default value self._model.set_markerchan(self.markerchanmenu.currentText()) # processing mode (batch or single file) self.batchmenulabel = QLabel("mode") self.batchmenu = QComboBox(self) self.batchmenu.addItem("single file") self.batchmenu.addItem("multiple files") self.batchmenu.currentTextChanged.connect(self._model.set_batchmode) self.batchmenu.currentTextChanged.connect(self.toggle_options) # initialize with default value self._model.set_batchmode(self.batchmenu.currentText()) self.toggle_options(self.batchmenu.currentText()) # modality selection self.modmenulabel = QLabel("modality") self.modmenu = QComboBox(self) self.modmenu.addItem("ECG") self.modmenu.addItem("PPG") self.modmenu.addItem("RESP") self.modmenu.currentTextChanged.connect(self._model.set_modality) self.modmenu.currentTextChanged.connect(self.toggle_options) # initialize with default value self._model.set_modality(self.modmenu.currentText()) self.toggle_options(self.modmenu.currentText()) # segment selection; this widget can be openend / set visible from # the menu and closed from within itself (see mapping of segmentermap); # it provides utilities to select a segment from the signal self.segmentermap = QSignalMapper(self) self.segmenter = QDockWidget("select a segment", self) # disable closing such that widget can only be closed by confirming # selection or custom button self.segmenter.setFeatures(QDockWidget.NoDockWidgetFeatures) # Limit number of decimals to four. regex = QRegExp("[0-9]*\.?[0-9]{4}") validator = QRegExpValidator(regex) self.startlabel = QLabel("start") self.startedit = QLineEdit() self.startedit.setValidator(validator) self.endlabel = QLabel("end") self.endedit = QLineEdit() self.endedit.setValidator(validator) segmentfromcursor = QAction(QIcon(":/mouse_icon.png"), "select with mouse", self) segmentfromcursor.triggered.connect(self.enable_segmentedit) self.startedit.addAction(segmentfromcursor, QLineEdit.TrailingPosition) self.endedit.addAction(segmentfromcursor, QLineEdit.TrailingPosition) self.previewedit = QPushButton("preview segment") lambdafn = lambda: self._model.set_segment( [self.startedit.text(), self.endedit.text()]) self.previewedit.clicked.connect(lambdafn) self.confirmedit = QPushButton("confirm segment") self.confirmedit.clicked.connect(self._controller.segment_signal) self.confirmedit.clicked.connect(self.segmentermap.map) self.segmentermap.setMapping(self.confirmedit, 0) self.abortedit = QPushButton("abort segmentation") self.abortedit.clicked.connect(self.segmentermap.map) # reset the segment to None self.segmentermap.setMapping(self.abortedit, 2) self.segmenterlayout = QFormLayout() self.segmenterlayout.addRow(self.startlabel, self.startedit) self.segmenterlayout.addRow(self.endlabel, self.endedit) self.segmenterlayout.addRow(self.previewedit) self.segmenterlayout.addRow(self.confirmedit) self.segmenterlayout.addRow(self.abortedit) self.segmenterwidget = QWidget() self.segmenterwidget.setLayout(self.segmenterlayout) self.segmenter.setWidget(self.segmenterwidget) self.segmenter.setVisible(False) self.segmenter.setAllowedAreas(Qt.RightDockWidgetArea) self.addDockWidget(Qt.RightDockWidgetArea, self.segmenter) # Set up dialog to gather user input for custom files. regex = QRegExp("[1-9][0-9]") validator = QRegExpValidator(regex) self.signallabel = QLabel("biosignal column") self.signaledit = QLineEdit() self.signaledit.setValidator(validator) self.markerlabel = QLabel("marker column") self.markeredit = QLineEdit() self.markeredit.setValidator(validator) regex = QRegExp("[0-9]{2}") validator = QRegExpValidator(regex) self.headerrowslabel = QLabel("number of header rows") self.headerrowsedit = QLineEdit() self.headerrowsedit.setValidator(validator) regex = QRegExp("[0-9]{5}") validator = QRegExpValidator(regex) self.sfreqlabel = QLabel("sampling rate") self.sfreqedit = QLineEdit() self.sfreqedit.setValidator(validator) self.separatorlabel = QLabel("column separator") self.separatormenu = QComboBox(self) self.separatormenu.addItem("comma") self.separatormenu.addItem("tab") self.separatormenu.addItem("colon") self.separatormenu.addItem("space") self.continuecustomfile = QPushButton("continue loading file") self.continuecustomfile.clicked.connect(self.set_customheader) self.customfiledialog = QDialog() self.customfiledialog.setWindowTitle("custom file info") self.customfiledialog.setWindowIcon(QIcon(":/file_icon.png")) self.customfiledialog.setWindowFlags( Qt.WindowCloseButtonHint ) # remove help button by only setting close button self.customfilelayout = QFormLayout() self.customfilelayout.addRow(self.signallabel, self.signaledit) self.customfilelayout.addRow(self.markerlabel, self.markeredit) self.customfilelayout.addRow(self.separatorlabel, self.separatormenu) self.customfilelayout.addRow(self.headerrowslabel, self.headerrowsedit) self.customfilelayout.addRow(self.sfreqlabel, self.sfreqedit) self.customfilelayout.addRow(self.continuecustomfile) self.customfiledialog.setLayout(self.customfilelayout) # set up menubar menubar = self.menuBar() # signal menu signalmenu = menubar.addMenu("biosignal") openSignal = signalmenu.addMenu("load") openEDF = QAction("EDF", self) openEDF.triggered.connect(lambda: self._model.set_filetype("EDF")) openEDF.triggered.connect(self._controller.get_fpaths) openSignal.addAction(openEDF) openOpenSignals = QAction("OpenSignals", self) openOpenSignals.triggered.connect( lambda: self._model.set_filetype("OpenSignals")) openOpenSignals.triggered.connect(self._controller.get_fpaths) openSignal.addAction(openOpenSignals) openCustom = QAction("Custom", self) openCustom.triggered.connect( lambda: self._model.set_filetype("Custom")) openCustom.triggered.connect(lambda: self.customfiledialog.exec_()) openSignal.addAction(openCustom) segmentSignal = QAction("select segment", self) segmentSignal.triggered.connect(self.segmentermap.map) self.segmentermap.setMapping(segmentSignal, 1) signalmenu.addAction(segmentSignal) self.segmentermap.mapped.connect(self.toggle_segmenter) saveSignal = QAction("save", self) saveSignal.triggered.connect(self._controller.get_wpathsignal) signalmenu.addAction(saveSignal) # peak menu peakmenu = menubar.addMenu("peaks") findPeaks = QAction("find", self) findPeaks.triggered.connect(self._controller.find_peaks) peakmenu.addAction(findPeaks) autocorrectPeaks = QAction("autocorrect", self) autocorrectPeaks.triggered.connect(self._controller.autocorrect_peaks) peakmenu.addAction(autocorrectPeaks) savePeaks = QAction("save", self) savePeaks.triggered.connect(self._controller.get_wpathpeaks) peakmenu.addAction(savePeaks) loadPeaks = QAction("load", self) loadPeaks.triggered.connect(self._controller.get_rpathpeaks) peakmenu.addAction(loadPeaks) # stats menu statsmenu = menubar.addMenu("statistics") calculateStats = QAction("calculate", self) calculateStats.triggered.connect(self._controller.calculate_stats) statsmenu.addAction(calculateStats) saveStats = QAction("save", self) saveStats.triggered.connect(self._controller.get_wpathstats) statsmenu.addAction(saveStats) # set up status bar to display error messages and current file path self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) self.progressBar = QProgressBar(self) self.progressBar.setRange(0, 1) self.statusBar.addPermanentWidget(self.progressBar) self.currentFile = QLabel() self.statusBar.addPermanentWidget(self.currentFile) # set up the central widget containing the plot and navigationtoolbar self.centwidget = QWidget() self.setCentralWidget(self.centwidget) # connect canvas0 to keyboard and mouse input for peak editing; # only widgets (e.g. canvas) that currently have focus capture # keyboard input: "You must enable keyboard focus for a widget if # it processes keyboard events." self.canvas0.setFocusPolicy(Qt.ClickFocus) self.canvas0.setFocus() self.canvas0.mpl_connect("key_press_event", self._controller.edit_peaks) self.canvas0.mpl_connect("button_press_event", self.get_xcursor) # arrange the three figure canvases in splitter object self.splitter = QSplitter(Qt.Vertical) # setting opaque resizing to false is important, since resizing gets # very slow otherwise once axes are populated self.splitter.setOpaqueResize(False) self.splitter.addWidget(self.canvas0) self.splitter.addWidget(self.canvas1) self.splitter.addWidget(self.canvas2) self.splitter.setChildrenCollapsible(False) # define GUI layout self.vlayout0 = QVBoxLayout(self.centwidget) self.vlayout1 = QVBoxLayout() self.vlayoutA = QFormLayout() self.vlayoutB = QFormLayout() self.vlayoutC = QVBoxLayout() self.vlayoutD = QVBoxLayout() self.hlayout0 = QHBoxLayout() self.optionsgroupA = QGroupBox("processing options") self.vlayoutA.addRow(self.modmenulabel, self.modmenu) self.vlayoutA.addRow(self.batchmenulabel, self.batchmenu) self.optionsgroupA.setLayout(self.vlayoutA) self.optionsgroupB = QGroupBox("channels") self.vlayoutB.addRow(self.sigchanmenulabel, self.sigchanmenu) self.vlayoutB.addRow(self.markerchanmenulabel, self.markerchanmenu) self.optionsgroupB.setLayout(self.vlayoutB) self.optionsgroupC = QGroupBox("peaks") self.vlayoutC.addWidget(self.editcheckbox) self.vlayoutC.addWidget(self.savecheckbox) self.vlayoutC.addWidget(self.correctcheckbox) self.optionsgroupC.setLayout(self.vlayoutC) self.optionsgroupD = QGroupBox("select statistics for saving") self.vlayoutD.addWidget(self.periodcheckbox) self.vlayoutD.addWidget(self.ratecheckbox) self.vlayoutD.addWidget(self.tidalampcheckbox) self.optionsgroupD.setLayout(self.vlayoutD) self.vlayout1.addWidget(self.optionsgroupA) self.vlayout1.addWidget(self.optionsgroupB) self.vlayout1.addWidget(self.optionsgroupC) self.vlayout1.addWidget(self.optionsgroupD) self.optionsgroupwidget = QWidget() self.optionsgroupwidget.setLayout(self.vlayout1) self.optionsgroup = QDockWidget("configurations", self) self.optionsgroup.setAllowedAreas(Qt.LeftDockWidgetArea) self.toggleoptionsgroup = self.optionsgroup.toggleViewAction() self.toggleoptionsgroup.setText("show/hide configurations") menubar.addAction(self.toggleoptionsgroup) self.optionsgroup.setWidget(self.optionsgroupwidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.optionsgroup) self.vlayout0.addWidget(self.splitter) self.hlayout0.addWidget(self.navitools) self.vlayout0.addLayout(self.hlayout0) ############################################## # connect output widgets to external signals # ############################################## self._model.signal_changed.connect(self.plot_signal) self._model.marker_changed.connect(self.plot_marker) self._model.peaks_changed.connect(self.plot_peaks) self._model.period_changed.connect(self.plot_period) self._model.rate_changed.connect(self.plot_rate) self._model.tidalamp_changed.connect(self.plot_tidalamp) self._model.path_changed.connect(self.display_path) self._model.segment_changed.connect(self.plot_segment) self._model.status_changed.connect(self.display_status) self._model.progress_changed.connect(self.display_progress) self._model.model_reset.connect(self.reset_plot) ########### # methods # ########### def plot_signal(self, value): self.ax00.clear() self.ax00.relim() # reset navitools history self.navitools.update() self.line00 = self.ax00.plot(self._model.sec, value, zorder=1) self.ax00.set_xlabel("seconds", fontsize="large", fontweight="heavy") self.canvas0.draw() # print("plot_signal listening") # print(self.ax0.collections, self.ax0.patches, self.ax0.artists) def plot_peaks(self, value): # self.scat is listed in ax.collections if self.ax00.collections: self.ax00.collections[0].remove() self.scat = self.ax00.scatter(self._model.sec[value], self._model.signal[value], c="m", zorder=2) self.canvas0.draw() # print("plot_peaks listening") # print(self.ax0.collections, self.ax0.patches, self.ax0.artists) def plot_segment(self, value): # If an invalid signal has been selected reset the segmenter interface. if value is None: self.toggle_segmenter(1) return if self.ax00.patches: # self.segementspan is listed in ax.patches self.ax00.patches[0].remove() self.segmentspan = self.ax00.axvspan(value[0], value[1], color="m", alpha=0.25) self.canvas0.draw() self.confirmedit.setEnabled(True) # print(self.ax0.collections, self.ax0.patches, self.ax0.artists) def plot_marker(self, value): self.ax10.clear() self.ax10.relim() self.line10 = self.ax10.plot(value[0], value[1]) self.canvas1.draw() # print("plot_marker listening") def plot_period(self, value): self.ax20.clear() self.ax20.relim() self.navitools.home() if self._model.savestats["period"]: self.line20 = self.ax20.plot(self._model.sec, value, c="m") else: self.line20 = self.ax20.plot(self._model.sec, value) self.ax20.set_ylim(bottom=min(value), top=max(value)) self.ax20.set_title("period", pad=0, fontweight="heavy") self.ax20.grid(True, axis="y") self.navitools.update() self.canvas2.draw() # print("plot_period listening") def plot_rate(self, value): self.ax21.clear() self.ax21.relim() self.navitools.home() if self._model.savestats["rate"]: self.line21 = self.ax21.plot(self._model.sec, value, c="m") else: self.line21 = self.ax21.plot(self._model.sec, value) self.ax21.set_ylim(bottom=min(value), top=max(value)) self.ax21.set_title("rate", pad=0, fontweight="heavy") self.ax21.grid(True, axis="y") self.navitools.update() self.canvas2.draw() # print("plot_rate listening") def plot_tidalamp(self, value): self.ax22.clear() self.ax22.relim() self.navitools.home() if self._model.savestats["tidalamp"]: self.line22 = self.ax22.plot(self._model.sec, value, c="m") else: self.line22 = self.ax22.plot(self._model.sec, value) self.ax22.set_ylim(bottom=min(value), top=max(value)) self.ax22.set_title("amplitude", pad=0, fontweight="heavy") self.ax22.grid(True, axis="y") self.navitools.update() self.canvas2.draw() # print("plot_tidalamp listening") def display_path(self, value): self.currentFile.setText(value) def display_status(self, status): # display status until new status is set self.statusBar.showMessage(status) def display_progress(self, value): # if value is 0, the progressbar indicates a busy state self.progressBar.setRange(0, value) def toggle_segmenter(self, value): if not self._model.loaded: return # Open segmenter when called from signalmenu or clear segmenter # upon selection of invalid segment. if value == 1: self.segmenter.setVisible(True) self.confirmedit.setEnabled(False) self.startedit.clear() self.endedit.clear() if self.ax00.patches: self.ax00.patches[0].remove() self.canvas0.draw() # Close segmenter after segment has been confirmed. elif value == 0: self.segmenter.setVisible(False) if self.ax00.patches: self.ax00.patches[0].remove() self.canvas0.draw() # Close segmenter after segmentation has been aborted (reset # segment). elif value == 2: self._model.set_segment([0, 0]) # This will reset the model to None self.segmenter.setVisible(False) if self.ax00.patches: self.ax00.patches[0].remove() self.canvas0.draw() def enable_segmentedit(self): # disable peak editing to avoid interference self.editcheckbox.setChecked(False) if self.startedit.hasFocus(): self.segmentcursor = "start" elif self.endedit.hasFocus(): self.segmentcursor = "end" def set_customheader(self): """Populate the customheader with inputs from the customfiledialog""" # Check if one of the mandatory fields is missing. mandatoryfields = self.signaledit.text() and self.headerrowsedit.text( ) and self.sfreqedit.text() if not mandatoryfields: self._model.status = ( "Please provide values for 'biosignal column'" ", 'number of header rows' and 'sampling" " rate'.") return seps = {"comma": ",", "tab": "\t", "colon": ":", "space": " "} self._model.customheader = dict.fromkeys( self._model.customheader, None ) # reset header here since it cannot be reset in controller.get_fpaths() self._model.customheader["signalidx"] = int(self.signaledit.text()) self._model.customheader["skiprows"] = int(self.headerrowsedit.text()) self._model.customheader["sfreq"] = int(self.sfreqedit.text()) self._model.customheader["separator"] = seps[ self.separatormenu.currentText()] if self.markeredit.text(): # not mandatory self._model.customheader["markeridx"] = int(self.markeredit.text()) self.customfiledialog.done(QDialog.Accepted) # close the dialog window self._controller.get_fpaths() # move on to file selection def get_xcursor(self, event): # event.button 1 corresponds to left mouse button if event.button != 1: return # limit number of decimal places to two if self.segmentcursor == "start": self.startedit.selectAll() self.startedit.insert("{:.2f}".format(event.xdata)) elif self.segmentcursor == "end": self.endedit.selectAll() self.endedit.insert("{:.2f}".format(event.xdata)) # disable segment cursor again after value has been set self.segmentcursor = False def select_stats(self, event): """ select or deselect statistics to be saved; toggle boolean with xor operator ^=, toggle color with dictionary """ self._model.savestats[event] ^= True line = None if event == "period": if self.line20: line = self.line20[0] elif event == "rate": if self.line21: line = self.line21[0] elif event == "tidalamp": if self.line22: line = self.line22[0] if line: line.set_color(self.togglecolors[line.get_color()]) self.canvas2.draw() def toggle_options(self, event): if event in ["ECG", "PPG"]: self.tidalampcheckbox.setEnabled(False) self.tidalampcheckbox.setChecked(False) self.ax22.set_visible(False) self.canvas2.draw() elif event == "RESP": self.tidalampcheckbox.setEnabled(True) self.ax22.set_visible(True) self.canvas2.draw() elif event == "multiple files": self.editcheckbox.setEnabled(False) self.editcheckbox.setChecked(False) self.savecheckbox.setEnabled(True) self.correctcheckbox.setEnabled(True) self.markerchanmenu.setEnabled(False) elif event == "single file": self.editcheckbox.setEnabled(True) self.markerchanmenu.setEnabled(True) self.savecheckbox.setEnabled(False) self.savecheckbox.setChecked(False) self.correctcheckbox.setEnabled(False) self.correctcheckbox.setChecked(False) def reset_plot(self): self.ax00.clear() self.ax00.relim() self.line00 = None self.scat = None self.segmentspan = None self.ax10.clear() self.ax10.relim() self.line10 = None self.ax20.clear() self.ax20.relim() self.line20 = None self.ax21.clear() self.ax21.relim() self.line21 = None self.ax22.clear() self.ax22.relim() self.line22 = None self.canvas0.draw() self.canvas1.draw() self.canvas2.draw() self.navitools.update() self.currentFile.clear()
class MainWindow(QMainWindow): def __init__(self, app: QApplication): super().__init__() self.current_file = None self.console_dock: QDockWidget = None self.tools_dock: QDockWidget = None self.toolbar: QToolBar = None self.graph_widget: GraphWidget = None self.log_console_widget: LogConsoleWidget = None self.tools_widget: ToolsWidget = None self.file_menu: QMenu = None self.help_menu: QMenu = None self.view_menu: QMenu = None self.docks_menu: QMenu = None self.about_action: QAction = None self.new_action: QAction = None self.open_action: QAction = None self.save_action: QAction = None self.save_as_action: QAction = None self.exit_action: QAction = None self.toggle_tools_dock: QAction = None self.toggle_console_dock: QAction = None self.create_actions(app) self.create_widgets() self.create_docks() self.create_menus() self.create_toolbar() self.create_statusbar() self.setCentralWidget(self.graph_widget) self.addDockWidget(Qt.BottomDockWidgetArea, self.console_dock) self.addDockWidget(Qt.RightDockWidgetArea, self.tools_dock) self.addToolBar(self.toolbar) self.setWindowTitle(self.tr("Proofy")) self.read_settings() def create_statusbar(self): self.statusBar().showMessage(self.tr("Welcome to Proofy!")) def create_docks(self): self.console_dock = QDockWidget(self.tr("Console")) self.console_dock.setWidget(self.log_console_widget) self.tools_dock = QDockWidget(self.tr("Tools")) self.tools_dock.setWidget(self.tools_widget) def create_toolbar(self): self.toolbar = QToolBar(self.tr("Tools"), self) self.toolbar.setStatusTip(self.tr("Tools")) self.toolbar.addActions([ self.new_action, self.open_action, self.save_action, self.save_as_action, self.exit_action, ]) self.toolbar.addSeparator() self.toolbar.addAction(self.about_action) def create_widgets(self): self.log_console_widget = LogConsoleWidget() self.log_console_widget.add_loggers(logger) self.graph_widget = GraphWidget(self.log_console_widget) self.tools_widget = ToolsWidget(graph_widget=self.graph_widget) def create_menus(self): self.file_menu = self.menuBar().addMenu("File") self.file_menu.setStatusTip(self.tr("File operations")) self.file_menu.addActions([ self.new_action, self.open_action, self.save_action, self.save_as_action, self.exit_action, ]) self.view_menu = self.menuBar().addMenu("View") self.view_menu.setStatusTip(self.tr("View settings")) self.docks_menu = self.view_menu.addMenu("Docks") self.docks_menu.addAction(self.toggle_tools_dock) self.docks_menu.addAction(self.toggle_console_dock) self.help_menu = self.menuBar().addMenu("Help") self.help_menu.setStatusTip(self.tr("Help")) self.help_menu.addAction(self.about_action) def create_actions(self, app): self.about_action = QAction( app.style().standardIcon( QtWidgets.QStyle.SP_MessageBoxInformation), "About", self, ) self.about_action.setStatusTip("Show information about Proofy") self.about_action.triggered.connect(self.about) self.new_action = QAction( app.style().standardIcon(QtWidgets.QStyle.SP_FileIcon), "New...", self) self.new_action.setStatusTip(self.tr("Create a new file")) self.new_action.setShortcuts(QKeySequence.New) self.new_action.triggered.connect(self.new) self.open_action = QAction( app.style().standardIcon(QtWidgets.QStyle.SP_DialogOpenButton), "Open...", self, ) self.open_action.setStatusTip(self.tr("Open file")) self.open_action.setShortcuts(QKeySequence.Open) self.open_action.triggered.connect(self.open) self.save_action = QAction( app.style().standardIcon(QtWidgets.QStyle.SP_DialogSaveButton), "Save...", self, ) self.save_action.setStatusTip(self.tr("Save file")) self.save_action.setShortcuts(QKeySequence.Save) self.save_action.triggered.connect(self.save) self.save_as_action = QAction( app.style().standardIcon(QtWidgets.QStyle.SP_DriveFDIcon), "Save As...", self, ) self.save_as_action.setStatusTip(self.tr("Save to file")) self.save_as_action.setShortcuts(QKeySequence.SaveAs) self.save_as_action.triggered.connect(self.save_as) self.exit_action = QAction( app.style().standardIcon(QtWidgets.QStyle.SP_DialogCloseButton), "Exit", self, ) self.exit_action.setStatusTip(self.tr("Exit Proofy")) self.exit_action.setShortcuts(QKeySequence.Quit) self.exit_action.triggered.connect(self.exit) self.toggle_console_dock = QAction("Toggle Console Dock", self) self.toggle_console_dock.setStatusTip( "Toggle visibility of the console dock") self.toggle_console_dock.triggered.connect( lambda _: self.console_dock.setVisible(not self.console_dock. isVisible())) self.toggle_tools_dock = QAction("Toggle Tools Dock", self) self.toggle_tools_dock.setStatusTip( "Toggle visibility of the tools dock") self.toggle_tools_dock.triggered.connect( lambda _: self.tools_dock.setVisible(not self.tools_dock.isVisible( ))) @Slot() def about(self): logger.debug(locals()) QMessageBox.about( self, "About Proofy", self.tr(f""" <h1>Proofy {__version__}</h1> <p> <b>Proofy is a formal proof system GUI.</b> </p> <p> Oh, it looks like Proofy wants to talk! <blockquote>Proofy likes Sequent Calculus! And circles! And edges! And arrows! And ...</blockquote> </p> """), ) def closeEvent(self, event: QCloseEvent): logger.debug(locals()) if self.unsaved_check(): self.write_settings() event.accept() else: event.ignore() @Slot() def exit(self): logger.debug(locals()) if self.unsaved_check(): QApplication.quit() @Slot() def new(self): logger.debug(locals()) if self.unsaved_check(): self.current_file = None def set_file_status(self, *, modified: bool): if self.current_file: file = pathlib.Path(self.current_file[0]) self.setWindowTitle(f"{file.name}[*] [{file}] - Proofy") self.setWindowModified(modified) else: self.setWindowTitle(f"Proofy[*]") self.setWindowModified(modified) @Slot() def open(self): logger.debug(locals()) if self.unsaved_check(): if (path := QFileDialog.getOpenFileName( self, caption=self.tr("Open File"), filter=self.graph_widget.get_open_file_extensions(), )): try: QApplication.setOverrideCursor(Qt.WaitCursor) self.graph_widget.open_file(*path) self.statusBar().showMessage(f"Opened {path} successfully") self.current_file = path self.set_file_status(modified=False) except Exception as e: logger.error(e) finally: QApplication.restoreOverrideCursor()
class View(QMainWindow): """View component of the MVC application. Presents the state of the application as well as the available means of interaction. Receives updates about the state from the Model and informs Controller about user interactions. """ def __init__(self, model, controller): """Define GUI elements and their layout. Parameters ---------- model : QObject Model component of the MVC application. controller : QObject Controller component of the MVC application. """ super().__init__() self._model = model self._controller = controller self.segmentcursor = False self.togglecolors = {"#1f77b4": "m", "m": "#1f77b4"} self.setWindowTitle("biopeaks") self.setGeometry(50, 50, 1750, 750) self.setWindowIcon(QIcon(":/python_icon.png")) # Figure for biosignal. self.figure0 = Figure() self.canvas0 = FigureCanvas(self.figure0) # Enforce minimum height, otherwise resizing with self.splitter causes # mpl to throw an error because figure is resized to height 0. The # widget can still be fully collapsed with self.splitter. self.canvas0.setMinimumHeight(1) # in pixels self.ax00 = self.figure0.add_subplot(1, 1, 1) self.ax00.set_frame_on(False) self.figure0.subplots_adjust(left=0.04, right=0.98, bottom=0.25) self.line00 = None self.scat = None self.segmentspan = None # Figure for marker. self.figure1 = Figure() self.canvas1 = FigureCanvas(self.figure1) self.canvas1.setMinimumHeight(1) self.ax10 = self.figure1.add_subplot(1, 1, 1, sharex=self.ax00) self.ax10.get_xaxis().set_visible(False) self.ax10.set_frame_on(False) self.figure1.subplots_adjust(left=0.04, right=0.98) self.line10 = None # Figure for statistics. self.figure2 = Figure() self.canvas2 = FigureCanvas(self.figure2) self.canvas2.setMinimumHeight(1) self.ax20 = self.figure2.add_subplot(3, 1, 1, sharex=self.ax00) self.ax20.get_xaxis().set_visible(False) self.ax20.set_frame_on(False) self.line20 = None self.ax21 = self.figure2.add_subplot(3, 1, 2, sharex=self.ax00) self.ax21.get_xaxis().set_visible(False) self.ax21.set_frame_on(False) self.line21 = None self.ax22 = self.figure2.add_subplot(3, 1, 3, sharex=self.ax00) self.ax22.get_xaxis().set_visible(False) self.ax22.set_frame_on(False) self.line22 = None self.figure2.subplots_adjust(left=0.04, right=0.98) self.navitools = CustomNavigationToolbar(self.canvas0, self) # Peak editing. self.editcheckbox = QCheckBox("editable", self) self.editcheckbox.stateChanged.connect(self._model.set_peakseditable) # Peak saving during batch processing. self.savecheckbox = QCheckBox("save during batch processing", self) self.savecheckbox.stateChanged.connect(self._model.set_savebatchpeaks) # Peak auto-correction during batch processing. self.correctcheckbox = QCheckBox("correct during batch processing", self) self.correctcheckbox.stateChanged.connect( self._model.set_correctbatchpeaks) # Selection of stats for saving. self.periodcheckbox = QCheckBox("period", self) self.periodcheckbox.stateChanged.connect( lambda: self.select_stats("period")) self.ratecheckbox = QCheckBox("rate", self) self.ratecheckbox.stateChanged.connect( lambda: self.select_stats("rate")) self.tidalampcheckbox = QCheckBox("tidal amplitude", self) self.tidalampcheckbox.stateChanged.connect( lambda: self.select_stats("tidalamp")) # Channel selection. self.sigchanmenulabel = QLabel("biosignal") self.sigchanmenu = QComboBox(self) self.sigchanmenu.addItem("A1") self.sigchanmenu.addItem("A2") self.sigchanmenu.addItem("A3") self.sigchanmenu.addItem("A4") self.sigchanmenu.addItem("A5") self.sigchanmenu.addItem("A6") self.sigchanmenu.currentTextChanged.connect(self._model.set_signalchan) self._model.set_signalchan( self.sigchanmenu.currentText()) # initialize with default value self.markerchanmenulabel = QLabel("marker") self.markerchanmenu = QComboBox(self) self.markerchanmenu.addItem("none") self.markerchanmenu.addItem("I1") self.markerchanmenu.addItem("I2") self.markerchanmenu.addItem("A1") self.markerchanmenu.addItem("A2") self.markerchanmenu.addItem("A3") self.markerchanmenu.addItem("A4") self.markerchanmenu.addItem("A5") self.markerchanmenu.addItem("A6") self.markerchanmenu.currentTextChanged.connect( self._model.set_markerchan) self._model.set_markerchan(self.markerchanmenu.currentText()) # Processing mode. self.batchmenulabel = QLabel("mode") self.batchmenu = QComboBox(self) self.batchmenu.addItem("single file") self.batchmenu.addItem("multiple files") self.batchmenu.currentTextChanged.connect(self._model.set_batchmode) self.batchmenu.currentTextChanged.connect(self.toggle_options) self._model.set_batchmode(self.batchmenu.currentText()) self.toggle_options(self.batchmenu.currentText()) # Modality selection. self.modmenulabel = QLabel("modality") self.modmenu = QComboBox(self) self.modmenu.addItem("ECG") self.modmenu.addItem("PPG") self.modmenu.addItem("RESP") self.modmenu.currentTextChanged.connect(self._model.set_modality) self.modmenu.currentTextChanged.connect(self.toggle_options) self._model.set_modality(self.modmenu.currentText()) self.toggle_options(self.modmenu.currentText()) # Segment selection. This widget can be openend / set visible from # the menu and closed from within itself (see mapping of segmentermap). self.segmentermap = QSignalMapper(self) self.segmenter = QDockWidget("select a segment", self) self.segmenter.setFeatures( QDockWidget.NoDockWidgetFeatures ) # disable closing such that widget can only be closed by confirming selection or custom button regex = QRegExp( "[0-9]*\.?[0-9]{4}") # Limit number of decimals to four validator = QRegExpValidator(regex) self.startlabel = QLabel("start") self.startedit = QLineEdit() self.startedit.setValidator(validator) self.endlabel = QLabel("end") self.endedit = QLineEdit() self.endedit.setValidator(validator) segmentfromcursor = QAction(QIcon(":/mouse_icon.png"), "select with mouse", self) segmentfromcursor.triggered.connect(self.enable_segmentedit) self.startedit.addAction(segmentfromcursor, QLineEdit.TrailingPosition) self.endedit.addAction(segmentfromcursor, QLineEdit.TrailingPosition) self.previewedit = QPushButton("preview segment") lambdafn = lambda: self._model.set_segment( [self.startedit.text(), self.endedit.text()]) self.previewedit.clicked.connect(lambdafn) self.confirmedit = QPushButton("confirm segment") self.confirmedit.clicked.connect(self._controller.segment_dataset) self.confirmedit.clicked.connect(self.segmentermap.map) self.segmentermap.setMapping(self.confirmedit, 0) self.abortedit = QPushButton("abort segmentation") self.abortedit.clicked.connect(self.segmentermap.map) self.segmentermap.setMapping(self.abortedit, 2) # resets the segment to None self.segmenterlayout = QFormLayout() self.segmenterlayout.addRow(self.startlabel, self.startedit) self.segmenterlayout.addRow(self.endlabel, self.endedit) self.segmenterlayout.addRow(self.previewedit) self.segmenterlayout.addRow(self.confirmedit) self.segmenterlayout.addRow(self.abortedit) self.segmenterwidget = QWidget() self.segmenterwidget.setLayout(self.segmenterlayout) self.segmenter.setWidget(self.segmenterwidget) self.segmenter.setVisible(False) self.segmenter.setAllowedAreas(Qt.RightDockWidgetArea) self.addDockWidget(Qt.RightDockWidgetArea, self.segmenter) # Custom file dialog. regex = QRegExp("[1-9][0-9]") validator = QRegExpValidator(regex) self.signallabel = QLabel("biosignal column") self.signaledit = QLineEdit() self.signaledit.setValidator(validator) self.markerlabel = QLabel("marker column") self.markeredit = QLineEdit() self.markeredit.setValidator(validator) regex = QRegExp("[0-9]{2}") validator = QRegExpValidator(regex) self.headerrowslabel = QLabel("number of header rows") self.headerrowsedit = QLineEdit() self.headerrowsedit.setValidator(validator) regex = QRegExp("[0-9]{5}") validator = QRegExpValidator(regex) self.sfreqlabel = QLabel("sampling rate") self.sfreqedit = QLineEdit() self.sfreqedit.setValidator(validator) self.separatorlabel = QLabel("column separator") self.separatormenu = QComboBox(self) self.separatormenu.addItem("comma") self.separatormenu.addItem("tab") self.separatormenu.addItem("colon") self.separatormenu.addItem("space") self.continuecustomfile = QPushButton("continue loading file") self.continuecustomfile.clicked.connect(self.set_customheader) self.customfiledialog = QDialog() self.customfiledialog.setWindowTitle("custom file info") self.customfiledialog.setWindowIcon(QIcon(":/file_icon.png")) self.customfiledialog.setWindowFlags( Qt.WindowCloseButtonHint ) # remove help button by only setting close button self.customfilelayout = QFormLayout() self.customfilelayout.addRow(self.signallabel, self.signaledit) self.customfilelayout.addRow(self.markerlabel, self.markeredit) self.customfilelayout.addRow(self.separatorlabel, self.separatormenu) self.customfilelayout.addRow(self.headerrowslabel, self.headerrowsedit) self.customfilelayout.addRow(self.sfreqlabel, self.sfreqedit) self.customfilelayout.addRow(self.continuecustomfile) self.customfiledialog.setLayout(self.customfilelayout) # Layout. menubar = self.menuBar() signalmenu = menubar.addMenu("biosignal") openSignal = signalmenu.addMenu("load") openEDF = QAction("EDF", self) openEDF.triggered.connect(lambda: self._model.set_filetype("EDF")) openEDF.triggered.connect(self._controller.load_channels) openSignal.addAction(openEDF) openOpenSignals = QAction("OpenSignals", self) openOpenSignals.triggered.connect( lambda: self._model.set_filetype("OpenSignals")) openOpenSignals.triggered.connect(self._controller.load_channels) openSignal.addAction(openOpenSignals) openCustom = QAction("Custom", self) openCustom.triggered.connect( lambda: self._model.set_filetype("Custom")) openCustom.triggered.connect(lambda: self.customfiledialog.exec_()) openSignal.addAction(openCustom) segmentSignal = QAction("select segment", self) segmentSignal.triggered.connect(self.segmentermap.map) self.segmentermap.setMapping(segmentSignal, 1) signalmenu.addAction(segmentSignal) self.segmentermap.mapped.connect(self.toggle_segmenter) saveSignal = QAction("save", self) saveSignal.triggered.connect(self._controller.save_channels) signalmenu.addAction(saveSignal) peakmenu = menubar.addMenu("peaks") findPeaks = QAction("find", self) findPeaks.triggered.connect(self._controller.find_peaks) peakmenu.addAction(findPeaks) autocorrectPeaks = QAction("autocorrect", self) autocorrectPeaks.triggered.connect(self._controller.autocorrect_peaks) peakmenu.addAction(autocorrectPeaks) savePeaks = QAction("save", self) savePeaks.triggered.connect(self._controller.save_peaks) peakmenu.addAction(savePeaks) loadPeaks = QAction("load", self) loadPeaks.triggered.connect(self._controller.load_peaks) peakmenu.addAction(loadPeaks) statsmenu = menubar.addMenu("statistics") calculateStats = QAction("calculate", self) calculateStats.triggered.connect(self._controller.calculate_stats) statsmenu.addAction(calculateStats) saveStats = QAction("save", self) saveStats.triggered.connect(self._controller.save_stats) statsmenu.addAction(saveStats) self.statusBar = QStatusBar() self.setStatusBar(self.statusBar) self.progressBar = QProgressBar(self) self.progressBar.setRange(0, 1) self.statusBar.addPermanentWidget(self.progressBar) self.currentFile = QLabel() self.statusBar.addPermanentWidget(self.currentFile) self.centwidget = QWidget() # contains figures and navigationtoolbar self.setCentralWidget(self.centwidget) self.canvas0.setFocusPolicy( Qt.ClickFocus ) # only widgets (e.g. canvas) that currently have focus capture keyboard input self.canvas0.setFocus() self.canvas0.mpl_connect( "key_press_event", self._controller.edit_peaks ) # connect canvas to keyboard input for peak editing self.canvas0.mpl_connect( "button_press_event", self.get_xcursor) # connect canvas to mouse input for peak editing self.splitter = QSplitter( Qt.Vertical ) # arrange the three figure canvases in splitter object self.splitter.setOpaqueResize( False) # resizing gets very slow otherwise once axes are populated self.splitter.addWidget(self.canvas0) self.splitter.addWidget(self.canvas1) self.splitter.addWidget(self.canvas2) self.splitter.setChildrenCollapsible(False) self.vlayout0 = QVBoxLayout(self.centwidget) self.vlayout1 = QVBoxLayout() self.vlayoutA = QFormLayout() self.vlayoutB = QFormLayout() self.vlayoutC = QVBoxLayout() self.vlayoutD = QVBoxLayout() self.hlayout0 = QHBoxLayout() self.optionsgroupA = QGroupBox("processing options") self.vlayoutA.addRow(self.modmenulabel, self.modmenu) self.vlayoutA.addRow(self.batchmenulabel, self.batchmenu) self.optionsgroupA.setLayout(self.vlayoutA) self.optionsgroupB = QGroupBox("channels") self.vlayoutB.addRow(self.sigchanmenulabel, self.sigchanmenu) self.vlayoutB.addRow(self.markerchanmenulabel, self.markerchanmenu) self.optionsgroupB.setLayout(self.vlayoutB) self.optionsgroupC = QGroupBox("peaks") self.vlayoutC.addWidget(self.editcheckbox) self.vlayoutC.addWidget(self.savecheckbox) self.vlayoutC.addWidget(self.correctcheckbox) self.optionsgroupC.setLayout(self.vlayoutC) self.optionsgroupD = QGroupBox("select statistics for saving") self.vlayoutD.addWidget(self.periodcheckbox) self.vlayoutD.addWidget(self.ratecheckbox) self.vlayoutD.addWidget(self.tidalampcheckbox) self.optionsgroupD.setLayout(self.vlayoutD) self.vlayout1.addWidget(self.optionsgroupA) self.vlayout1.addWidget(self.optionsgroupB) self.vlayout1.addWidget(self.optionsgroupC) self.vlayout1.addWidget(self.optionsgroupD) self.optionsgroupwidget = QWidget() self.optionsgroupwidget.setLayout(self.vlayout1) self.optionsgroup = QDockWidget("configurations", self) self.optionsgroup.setAllowedAreas(Qt.LeftDockWidgetArea) self.toggleoptionsgroup = self.optionsgroup.toggleViewAction() self.toggleoptionsgroup.setText("show/hide configurations") menubar.addAction(self.toggleoptionsgroup) self.optionsgroup.setWidget(self.optionsgroupwidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.optionsgroup) self.vlayout0.addWidget(self.splitter) self.hlayout0.addWidget(self.navitools) self.vlayout0.addLayout(self.hlayout0) # Subscribe to updates from the Model. self._model.signal_changed.connect(self.plot_signal) self._model.marker_changed.connect(self.plot_marker) self._model.peaks_changed.connect(self.plot_peaks) self._model.period_changed.connect(self.plot_period) self._model.rate_changed.connect(self.plot_rate) self._model.tidalamp_changed.connect(self.plot_tidalamp) self._model.path_changed.connect(self.display_path) self._model.segment_changed.connect(self.plot_segment) self._model.status_changed.connect(self.display_status) self._model.progress_changed.connect(self.display_progress) self._model.model_reset.connect(self.reset_plot) def plot_signal(self, signal): """Plot the biosignal. Receives updates in signal from Model. Parameters ---------- signal : ndarray of float Vector representing the biosignal. See Also -------- model.Model.signal """ self.ax00.clear() self.ax00.relim() self.navitools.update() # reset navitools history self.line00 = self.ax00.plot(self._model.sec, signal, zorder=1) self.ax00.set_xlabel("seconds", fontsize="large", fontweight="heavy") self.canvas0.draw() def plot_peaks(self, peaks): """Plot the extrema. Receives updates in peaks from Model. Parameters ---------- peaks : ndarray of int Vector representing the extrema. See Also -------- model.Model.peaks """ if self.ax00.collections: # self.scat is listed in ax.collections self.ax00.collections[0].remove() self.scat = self.ax00.scatter(self._model.sec[peaks], self._model.signal[peaks], c="m", zorder=2) self.canvas0.draw() def plot_segment(self, segment): """Show preview of segment. Receives updates in segment from Model. Parameters ---------- segment : list of float The start and end of the segment in seconds. See Also -------- model.Model.segment """ if segment is None: # if an invalid segment has been selected reset the segmenter interface self.toggle_segmenter(1) return if self.ax00.patches: # self.segementspan is listed in ax.patches self.ax00.patches[0].remove() self.segmentspan = self.ax00.axvspan(segment[0], segment[1], color="m", alpha=0.25) self.canvas0.draw() self.confirmedit.setEnabled(True) def plot_marker(self, marker): """Plot the marker channel. Receives updates in marker from Model. Parameters ---------- marker : list of ndarray Seconds element is vector representing the marker channel and first element is a vector representing the seconds associated with each sample in the marker channel. See Also -------- model.Model.marker """ self.ax10.clear() self.ax10.relim() self.line10 = self.ax10.plot(marker[0], marker[1]) self.canvas1.draw() def plot_period(self, period): """Plot instantaneous period. Receives updates in period from Model. Parameters ---------- period : ndarray of float Vector representing the instantaneous period. See Also -------- model.Model.periodintp """ self.ax20.clear() self.ax20.relim() self.navitools.home() if self._model.savestats["period"]: self.line20 = self.ax20.plot(self._model.sec, period, c="m") else: self.line20 = self.ax20.plot(self._model.sec, period) self.ax20.set_ylim(bottom=min(period), top=max(period)) self.ax20.set_title("period", pad=0, fontweight="heavy") self.ax20.grid(True, axis="y") self.navitools.update() self.canvas2.draw() def plot_rate(self, rate): """Plot instantaneous rate. Receives updates in rate from Model. Parameters ---------- rate : ndarray of float Vector representing the instantaneous rate. See Also -------- model.Model.rateintp """ self.ax21.clear() self.ax21.relim() self.navitools.home() if self._model.savestats["rate"]: self.line21 = self.ax21.plot(self._model.sec, rate, c="m") else: self.line21 = self.ax21.plot(self._model.sec, rate) self.ax21.set_ylim(bottom=min(rate), top=max(rate)) self.ax21.set_title("rate", pad=0, fontweight="heavy") self.ax21.grid(True, axis="y") self.navitools.update() self.canvas2.draw() def plot_tidalamp(self, tidalamp): """Plot instantaneous tidal amplitude. Receives updates in tidal amplitude from Model. Parameters ---------- tidalamp : ndarray of float Vector representing the instantaneous tidal amplitude. See Also -------- model.Model.tidalampintp """ self.ax22.clear() self.ax22.relim() self.navitools.home() if self._model.savestats["tidalamp"]: self.line22 = self.ax22.plot(self._model.sec, tidalamp, c="m") else: self.line22 = self.ax22.plot(self._model.sec, tidalamp) self.ax22.set_ylim(bottom=min(tidalamp), top=max(tidalamp)) self.ax22.set_title("amplitude", pad=0, fontweight="heavy") self.ax22.grid(True, axis="y") self.navitools.update() self.canvas2.draw() def display_path(self, path): """Display the path to the current dataset. Receives update in path from Model. Parameters ---------- path : str The path to the file containing the current dataset. See Also -------- model.Model.rpathsignal """ self.currentFile.setText(path) def display_status(self, status): """Display a status message. Receives updates in status message from Model. Parameters ---------- status : str A status message. See Also -------- model.Model.status """ self.statusBar.showMessage(status) def display_progress(self, progress): """Display task progress. Receives updates in progress from Model. Parameters ---------- progress : int Integer indicating the current task progress. See Also -------- model.Model.progress, controller.Worker, controller.threaded """ self.progressBar.setRange( 0, progress) # indicates busy state if progress is 0 def toggle_segmenter(self, visibility_state): """Toggle visibility of segmenter widget. Parameters ---------- visibility_state : int Update in state of the segmenter widget's visibility. """ if not self._model.loaded: return if visibility_state == 1: # open segmenter when called from signalmenu or clear segmenter upon selection of invalid segment self.segmenter.setVisible(True) self.confirmedit.setEnabled(False) self.startedit.clear() self.endedit.clear() elif visibility_state == 0: # close segmenter after segment has been confirmed self.segmenter.setVisible(False) elif visibility_state == 2: # close segmenter after segmentation has been aborted (reset segment) self._model.set_segment([0, 0]) self.segmenter.setVisible(False) if self.ax00.patches: self.ax00.patches[0].remove() self.canvas0.draw() def enable_segmentedit(self): """Associate cursor position with a specific segmenter text field. Regulate if cursor position is associated with editing the start or end of a segment. """ self.editcheckbox.setChecked( False) # disable peak editing to avoid interference if self.startedit.hasFocus(): self.segmentcursor = "start" elif self.endedit.hasFocus(): self.segmentcursor = "end" def get_xcursor(self, mouse_event): """Retrieve input to segmenter text fields from cursor position. Retrieve the start or end of a segment in seconds from the current cursor position. Parameters ---------- mouse_event : MouseEvent Event containing information about the current cursor position in data coordinates. See Also -------- matplotlib.backend_bases.MouseEvent """ if mouse_event.button != 1: # 1 = left mouse button return if self.segmentcursor == "start": self.startedit.selectAll() self.startedit.insert("{:.2f}".format( mouse_event.xdata)) # limit number of decimal places to two elif self.segmentcursor == "end": self.endedit.selectAll() self.endedit.insert("{:.2f}".format(mouse_event.xdata)) self.segmentcursor = False # disable segment cursor again after value has been set def set_customheader(self): """Populate the customheader with inputs from the customfiledialog.""" mandatoryfields = self.signaledit.text() and self.headerrowsedit.text( ) and self.sfreqedit.text( ) # check if one of the mandatory fields is missing if not mandatoryfields: self._model.status = ( "Please provide values for 'biosignal column'" ", 'number of header rows' and 'sampling" " rate'.") return seps = {"comma": ",", "tab": "\t", "colon": ":", "space": " "} self._model.customheader = dict.fromkeys( self._model.customheader, None ) # reset header here since it cannot be reset in controller.load_chanels self._model.customheader["signalidx"] = int(self.signaledit.text()) self._model.customheader["skiprows"] = int(self.headerrowsedit.text()) self._model.customheader["sfreq"] = int(self.sfreqedit.text()) self._model.customheader["separator"] = seps[ self.separatormenu.currentText()] if self.markeredit.text(): # not mandatory self._model.customheader["markeridx"] = int(self.markeredit.text()) self.customfiledialog.done(QDialog.Accepted) # close the dialog window self._controller.load_channels() # move on to file selection def select_stats(self, statistic): """Select statistics to be saved. Parameters ---------- statistic : str The selected statistic. """ self._model.savestats[ statistic] ^= True # toggle boolean with xor operator line = None if statistic == "period": if self.line20: line = self.line20[0] elif statistic == "rate": if self.line21: line = self.line21[0] elif statistic == "tidalamp": if self.line22: line = self.line22[0] if line: line.set_color(self.togglecolors[line.get_color()]) self.canvas2.draw() def toggle_options(self, state): """Toggle availability of configuration options. Based on current state. Parameters ---------- state : str The aspect of the current state to which the availability of configuration options needs to be adapted. """ if state in ["ECG", "PPG"]: self.tidalampcheckbox.setEnabled(False) self.tidalampcheckbox.setChecked(False) self.ax22.set_visible(False) self.canvas2.draw() elif state == "RESP": self.tidalampcheckbox.setEnabled(True) self.ax22.set_visible(True) self.canvas2.draw() elif state == "multiple files": self.editcheckbox.setEnabled(False) self.editcheckbox.setChecked(False) self.savecheckbox.setEnabled(True) self.correctcheckbox.setEnabled(True) self.markerchanmenu.setEnabled(False) elif state == "single file": self.editcheckbox.setEnabled(True) self.markerchanmenu.setEnabled(True) self.savecheckbox.setEnabled(False) self.savecheckbox.setChecked(False) self.correctcheckbox.setEnabled(False) self.correctcheckbox.setChecked(False) def reset_plot(self): """Reset plot elements associated with the current dataset.""" self.ax00.clear() self.ax00.relim() self.line00 = None self.scat = None self.segmentspan = None self.ax10.clear() self.ax10.relim() self.line10 = None self.ax20.clear() self.ax20.relim() self.line20 = None self.ax21.clear() self.ax21.relim() self.line21 = None self.ax22.clear() self.ax22.relim() self.line22 = None self.canvas0.draw() self.canvas1.draw() self.canvas2.draw() self.navitools.update() self.currentFile.clear()
class PuppetMaster(QMainWindow): requestEditMode = Signal(bool) def __init__(self, parent=None, editMode=bool(False)): super(PuppetMaster, self).__init__(parent) self._parent = parent self._model = list() self.editMode = editMode self.setMouseTracking(True) self.setFocusPolicy(Qt.StrongFocus) self.setWindowTitle('PuppetMaster') self.setMinimumHeight(1) self.setMinimumWidth(1) self.setContextMenuPolicy(Qt.PreventContextMenu) # Main tabs self.tab = CanvasGraphicsViewTab(parent=self) self.tab.requestEditMode.connect(self.set_edit) self.setCentralWidget(self.tab) # Parameter Widget self.parameter = Parameters(parent=self) self.parameterDock = QDockWidget(": Parameters ::", self) self.parameterDock.setObjectName('Parameters') self.parameterDock.setFeatures(QDockWidget.DockWidgetClosable) self.parameterDock.setWidget(self.parameter) self.parameterDock.setTitleBarWidget(QWidget(self.parameterDock)) self.parameterDock.setVisible(self.editMode) self.addDockWidget(Qt.BottomDockWidgetArea, self.parameterDock) self.tab.onSelection.connect(self.update_parameters) self.parameter.onChangeBGColor.connect(self.tab.update_bg_color) self.parameter.onChangeFontColor.connect(self.tab.update_font_color) self.parameter.onChangeFontSize.connect(self.tab.update_font_size) self.parameter.onChangeText.connect(self.tab.update_text) self.parameter.onChangeShape.connect(self.tab.update_shape) # maya Signal on selection items self.idx = OpenMaya.MEventMessage.addEventCallback( "SelectionChanged", self.tab.maya_selection) # Menu self.setMenuBar(self.create_menu()) self.set_edit(self.editMode) def update_parameters(self, node=PickNode): shape = node.Shape if isinstance(node, PickNode) else str() self.parameter.update_param(text=node.toPlainText(), fontSize=node.font().pointSize(), fontColor=node.defaultTextColor(), bgColor=node.Background, shapeName=shape) def create_menu(self): window_menu = QMenuBar(self) file_menu = window_menu.addMenu("&File") new_action = QAction("&New...", self) new_action.setShortcut('Ctrl+N') new_action.setShortcutContext(Qt.WidgetShortcut) new_action.setStatusTip('Create a new Set') new_action.triggered.connect(self.tab.new_tab) file_menu.addAction(new_action) open_action = QAction("&Open...", self) open_action.setShortcut('Ctrl+O') open_action.setShortcutContext(Qt.WidgetShortcut) open_action.setStatusTip('Open a new set') open_action.triggered.connect(self.tab.open_set) file_menu.addAction(open_action) refresh_action = QAction("&Refresh...", self) refresh_action.setStatusTip('Refresh the current sets') refresh_action.triggered.connect(self.tab.refresh_set) file_menu.addAction(refresh_action) file_menu.addSeparator() save_action = QAction("&Save...", self) save_action.setShortcut('Ctrl+S') save_action.setShortcutContext(Qt.WidgetShortcut) save_action.setStatusTip('Save the current tab') save_action.triggered.connect(self.tab.save_set) file_menu.addAction(save_action) saveAs_action = QAction("&Save As...", self) saveAs_action.setShortcut('Ctrl+Shift+S') saveAs_action.setShortcutContext(Qt.WidgetShortcut) saveAs_action.setStatusTip('Save the current tab as a new Set') saveAs_action.triggered.connect(self.tab.saveAs_set) file_menu.addAction(saveAs_action) saveAsTemp_action = QAction("&Save As Template...", self) saveAsTemp_action.setStatusTip( 'Save the current tab as a new Template') saveAsTemp_action.triggered.connect(self.tab.saveAsTemplate_set) file_menu.addAction(saveAsTemp_action) file_menu.addSeparator() rename_action = QAction("&Rename Tab...", self) rename_action.setStatusTip('Rename the current Tab') rename_action.triggered.connect(self.tab.rename_set) file_menu.addAction(rename_action) close_action = QAction("&Close Tab...", self) close_action.setShortcut('Ctrl+Shift+W') close_action.setShortcutContext(Qt.WidgetShortcut) close_action.setStatusTip('Close the current Tab') close_action.triggered.connect(self.tab.closeCurrentTab) file_menu.addAction(close_action) picker_menu = window_menu.addMenu("&Picker") self.edit_action = QAction("&Edit Mode", self) self.edit_action.setStatusTip('Toggle between view and edit mode.') self.edit_action.triggered.connect(self.edit_toggle) self.edit_action.setCheckable(True) self.edit_action.setChecked(self.editMode) picker_menu.addAction(self.edit_action) picker_menu.addSeparator() self.background_action = QAction("&Change Background...", self) self.background_action.setEnabled(self.editMode) self.background_action.setStatusTip('Change the background.') self.background_action.triggered.connect(self.tab.set_background) picker_menu.addAction(self.background_action) self.namespace_action = QAction("&Change Namespace...", self) self.namespace_action.setEnabled(self.editMode) self.namespace_action.setStatusTip('Change the namespace.') self.namespace_action.triggered.connect(self.tab.set_namespace) picker_menu.addAction(self.namespace_action) help_menu = window_menu.addMenu("&Help") wiki_action = QAction("&About PuppetMaster...", self) wiki_action.setStatusTip('Open Wiki page') wiki_action.triggered.connect(self.wiki_open) help_menu.addAction(wiki_action) return window_menu def edit_toggle(self): self.set_edit(not self.editMode) def wiki_open(self): webbrowser.open_new_tab( 'https://github.com/Bernardrouhi/PuppetMaster/wiki') def force_load(self, paths=list): self.tab.force_load(paths) def findAndLoad(self, names=list()): ''' Find the names in PuppetMaster folder and load them Parameters ---------- names: (list) List of dictionaries of name and namespace. ''' if names: self.tab.findAndLoad(names) def destroyMayaSignals(self): # destroy the connection OpenMaya.MMessage.removeCallback(self.idx) def get_edit(self): return self.editMode def set_edit(self, value=bool): self.editMode = value self.background_action.setEnabled(self.editMode) self.namespace_action.setEnabled(self.editMode) self.parameterDock.setVisible(self.editMode) self.edit_action.setChecked(self.editMode) self.tab.Edit = self.editMode # Notification if not self.editMode: warningMes( "PUPPETMASTER-INFO: Out of 'Edit Mode' you won't be able to create/edit/move or delete any node." ) else: warningMes( "PUPPETMASTER-INFO: In 'Edit Mode' command buttons won't run any commands." ) Edit = property(get_edit, set_edit) def keyPressEvent(self, event): if event.modifiers() == (Qt.ControlModifier | Qt.ShiftModifier): if event.key() == Qt.Key_W: self.tab.closeCurrentTab() elif event.key() == Qt.Key_S: self.tab.saveAs_set() elif event.modifiers() == Qt.ControlModifier: if event.key() == Qt.Key_S: self.tab.save_set() elif event.key() == Qt.Key_N: self.tab.new_tab() elif event.key() == Qt.Key_O: self.tab.open_set() else: super(PuppetMaster, self).keyPressEvent(event)
class Docks: def __init__(self, WordListBox, DefinitionBox, HtmlWriter, Terminal, HorizontalFiller): # Definition Dock #-------------------------------------------------------------------------------------------- self._def_column = QWidget(self) self._def_layout = QGridLayout(self._def_column) self._def_dock = QDockWidget("Definition", self) #self._def_dock.setFeatures(self._def_dock.features() & ~QDockWidget.DockWidgetClosable) self._def_dock.setWidget(self._def_column) self.addDockWidget(Qt.LeftDockWidgetArea, self._def_dock) # Definition List Dock #-------------------------------------------------------------------------------------------- self._word_column = QWidget(self) self._word_layout = QGridLayout(self._word_column) self._word_dock = QDockWidget("Listed Definitions") self._word_listbox = WordListBox(self) self._word_listbox.itemClicked.connect(self.selectNewDefinition) #self._word_dock.setFeatures(self._def_dock.features() & ~QDockWidget.DockWidgetClosable) self._word_dock.setWidget(self._word_column) self.addDockWidget(Qt.LeftDockWidgetArea, self._word_dock) self.updateWordsListBox() #Web Dock #-------------------------------------------------------------------------------------------- self._view = QWebEngineView() # Loading the page. self.setDefaultUrl() self._search_bar = SearchToolBar(parent=self, view=self._view) self._search_bar.searchBar().returnPressed.connect(self.webSearch) # Setting up the web dock web_widget = QWidget(self) web_layout = QGridLayout(web_widget) # Place the web view in a widget. web_layout.addWidget(self._search_bar) web_layout.addWidget(self._view) web_layout.addWidget(self._search_bar.findBar()) web_layout.addWidget(VerticalFiller(self)) self._web_dock = QDockWidget("Web Browser", self) self._web_dock.setWidget(web_widget) self._web_dock.visibilityChanged.connect(self.webDockHandler) self.addDockWidget(Qt.RightDockWidgetArea, self._web_dock) # Html Editior Dock #-------------------------------------------------------------------------------------------- self._html_editor = HtmlWriter(parent=self) self._html_insert_button = QPushButton("Insert Html") self._html_insert_button.clicked.connect(self._html_editor.enterHtml) html_editor_widget = QWidget(self) html_editor_layout = QGridLayout(html_editor_widget) html_editor_layout.addWidget(QLabel("Enter Html to insert special formats (e.g. tables) into the document.")) html_editor_layout.addWidget(self._html_editor, 1, 0) button_row = QWidget(self) button_lay = QHBoxLayout(button_row) button_lay.addWidget(HorizontalFiller(self)) button_lay.addWidget(self._html_insert_button) html_editor_layout.addWidget(button_row, 2, 0) self._html_dock = QDockWidget("Html Editor", self) self._html_dock.setWidget(html_editor_widget) self.addDockWidget(Qt.RightDockWidgetArea, self._html_dock) # Terminal Dock #-------------------------------------------------------------------------------------------- self.TERMINAL = Terminal(self) self._terminal_dock = QDockWidget("Terminal", self) self._terminal_dock.setWidget(self.TERMINAL) self.addDockWidget(Qt.BottomDockWidgetArea, self._terminal_dock) self._terminal_dock.setVisible(False) def webDockHandler(self, visbility): """Resets the url when the user closes out the web dock. This is too limit web noise.""" if not visbility: self.setDefaultUrl() def setDefaultUrl(self): """ Set the default url to DuckDuckGo search page.""" self._view.load("https://duckduckgo.com/") def webSearch(self): self._view.load(self._search_bar.currentUrl()) def selectNewDefinition(self, item): """ When a definition is selected from the defintion word list, this method will write the new definition in the definiton box. """ word = item.text() definition = self._database.getDefinition(word[0], word) if definition != None and len(definition): self._definition_box.setText("<b><u>"+word+"</u></b> - "+definition) def updateWordsListBox(self): """Updates the definition word list when dictionary is changed or a new word is added.""" self._word_listbox.clear() for word in list(sorted(self._database.getAllDictWords())): self._word_listbox.addItem(word) def getWordsInListBox(self): """Returns a list of words from the presently selected dictionary.""" words = [] for row in range(0, self._word_listbox.count()): words.append(self._word_listbox.item(row).text()) return words def changeDatabase(self): """ When a new dictionary database is selected, this will update the highlighter to adjust to the new definitions. """ database_name = self._database_combo.currentText() self._database.setNewDatabase(database_name) self.activeNotepad().highlighter.updateRules() self.updateWordsListBox() self._definition_box.clear() self.activeNotepad().highlighter.rehighlight() def updateDatabaseNames(self): """Populates the dictionary combobox with the currently available dictionaries.""" # Keep the current selected dictionary when adding new dictionaries to the list. current_dict_text = self._database_combo.currentText() text_location = 0 self._database_combo.clear() databases = sorted([file_name.split(".")[0] for file_name in os.listdir(self.DATABASE_PATH)]) self._database_combo.addItems(databases) text_location = self._database_combo.findText(current_dict_text) self._database_combo.setCurrentIndex(text_location) def terminal(self, message): """Sends a message to the terminal dock.""" self.TERMINAL.insertBlueArrows() self.TERMINAL.insertPlainText(message)