class CodecTab(QScrollArea):

    # BUG: codec_frame should have height 210 but has 480.
    # WORKAROUND: manually set height to 210 height.
    # SEE: https://forum.qt.io/topic/42055/qwidget-height-returns-incorrect-value-in-5-3/7
    FRAME_HEIGHT = 210

    def __init__(self, parent, context, commands):
        super(QWidget, self).__init__(parent)
        self._context = context
        self._logger = context.logger()
        self._commands = commands

        self._next_frame_id = 1
        self._frames = QSplitter(Qt.Vertical)
        self._frames.setChildrenCollapsible(False)
        self._frames.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self._frames.setContentsMargins(0, 0, 0, 0)

        self._main_frame = QFrame(self)
        self._main_frame_layout = QVBoxLayout()
        self._main_frame_layout.addWidget(self._frames)
        self._main_frame_layout.addWidget(VSpacer(self))
        self._main_frame.setLayout(self._main_frame_layout)
        self.newFrame("", "")

        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setWidgetResizable(True)
        self.setWidget(self._main_frame)

    def newFrame(self,
                 text,
                 title,
                 previous_frame=None,
                 status=None,
                 msg=None):
        try:
            # BUG: Setting complex default values is not possible in python
            # WORKAROUND: Set default value to None and set real default later.
            if status is None:
                status = StatusWidget.DEFAULT

            if previous_frame and previous_frame.hasNext():
                next_frame = previous_frame.next()
                next_frame.setTitle(title)
                finished = False
                if status == StatusWidget.ERROR:
                    while not finished:
                        next_frame.flashStatus(status, msg)
                        # Display error only for the first frame.
                        msg = None
                        finished = not next_frame.hasNext()
                        next_frame = next_frame.next()
                else:
                    next_frame.setInputText(text, msg is not None
                                            and len(msg) > 0)
                    next_frame.flashStatus(status, msg)

                previous_frame.focusInputText()
            else:
                new_frame = CodecFrame(self, self._context,
                                       self._next_frame_id, self,
                                       self._commands, previous_frame, text)
                self._next_frame_id += 1
                if self._frames.count() > 0:
                    new_frame.flashStatus(status, msg)
                new_frame.setTitle(title)
                new_frame.setContentsMargins(0, 0, 0, 0)
                new_frame.layout().setContentsMargins(0, 0, 0, 0)
                self._frames.addWidget(new_frame)

                # BUG: QSplitter does not allow frames to be wider than the surrounding area (here: QScrollArea).
                # WORKAROUND: Set a fixed size for codec frames and disable handles which prevents users from
                #             trying to resize the codec frames.
                new_frame.setFixedHeight(self.FRAME_HEIGHT)
                self._frames.handle(self._frames.count() - 1).setEnabled(False)

                if previous_frame:
                    previous_frame.focusInputText()
                else:
                    new_frame.focusInputText()
        except Exception as e:
            self._logger.error("Unknown error: {}".format(str(e)))

    def removeFrames(self, frame):
        if frame:
            if frame.previous():
                frame.previous().setNext(None)

            frames_to_remove = [frame]
            while frame.next():
                frames_to_remove.append(frame.next())
                frame = frame.next()
            for frame_to_remove in reversed(frames_to_remove):
                frame_to_remove.deleteLater()

    def getFocussedFrame(self):
        widget = self._frames.focusWidget()
        while widget:
            if isinstance(widget, CodecFrame):
                return widget
            widget = widget.parent()
        return self._frames.widget(0)
Example #2
0
class PrioritizeDialog(QDialog):
    def __init__(self, parent, app, **kwargs):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        super().__init__(parent, flags, **kwargs)
        self._setupUi()
        self.model = PrioritizeDialogModel(app=app.model)
        self.categoryList = ComboboxModel(model=self.model.category_list,
                                          view=self.categoryCombobox)
        self.criteriaList = ListviewModel(model=self.model.criteria_list,
                                          view=self.criteriaListView)
        self.prioritizationList = PrioritizationList(
            model=self.model.prioritization_list,
            view=self.prioritizationListView)
        self.model.view = self

        self.addCriteriaButton.clicked.connect(self.model.add_selected)
        self.criteriaListView.doubleClicked.connect(self.model.add_selected)
        self.removeCriteriaButton.clicked.connect(self.model.remove_selected)
        self.prioritizationListView.doubleClicked.connect(
            self.model.remove_selected)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def _setupUi(self):
        self.setWindowTitle(tr("Re-Prioritize duplicates"))
        self.resize(700, 400)

        # widgets
        msg = tr(
            "Add criteria to the right box and click OK to send the dupes that correspond the "
            "best to these criteria to their respective group's "
            "reference position. Read the help file for more information.")
        self.promptLabel = QLabel(msg)
        self.promptLabel.setWordWrap(True)
        self.categoryCombobox = QComboBox()
        self.criteriaListView = QListView()
        self.criteriaListView.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.addCriteriaButton = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowRight), "")
        self.removeCriteriaButton = QPushButton(
            self.style().standardIcon(QStyle.SP_ArrowLeft), "")
        self.prioritizationListView = QListView()
        self.prioritizationListView.setAcceptDrops(True)
        self.prioritizationListView.setDragEnabled(True)
        self.prioritizationListView.setDragDropMode(
            QAbstractItemView.InternalMove)
        self.prioritizationListView.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.prioritizationListView.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)

        # layout
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.addWidget(self.promptLabel)
        self.splitter = QSplitter()
        sp = self.splitter.sizePolicy()
        sp.setVerticalPolicy(QSizePolicy.Expanding)
        self.splitter.setSizePolicy(sp)
        self.leftSide = QWidget()
        self.leftWidgetsLayout = QVBoxLayout()
        self.leftWidgetsLayout.addWidget(self.categoryCombobox)
        self.leftWidgetsLayout.addWidget(self.criteriaListView)
        self.leftSide.setLayout(self.leftWidgetsLayout)
        self.splitter.addWidget(self.leftSide)
        self.rightSide = QWidget()
        self.rightWidgetsLayout = QHBoxLayout()
        self.addRemoveButtonsLayout = QVBoxLayout()
        self.addRemoveButtonsLayout.addItem(verticalSpacer())
        self.addRemoveButtonsLayout.addWidget(self.addCriteriaButton)
        self.addRemoveButtonsLayout.addWidget(self.removeCriteriaButton)
        self.addRemoveButtonsLayout.addItem(verticalSpacer())
        self.rightWidgetsLayout.addLayout(self.addRemoveButtonsLayout)
        self.rightWidgetsLayout.addWidget(self.prioritizationListView)
        self.rightSide.setLayout(self.rightWidgetsLayout)
        self.splitter.addWidget(self.rightSide)
        self.mainLayout.addWidget(self.splitter)
        self.mainLayout.addWidget(self.buttonBox)
Example #3
0
class PrioritizeDialog(QDialog):
    def __init__(self, parent, app, **kwargs):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        super().__init__(parent, flags, **kwargs)
        self._setupUi()
        self.model = PrioritizeDialogModel(app=app.model)
        self.categoryList = ComboboxModel(model=self.model.category_list, view=self.categoryCombobox)
        self.criteriaList = ListviewModel(model=self.model.criteria_list, view=self.criteriaListView)
        self.prioritizationList = PrioritizationList(
            model=self.model.prioritization_list, view=self.prioritizationListView
        )
        self.model.view = self

        self.addCriteriaButton.clicked.connect(self.model.add_selected)
        self.removeCriteriaButton.clicked.connect(self.model.remove_selected)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def _setupUi(self):
        self.setWindowTitle(tr("Re-Prioritize duplicates"))
        self.resize(700, 400)

        #widgets
        msg = tr(
            "Add criteria to the right box and click OK to send the dupes that correspond the "
            "best to these criteria to their respective group's "
            "reference position. Read the help file for more information."
        )
        self.promptLabel = QLabel(msg)
        self.promptLabel.setWordWrap(True)
        self.categoryCombobox = QComboBox()
        self.criteriaListView = QListView()
        self.addCriteriaButton = QPushButton(self.style().standardIcon(QStyle.SP_ArrowRight), "")
        self.removeCriteriaButton = QPushButton(self.style().standardIcon(QStyle.SP_ArrowLeft), "")
        self.prioritizationListView = QListView()
        self.prioritizationListView.setAcceptDrops(True)
        self.prioritizationListView.setDragEnabled(True)
        self.prioritizationListView.setDragDropMode(QAbstractItemView.InternalMove)
        self.prioritizationListView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)

        # layout
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.addWidget(self.promptLabel)
        self.splitter = QSplitter()
        sp = self.splitter.sizePolicy()
        sp.setVerticalPolicy(QSizePolicy.Expanding)
        self.splitter.setSizePolicy(sp)
        self.leftSide = QWidget()
        self.leftWidgetsLayout = QVBoxLayout()
        self.leftWidgetsLayout.addWidget(self.categoryCombobox)
        self.leftWidgetsLayout.addWidget(self.criteriaListView)
        self.leftSide.setLayout(self.leftWidgetsLayout)
        self.splitter.addWidget(self.leftSide)
        self.rightSide = QWidget()
        self.rightWidgetsLayout = QHBoxLayout()
        self.addRemoveButtonsLayout = QVBoxLayout()
        self.addRemoveButtonsLayout.addItem(verticalSpacer())
        self.addRemoveButtonsLayout.addWidget(self.addCriteriaButton)
        self.addRemoveButtonsLayout.addWidget(self.removeCriteriaButton)
        self.addRemoveButtonsLayout.addItem(verticalSpacer())
        self.rightWidgetsLayout.addLayout(self.addRemoveButtonsLayout)
        self.rightWidgetsLayout.addWidget(self.prioritizationListView)
        self.rightSide.setLayout(self.rightWidgetsLayout)
        self.splitter.addWidget(self.rightSide)
        self.mainLayout.addWidget(self.splitter)
        self.mainLayout.addWidget(self.buttonBox)
Example #4
0
class MiniGCS(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.mav = None
        self.param = UserData.getInstance().getUserDataEntry(
            UD_MAIN_WINDOW_KEY, {})
        current_path = os.path.abspath(os.path.dirname(__file__))
        qmlFile = os.path.join(current_path, './instruments/map.qml')
        self.setWindowTitle('Mini GCS')
        if UD_MAIN_WINDOW_HEIGHT_KEY in self.param and UD_MAIN_WINDOW_WIDTH_KEY in self.param:
            self.resize(self.param[UD_MAIN_WINDOW_WIDTH_KEY],
                        self.param[UD_MAIN_WINDOW_HEIGHT_KEY])
        self.teleWindow = ConnectionEditWindow()
        self.teleWindow.MAVLinkConnectedSignal.connect(self.createConnection)
        self.window = QSplitter()
        self.left = QSplitter(Qt.Vertical, self.window)
        self.pfd = PrimaryFlightDisplay(self.window)
        self.sts = SystemStatusPanel(self.window)
        self.msgSignWindow = MessageSigningSetupWindow()
        self.hudWindow = HUDWindow()
        self.hud = self.hudWindow.hud
        self.sts.connectToMAVLink.connect(self.teleWindow.show)
        self.sts.disconnectFromMAVLink.connect(self.disconnect)
        spPfd = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        spPfd.setVerticalStretch(3)
        self.pfd.setSizePolicy(spPfd)
        spSts = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        spSts.setVerticalStretch(2)
        self.sts.setSizePolicy(spSts)
        self.left.addWidget(self.pfd)
        self.left.addWidget(self.sts)
        spLeft = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        spLeft.setHorizontalStretch(2)
        self.left.setSizePolicy(spLeft)
        self.map = MapWidget(qmlFile)
        spRight = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        spRight.setHorizontalStretch(5)
        self.map.setSizePolicy(spRight)
        self.window.addWidget(self.left)
        self.window.addWidget(self.map)
        self.localGPSWindow = GPSConfigurationWindow()
        # TODO configurable behavior
        self.localGPSWindow.connection.locationUpdate.connect(
            self.map.updateHomeLocationEvent)
        self.sts.connectToLocalGPS.connect(self.localGPSWindow.show)
        self.sts.disconnectFromLocalGPS.connect(
            self.localGPSWindow.connection.disconnect)
        self.sts.statusPanel.showHUDButton.clicked.connect(self.hudWindow.show)
        self.teleWindow.cancelConnectionSignal.connect(
            lambda: self.sts.statusPanel.connectButton.setEnabled(True))

        self.__createMenus()
        self.setCentralWidget(self.window)

    def __createMenus(self):
        self.exitAction = QAction('Exit', self)
        self.exitAction.triggered.connect(qApp.exit)
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(self.exitAction)

        self.localGPSAction = QAction('Local GPS', self)
        self.localGPSAction.triggered.connect(
            self.sts.statusPanel.toggleGPSButtonLabel)
        self.showHUDAction = QAction('HUD', self)
        self.showHUDAction.triggered.connect(self.hudWindow.show)
        self.showMsgSignAction = QAction('Message Signing', self)
        self.showMsgSignAction.triggered.connect(self.msgSignWindow.show)
        self.baroRefCfgWindow = BarometerConfigWindow(
            DEFAULT_ALTITUDE_REFERENCE, DEFAULT_PRESSURE_REFERENCE)
        self.baroRefCfgAction = QAction('Pressure Altitude Reference', self)
        self.baroRefCfgAction.triggered.connect(self.baroRefCfgWindow.show)
        self.plotterWindow = PlotterWindow('MAVLink Plotter')
        self.plotterAction = QAction('Plotter', self)
        self.plotterAction.triggered.connect(self.plotterWindow.show)
        self.servoOutputWindow = ServoOutputCheckWindow(8)
        self.servoOutputAction = QAction('Servo Output', self)
        self.servoOutputAction.triggered.connect(self.servoOutputWindow.show)
        toolsMenu = menubar.addMenu('&Tools')
        toolsMenu.addAction(self.localGPSAction)
        toolsMenu.addAction(self.showHUDAction)
        toolsMenu.addAction(self.showMsgSignAction)
        toolsMenu.addAction(self.baroRefCfgAction)
        toolsMenu.addAction(self.plotterAction)
        toolsMenu.addAction(self.servoOutputAction)

    def createConnection(self, conn):
        self.mav = MAVLinkConnection(
            conn, isinstance(conn, pymavlink.mavutil.mavlogfile))
        self.mav.heartbeatTimeoutSignal.connect(
            self.sts.statusPanel.resetConnectionButton)
        self.mav.establishConnection()
        if self.mav.running == False:
            QMessageBox.critical(self, 'Error', 'MAVLink connection timeout',
                                 QMessageBox.Ok)
            return
        self.map.waypointList.requestReturnToHome.connect(
            self.mav.initializeReturnToHome)
        self.map.uploadWaypointsToUAVEvent.connect(self.mav.uploadWaypoints)
        self.map.downloadWaypointsFromUAVSignal.connect(
            self.mav.downloadWaypoints)

        self.mav.connectionEstablishedSignal.connect(lambda: \
            self.sts.statusPanel.toggleButtonLabel(True))
        self.sts.addAPControlPanel(self.mav.uas.autopilotClass)
        self.mav.newTextMessageSignal.connect(self.map.displayTextMessage)
        self.mav.onboardWaypointsReceivedSignal.connect(
            self.map.setAllWaypoints)

        self.pfd.setActiveUAS(self.mav.uas)
        self.hud.setActiveUAS(self.mav.uas)
        # self.hud.enableVideo(True)
        # fpv = FileVideoSource('test.mp4')  # test only
        # self.hud.setVideoSource(fpv)
        self.mav.externalMessageHandler.connect(
            self.plotterWindow.handleMavlinkMessage)
        self.map.setActiveUAS(self.mav.uas)
        self.sts.statusPanel.setActiveUAS(self.mav.uas)
        self.sts.compassPanel.setActiveUAS(self.mav.uas)
        self.sts.barometerPanel.setActiveUAS(self.mav.uas)
        self.baroRefCfgWindow.updatePressureAltitudeReferenceSignal.connect(
            self.mav.uas.setPressureAltitudeReference)
        self.msgSignWindow.setMessageSigningKeySignal.connect(
            self.mav.setupMessageSigningKey)
        self.msgSignWindow.setMessageSigningKeySignal.connect(
            self.mav.uas.acceptMessageSigningKey)

        self.sts.statusPanel.editParameterButton.clicked.connect(
            self.mav.showParameterEditWindow)
        self.sts.initializaMavlinkForControlPanels(self.mav)
        self.servoOutputWindow.mavlinkMotorTestSignal.connect(
            self.mav.sendMavlinkMessage)

        self.msgSignWindow.setMAVLinkVersion(
            self.mav.connection.WIRE_PROTOCOL_VERSION)
        self.mav.start()

    def disconnect(self):
        self.mav.requestExit()

    def closeEvent(self, event):
        print('[MAIN] closeEvent')
        ud = UserData.getInstance()
        s = self.size()
        self.param[UD_MAIN_WINDOW_HEIGHT_KEY] = s.height()
        self.param[UD_MAIN_WINDOW_WIDTH_KEY] = s.width()
        ud.setUserDataEntry(UD_MAIN_WINDOW_KEY, self.param)
        try:
            ud.saveGCSConfiguration()
            print('GCS Conf saved.')
        except IOError:
            pass
        super().closeEvent(event)
Example #5
0
 def __init__(self, parent=None):
     self.parent = parent
     self.window_type = "t"
     self.allow_closing = False
     super().__init__()
     self.setWindowTitle("Map-Spectrum Table")
     self.current_focused_table = None
     # 前処理
     self.preprocess_layout = my_w.ClickableLayout(parent=self)
     pre_inside_widget = QWidget()
     pre_inside_widget.setLayout(self.preprocess_layout)
     pre_inside_widget.setObjectName("map_inside_widget")
     pre_inside_widget.setStyleSheet(
         "QWidget#map_inside_widget{background-color: white}")
     pre_scroll_area = QScrollArea()
     pre_scroll_area.setWidgetResizable(True)
     pre_scroll_area.setWidget(pre_inside_widget)
     pre_area_layout = QVBoxLayout()
     pre_area_layout.setContentsMargins(0, 0, 0, 0)
     pre_area_layout.setSpacing(0)
     pre_area_layout.addWidget(
         gf.QRichLabel("pre-processing", font=gf.boldFont))
     pre_area_layout.addWidget(pre_scroll_area)
     # マップエリア
     self.map_layout = my_w.ClickableLayout(parent=self)
     map_inside_widget = QWidget()
     map_inside_widget.setLayout(self.map_layout)
     map_inside_widget.setObjectName("map_inside_widget")
     map_inside_widget.setStyleSheet(
         "QWidget#map_inside_widget{background-color: white}")
     map_scroll_area = QScrollArea()
     map_scroll_area.setWidgetResizable(True)
     map_scroll_area.setWidget(map_inside_widget)
     map_area_layout = QVBoxLayout()
     map_area_layout.setContentsMargins(0, 0, 0, 0)
     map_area_layout.setSpacing(0)
     map_area_layout.addWidget(
         gf.QRichLabel("Added Hyperspectral Data", font=gf.boldFont))
     map_area_layout.addWidget(map_scroll_area)
     # スペクトルエリア
     self.spectrum_layout = my_w.ClickableLayout(parent=self)
     spectrum_inside_widget = QWidget()
     spectrum_inside_widget.setLayout(self.spectrum_layout)
     spectrum_inside_widget.setObjectName("spectrum_inside_widget")
     spectrum_inside_widget.setStyleSheet(
         "QWidget#spectrum_inside_widget{background-color: white}")
     spectrum_scroll_area = QScrollArea()
     spectrum_scroll_area.setWidgetResizable(True)
     spectrum_scroll_area.setWidget(spectrum_inside_widget)
     spectrum_area_layout = QVBoxLayout()
     spectrum_area_layout.setContentsMargins(0, 0, 0, 0)
     spectrum_area_layout.setSpacing(0)
     spectrum_area_layout.addWidget(
         gf.QRichLabel("Added Spectrum Data", font=gf.boldFont))
     spectrum_area_layout.addWidget(spectrum_scroll_area)
     # 前処理ボタンエリア
     self.btn_p_CRR = QPushButton("CRR")
     self.btn_p_CRR.setToolTip("Cosmic Ray Removal")
     self.btn_p_CRR.setFixedWidth(50)
     self.btn_p_CRR.setEnabled(False)
     self.btn_p_NR = QPushButton("NR")
     self.btn_p_NR.setToolTip("PCA-based noise reduction")
     self.btn_p_NR.setFixedWidth(50)
     self.btn_p_NR.setEnabled(False)
     self.btn_p_revert = QPushButton("revert")
     self.btn_p_revert.setFixedWidth(100)
     self.btn_p_revert.setEnabled(False)
     self.btn_p_hide_show = QPushButton("hide/show")
     self.btn_p_hide_show.setFixedWidth(100)
     self.btn_p_hide_show.setEnabled(False)
     btnLayout_p = QHBoxLayout()
     btnLayout_p.setContentsMargins(0, 0, 0, 0)
     btnLayout_p.setSpacing(7)
     btnLayout_p.addWidget(self.btn_p_CRR)
     btnLayout_p.addWidget(self.btn_p_NR)
     btnLayout_p.addStretch(1)
     btnLayout_p.addWidget(self.btn_p_hide_show)
     btnLayout_p.addWidget(self.btn_p_revert)
     # マップボタンエリア
     btn_width = 97
     self.btn_m_export = my_w.CustomMenuButton("export",
                                               icon_path=gf.icon_path,
                                               divide=False)
     self.btn_m_export.setFixedWidth(btn_width)
     self.btn_m_export.setEnabled(False)
     self.btn_m_remove = my_w.CustomMenuButton("remove",
                                               icon_path=gf.icon_path,
                                               divide=True)
     self.btn_m_remove.setFixedWidth(btn_width)
     self.btn_m_remove.setEnabled(False)
     self.btn_m_hide_show = QPushButton("hide/show")  #, divide=True)
     self.btn_m_hide_show.setFixedWidth(btn_width)
     self.btn_m_hide_show.setEnabled(False)
     self.btn_m_others = my_w.CustomMenuButton("",
                                               icon_path=gf.icon_path,
                                               divide=False)
     self.btn_m_others.setFixedWidth(35)
     self.btn_m_others.setEnabled(False)
     btnLayout_m = QHBoxLayout()
     btnLayout_m.setContentsMargins(0, 0, 0, 0)
     btnLayout_m.setSpacing(7)
     btnLayout_m.addStretch(1)
     btnLayout_m.addWidget(self.btn_m_export)
     btnLayout_m.addWidget(self.btn_m_remove)
     btnLayout_m.addWidget(self.btn_m_hide_show)
     btnLayout_m.addWidget(self.btn_m_others)
     # スペクトルボタンエリア
     self.btn_s_export = my_w.CustomMenuButton("export",
                                               icon_path=gf.icon_path,
                                               divide=False)
     self.btn_s_export.setFixedWidth(btn_width)
     self.btn_s_export.setEnabled(False)
     self.btn_s_remove = my_w.CustomMenuButton("remove",
                                               icon_path=gf.icon_path,
                                               divide=True)
     self.btn_s_remove.setFixedWidth(btn_width)
     self.btn_s_remove.setEnabled(False)
     self.btn_s_hide_show = my_w.CustomMenuButton("hide/show",
                                                  icon_path=gf.icon_path,
                                                  divide=True)
     self.btn_s_hide_show.setFixedWidth(btn_width)
     self.btn_s_hide_show.setEnabled(False)
     self.btn_s_others = my_w.CustomMenuButton("",
                                               icon_path=gf.icon_path,
                                               divide=False)
     self.btn_s_others.setFixedWidth(35)
     self.btn_s_others.setEnabled(False)
     btnLayout_s = QHBoxLayout()
     btnLayout_s.setContentsMargins(0, 0, 0, 0)
     btnLayout_s.setSpacing(7)
     btnLayout_s.addStretch(1)
     btnLayout_s.addWidget(self.btn_s_export)
     btnLayout_s.addWidget(self.btn_s_remove)
     btnLayout_s.addWidget(self.btn_s_hide_show)
     btnLayout_s.addWidget(self.btn_s_others)
     # レイアウト
     pre_area_layout.addLayout(btnLayout_p)
     map_area_layout.addLayout(btnLayout_m)
     spectrum_area_layout.addLayout(btnLayout_s)
     pre_area_widget = QWidget()
     policy = pre_area_widget.sizePolicy()
     policy.setVerticalStretch(4)
     pre_area_widget.setSizePolicy(policy)
     pre_area_widget.setLayout(pre_area_layout)
     map_area_widget = QWidget()
     map_area_widget.setLayout(map_area_layout)
     spectrum_area_widget = QWidget()
     spectrum_area_widget.setLayout(spectrum_area_layout)
     sub_area = QSplitter(Qt.Horizontal)
     policy = sub_area.sizePolicy()
     policy.setVerticalStretch(10)
     sub_area.setSizePolicy(policy)
     sub_area.addWidget(map_area_widget)
     sub_area.addWidget(spectrum_area_widget)
     main_area = QSplitter(Qt.Vertical)
     main_area.addWidget(pre_area_widget)
     main_area.addWidget(sub_area)
     self.resize(self.width(), 600)
     self.layout = QVBoxLayout()
     self.layout.setSpacing(0)
     self.layout.addWidget(main_area)
     # メニュー
     s_export_menu = QMenu()
     self.s_e_action_dict = {}
     self.s_e_action_dict["as spc"] = s_export_menu.addAction(
         'as spc', functools.partial(self.btn_export_clicked_s, ext=".spc"))
     self.s_e_action_dict["as text"] = s_export_menu.addAction(
         'as text', functools.partial(self.btn_export_clicked_s,
                                      ext=".txt"))
     self.s_e_action_dict["as info"] = s_export_menu.addAction(
         'as info', functools.partial(self.btn_export_clicked_s,
                                      ext=".info"))
     s_remove_menu = QMenu()
     s_remove_menu.addAction('remove all', self.remove_all_clicked_s)
     s_hide_show_menu = QMenu()
     s_hide_show_menu.addAction(
         'hide/show all',
         functools.partial(self.hide_show_all_clicked,
                           target_layout="spectrum"))
     s_others_menu = QMenu()
     s_others_menu.addAction(
         "add custom name",
         functools.partial(self.add_custom_name_clicked, map_or_spc="spc"))
     s_others_menu.addAction(
         "remove custom name",
         functools.partial(self.add_custom_name_clicked,
                           map_or_spc="spc",
                           text=""))
     m_export_menu = QMenu()
     self.m_e_action_dict = {}
     self.m_e_action_dict["as tiff \& svg"] = m_export_menu.addAction(
         'as tiff / svg',
         functools.partial(self.btn_export_clicked_m, ext=".tiff .svg"))
     self.m_e_action_dict["as spc"] = m_export_menu.addAction(
         'as spc', functools.partial(self.btn_export_clicked_m, ext=".spc"))
     m_remove_menu = QMenu()
     m_remove_menu.addAction('remove all', self.remove_all_clicked_m)
     m_others_menu = QMenu()
     m_others_menu.addAction(
         "add custom name",
         functools.partial(self.add_custom_name_clicked, map_or_spc="map"))
     m_others_menu.addAction(
         "remove custom name",
         functools.partial(self.add_custom_name_clicked,
                           map_or_spc="map",
                           text=""))
     # m_hide_show_menu = QMenu()
     # m_hide_show_menu.addAction('hide/show all', functools.partial(self.hide_show_all_clicked, target_layout="map"))
     # イベントコネクト
     self.btn_p_CRR.clicked.connect(self.btn_CRR_clicked_p)
     self.btn_p_NR.clicked.connect(self.btn_NR_clicked_p)
     self.btn_p_revert.clicked.connect(self.btn_revert_clicked_p)
     self.btn_p_hide_show.clicked.connect(
         functools.partial(self.btn_hide_show_clicked,
                           target_layout="preprocess"))
     self.btn_s_export.setMenu(s_export_menu)
     self.btn_s_remove.clicked.connect(self.btn_remove_clicked_s)
     self.btn_s_remove.setMenu(s_remove_menu)
     self.btn_s_hide_show.clicked.connect(
         functools.partial(self.btn_hide_show_clicked,
                           target_layout="spectrum"))
     self.btn_s_hide_show.setMenu(s_hide_show_menu)
     self.btn_s_others.setMenu(s_others_menu)
     self.btn_m_export.setMenu(m_export_menu)
     self.btn_m_remove.clicked.connect(self.btn_remove_clicked_m)
     self.btn_m_remove.setMenu(m_remove_menu)
     self.btn_m_hide_show.clicked.connect(
         functools.partial(self.btn_hide_show_clicked, target_layout="map"))
     self.btn_m_others.setMenu(m_others_menu)
     # その他
     self.setFocusPolicy(Qt.StrongFocus)
     # self.setLayout(self.layout)
     # tab barが現れるのを防ぐため、QWidget ではなく QMainWindow で window を作成し、TabBarを消去した。
     central_widget = QWidget()
     central_widget.setLayout(self.layout)
     self.setCentralWidget(central_widget)
     self.setUnifiedTitleAndToolBarOnMac(True)
Example #6
0
class PlotWidgetContainer(QWidget):
    def __init__(self, modelRoot, *args, **kwargs):
        super(PlotWidgetContainer, self).__init__(*args)
        self.modelRoot = modelRoot
        if len(moose.wildcardFind(modelRoot + "/##[ISA=ChemCompt]")) == 0:
            self.modelType = ELECTRICAL
        else:
            self.modelType = CHEMICAL

        self.model = moose.element(self.modelRoot)
        if self.modelRoot != "/":
            self.modelRoot = self.findModelPath(self.modelRoot)
            if moose.exists(modelRoot + "/data"):
                self.data = moose.element(self.modelRoot + "/data")
            else:
                self.data = moose.Neutral(self.modelRoot + "/data")
        else:
            self.data = moose.element("/data")

        self._layout = QVBoxLayout()
        self.graphs = QSplitter()
        self.graphs.setOrientation(QtCore.Qt.Vertical)
        self.graphsArea = QScrollArea()
        self.rowIndex = 0
        self.graphs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setAcceptDrops(True)
        self.graphsArea.setWidget(self.graphs)
        self.graphsArea.setWidgetResizable(True)
        self.graphWidgets = []
        self._layout.addWidget(self.graphsArea)
        self.setLayout(self._layout)

        for graph in self.data.children:
            self.addPlotWidget(graph=graph)

        if len(self.data.children) == 0:
            self.addPlotWidget()

    def mooseIsInstance(self, element, classNames):
        return moose.element(element).__class__.__name__ in classNames

    def findModelPath(self, element):
        child = element
        while not self.mooseIsInstance(element, "Shell"):
            child = moose.element(element).path
            element = moose.element(element).parent
        return child

    def deleteWidget(self, graphWidget):
        # print("Deleted => ", graphWidget)
        self.graphWidgets.remove(graphWidget)
        graphWidget.setParent(None)
        graphWidget.close()

    def createMenuBar(self):
        bar = sidebar.sidebar()
        bar.addAction(
            sidebar.add_graph_action(bar, lambda event: self.addPlotWidget()))
        return bar

    def addPlotWidget(self, row=None, col=0, graph=None):
        if graph == None:
            graph = moose.Neutral(self.data.path + "/graph_" +
                                  str(self.rowIndex))

        if row == None:
            row = self.rowIndex

        #if self.modelType == ELECTRICAL:
        #    for axes in list(widget.canvas.axes.values()):
        #        axes.set_ylim(bottom = -0.07, top= 0.03)

        # FIXME:
        # Has been removed? See #23
        #  widget = default.PlotWidget(self.model, graph, self.rowIndex, self)
        ## self.graphs.addWidget(widget)
        ## self.rowIndex += 1
        ## self.graphWidgets.append(widget)
        ## widget.widgetClosedSignal.connect(self.deleteWidget)
        ## widget.addGraph.connect(lambda event : self.addPlotWidget())
        ## return widget

    def showPlotView(self):
        pass

    def setModelRoot(self, *args):
        pass

    def getMenus(self, *args):
        return []

    def setDataRoot(self, *args):
        pass

    def updatePlots(self):
        for graphWidget in self.graphWidgets:
            graphWidget.updatePlots()

    def rescalePlots(self):
        for graphWidget in self.graphWidgets:
            graphWidget.rescalePlots()

    def extendXAxes(self, xlim):
        for graphWidget in self.graphWidgets:
            graphWidget.extendXAxes(xlim)

    def plotAllData(self):
        for graphWidget in self.graphWidgets:
            graphWidget.plotAllData()
Example #7
0
    def createMain(self):
        self.testIndexTracker = 0
        self.MainBodyBox = QGroupBox()

        mainbodylayout = QHBoxLayout()

        kMinimumWidth = 120
        kMaximumWidth = 150
        kMinimumHeight = 30
        kMaximumHeight = 80

        # Splitters
        MainSplitter = QSplitter(Qt.Horizontal)
        LeftColSplitter = QSplitter(Qt.Vertical)
        RightColSplitter = QSplitter(Qt.Vertical)

        #Group Box for controller
        ControllerBox = QGroupBox()
        ControllerSP = ControllerBox.sizePolicy()
        ControllerSP.setVerticalStretch(self.VerticalSegCol0[0])
        ControllerBox.setSizePolicy(ControllerSP)

        self.ControlLayout = QGridLayout()

        self.CustomizedButton = QPushButton("&Customize...")
        self.CustomizedButton.clicked.connect(self.customizeTest)
        self.ResetButton = QPushButton("&Reset")
        self.ResetButton.clicked.connect(self.resetConfigTest)
        self.RunButton = QPushButton("&Run")
        self.RunButton.setDefault(True)
        self.RunButton.clicked.connect(self.initialTest)
        self.RunButton.clicked.connect(self.runTest)
        #self.ContinueButton = QPushButton("&Continue")
        #self.ContinueButton.clicked.connect(self.sendProceedSignal)
        self.AbortButton = QPushButton("&Abort")
        self.AbortButton.clicked.connect(self.abortTest)
        #self.SaveButton = QPushButton("&Save")
        #self.SaveButton.clicked.connect(self.saveTest)
        self.saveCheckBox = QCheckBox("&auto-save to DB")
        self.saveCheckBox.setMaximumHeight(30)
        self.saveCheckBox.setChecked(self.autoSave)
        if not isActive(self.connection):
            self.saveCheckBox.setChecked(False)
            self.saveCheckBox.setDisabled(True)
        self.saveCheckBox.clicked.connect(self.setAutoSave)

        self.ControlLayout.addWidget(self.CustomizedButton, 0, 0, 1, 2)
        self.ControlLayout.addWidget(self.ResetButton, 0, 2, 1, 1)
        self.ControlLayout.addWidget(self.RunButton, 1, 0, 1, 1)
        self.ControlLayout.addWidget(self.AbortButton, 1, 1, 1, 1)
        self.ControlLayout.addWidget(self.saveCheckBox, 1, 2, 1, 1)

        ControllerBox.setLayout(self.ControlLayout)

        #Group Box for ternimal display
        TerminalBox = QGroupBox("&Terminal")
        TerminalSP = TerminalBox.sizePolicy()
        TerminalSP.setVerticalStretch(self.VerticalSegCol0[1])
        TerminalBox.setSizePolicy(TerminalSP)
        TerminalBox.setMinimumWidth(400)

        ConsoleLayout = QGridLayout()

        self.ConsoleView = QPlainTextEdit()
        self.ConsoleView.setStyleSheet(
            "QTextEdit { background-color: rgb(10, 10, 10); color : white; }")
        #self.ConsoleView.setCenterOnScroll(True)
        self.ConsoleView.ensureCursorVisible()

        ConsoleLayout.addWidget(self.ConsoleView)
        TerminalBox.setLayout(ConsoleLayout)

        #Group Box for output display
        OutputBox = QGroupBox("&Result")
        OutputBoxSP = OutputBox.sizePolicy()
        OutputBoxSP.setVerticalStretch(self.VerticalSegCol1[0])
        OutputBox.setSizePolicy(OutputBoxSP)

        OutputLayout = QGridLayout()
        self.ResultWidget = ResultTreeWidget(self.info, self.DisplayW,
                                             self.DisplayH, self.master)
        #self.DisplayTitle = QLabel('<font size="6"> Result: </font>')
        #self.DisplayLabel = QLabel()
        #self.DisplayLabel.setScaledContents(True)
        #self.DisplayView = QPixmap('test_plots/test_best1.png').scaled(QSize(self.DisplayW,self.DisplayH), Qt.KeepAspectRatio, Qt.SmoothTransformation)
        #self.DisplayLabel.setPixmap(self.DisplayView)
        #self.ReferTitle = QLabel('<font size="6"> Reference: </font>')
        #self.ReferLabel = QLabel()
        #self.ReferLabel.setScaledContents(True)
        #self.ReferView = QPixmap('test_plots/test_best1.png').scaled(QSize(self.DisplayW,self.DisplayH), Qt.KeepAspectRatio, Qt.SmoothTransformation)
        #self.ReferLabel.setPixmap(self.ReferView)

        #self.ListWidget = QListWidget()
        #self.ListWidget.setMinimumWidth(150)
        #self.ListWidget.clicked.connect(self.clickedOutputItem)
        ##To be removed (END)

        #OutputLayout.addWidget(self.DisplayTitle,0,0,1,2)
        #OutputLayout.addWidget(self.DisplayLabel,1,0,1,2)
        #OutputLayout.addWidget(self.ReferTitle,0,2,1,2)
        #OutputLayout.addWidget(self.ReferLabel,1,2,1,2)
        #OutputLayout.addWidget(self.ListWidget,0,4,2,1)

        OutputLayout.addWidget(self.ResultWidget, 0, 0, 1, 1)
        OutputBox.setLayout(OutputLayout)

        #Group Box for history
        self.HistoryBox = QGroupBox("&History")
        HistoryBoxSP = self.HistoryBox.sizePolicy()
        HistoryBoxSP.setVerticalStretch(self.VerticalSegCol1[1])
        self.HistoryBox.setSizePolicy(HistoryBoxSP)

        self.HistoryLayout = QGridLayout()

        # Display the table for module history
        #self.dataList = getLocalRemoteTests(self.connection, self.info[0])
        #self.proxy = QtTableWidget(self.dataList)
        #self.lineEdit       = QLineEdit()
        #self.lineEdit.textChanged.connect(self.proxy.on_lineEdit_textChanged)
        #self.view           = QTableView()
        #self.view.setSortingEnabled(True)
        #self.comboBox       = QComboBox()
        #self.comboBox.addItems(["{0}".format(x) for x in self.dataList[0]])
        #self.comboBox.currentIndexChanged.connect(self.proxy.on_comboBox_currentIndexChanged)
        #self.label          = QLabel()
        #self.label.setText("Regex Filter")

        #self.view.setModel(self.proxy)
        #self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.HistoryLayout = QGridLayout()
        #self.HistoryLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
        #self.HistoryLayout.addWidget(self.view, 1, 0, 1, 3)
        #self.HistoryLayout.addWidget(self.comboBox, 0, 2, 1, 1)
        #self.HistoryLayout.addWidget(self.label, 0, 0, 1, 1)

        #self.StatusCanvas = RunStatusCanvas(parent=self,width=5, height=4, dpi=100)
        self.StatusTable = QTableWidget()
        self.header = ["TestName"]
        for key in self.rd53_file.keys():
            ChipName = key.split("_")
            self.header.append("Module{}_Chip{}".format(
                ChipName[0], ChipName[1]))
        self.StatusTable.setColumnCount(len(self.header))
        self.StatusTable.setHorizontalHeaderLabels(self.header)
        self.StatusTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.HistoryLayout.addWidget(self.StatusTable)
        self.HistoryBox.setLayout(self.HistoryLayout)

        LeftColSplitter.addWidget(ControllerBox)
        LeftColSplitter.addWidget(TerminalBox)
        RightColSplitter.addWidget(OutputBox)
        RightColSplitter.addWidget(self.HistoryBox)

        LeftColSplitterSP = LeftColSplitter.sizePolicy()
        LeftColSplitterSP.setHorizontalStretch(self.HorizontalSeg[0])
        LeftColSplitter.setSizePolicy(LeftColSplitterSP)

        RightColSplitterSP = RightColSplitter.sizePolicy()
        RightColSplitterSP.setHorizontalStretch(self.HorizontalSeg[1])
        RightColSplitter.setSizePolicy(RightColSplitterSP)

        MainSplitter.addWidget(LeftColSplitter)
        MainSplitter.addWidget(RightColSplitter)

        mainbodylayout.addWidget(MainSplitter)
        #mainbodylayout.addWidget(ControllerBox, sum(self.VerticalSegCol0[:0]), sum(self.HorizontalSeg[:0]), self.VerticalSegCol0[0], self.HorizontalSeg[0])
        #mainbodylayout.addWidget(TerminalBox, sum(self.VerticalSegCol0[:1]), sum(self.HorizontalSeg[:0]), self.VerticalSegCol0[1], self.HorizontalSeg[0])
        #mainbodylayout.addWidget(OutputBox, sum(self.VerticalSegCol1[:0]), sum(self.HorizontalSeg[:1]), self.VerticalSegCol1[0], self.HorizontalSeg[1])
        #mainbodylayout.addWidget(HistoryBox, sum(self.VerticalSegCol1[:1]), sum(self.HorizontalSeg[:1]), self.VerticalSegCol1[1], self.HorizontalSeg[1])

        self.MainBodyBox.setLayout(mainbodylayout)
        self.mainLayout.addWidget(self.MainBodyBox, sum(self.GroupBoxSeg[0:1]),
                                  0, self.GroupBoxSeg[1], 1)
Example #8
0
    def __init__(self, name):
        super().__init__()
        self.setWindowTitle(name)
        with open(
                os.path.join(get_jak_path(), "decompiler_out",
                             "{}_asm.json".format(name))) as f:
            self.asm_data = json.loads(f.read())

        main_layout = QVBoxLayout()
        monospaced_font = get_monospaced_font()
        self.header_label = QLabel()

        main_layout.addWidget(self.header_label)

        function_splitter = QSplitter()
        function_splitter.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.function_list = QTreeView()
        self.function_list_model = QStandardItemModel()
        self.functions_by_name = dict()
        root = self.function_list_model.invisibleRootItem()
        seg_roots = []

        for i in range(3):
            seg_entry = QStandardItem(segment_id_to_name(i))
            seg_entry.setFont(monospaced_font)
            seg_entry.setEditable(False)
            root.appendRow(seg_entry)
            seg_roots.append(seg_entry)

        for f in self.asm_data["functions"]:
            function_entry = QStandardItem(f["name"])
            function_entry.setFont(monospaced_font)
            function_entry.setEditable(False)
            seg_roots[f["segment"]].appendRow(function_entry)
            self.functions_by_name[f["name"]] = f

        self.header_label.setText(
            "Object File {} Functions ({} total):".format(
                name, len(self.asm_data["functions"])))

        self.function_list.setModel(self.function_list_model)
        self.function_list.clicked.connect(self.display_function)
        function_splitter.addWidget(self.function_list)

        layout = QVBoxLayout()

        self.function_header_label = QLabel("No function selected")
        self.function_header_label.setFont(monospaced_font)
        self.header_label.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        layout.addWidget(self.function_header_label)

        self.op_asm_split_view = QSplitter()
        self.op_asm_split_view.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.basic_op_pane = QListView()
        self.basic_op_pane.clicked.connect(self.basic_op_clicked)
        #layout.addWidget(self.basic_op_pane)
        self.op_asm_split_view.addWidget(self.basic_op_pane)

        self.asm_pane = QListView()
        self.op_asm_split_view.addWidget(self.asm_pane)

        layout.addWidget(self.op_asm_split_view)

        self.asm_display = QPlainTextEdit()
        self.asm_display.setMaximumHeight(80)
        layout.addWidget(self.asm_display)

        self.warnings_label = QLabel()
        layout.addWidget(self.warnings_label)

        widget = QWidget()
        widget.setLayout(layout)
        function_splitter.addWidget(widget)
        main_layout.addWidget(function_splitter)

        # add it to the window!
        self.setLayout(main_layout)
Example #9
0
class ObjectFileView(QDialog):
    def __init__(self, name):
        super().__init__()
        self.setWindowTitle(name)
        with open(
                os.path.join(get_jak_path(), "decompiler_out",
                             "{}_asm.json".format(name))) as f:
            self.asm_data = json.loads(f.read())

        main_layout = QVBoxLayout()
        monospaced_font = get_monospaced_font()
        self.header_label = QLabel()

        main_layout.addWidget(self.header_label)

        function_splitter = QSplitter()
        function_splitter.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.function_list = QTreeView()
        self.function_list_model = QStandardItemModel()
        self.functions_by_name = dict()
        root = self.function_list_model.invisibleRootItem()
        seg_roots = []

        for i in range(3):
            seg_entry = QStandardItem(segment_id_to_name(i))
            seg_entry.setFont(monospaced_font)
            seg_entry.setEditable(False)
            root.appendRow(seg_entry)
            seg_roots.append(seg_entry)

        for f in self.asm_data["functions"]:
            function_entry = QStandardItem(f["name"])
            function_entry.setFont(monospaced_font)
            function_entry.setEditable(False)
            seg_roots[f["segment"]].appendRow(function_entry)
            self.functions_by_name[f["name"]] = f

        self.header_label.setText(
            "Object File {} Functions ({} total):".format(
                name, len(self.asm_data["functions"])))

        self.function_list.setModel(self.function_list_model)
        self.function_list.clicked.connect(self.display_function)
        function_splitter.addWidget(self.function_list)

        layout = QVBoxLayout()

        self.function_header_label = QLabel("No function selected")
        self.function_header_label.setFont(monospaced_font)
        self.header_label.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        layout.addWidget(self.function_header_label)

        self.op_asm_split_view = QSplitter()
        self.op_asm_split_view.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.basic_op_pane = QListView()
        self.basic_op_pane.clicked.connect(self.basic_op_clicked)
        #layout.addWidget(self.basic_op_pane)
        self.op_asm_split_view.addWidget(self.basic_op_pane)

        self.asm_pane = QListView()
        self.op_asm_split_view.addWidget(self.asm_pane)

        layout.addWidget(self.op_asm_split_view)

        self.asm_display = QPlainTextEdit()
        self.asm_display.setMaximumHeight(80)
        layout.addWidget(self.asm_display)

        self.warnings_label = QLabel()
        layout.addWidget(self.warnings_label)

        widget = QWidget()
        widget.setLayout(layout)
        function_splitter.addWidget(widget)
        main_layout.addWidget(function_splitter)

        # add it to the window!
        self.setLayout(main_layout)

    def display_function(self, item):
        name = item.data()
        monospaced_font = get_monospaced_font()
        func = self.functions_by_name[name]
        basic_op_model = QStandardItemModel()
        basic_op_root = basic_op_model.invisibleRootItem()
        asm_model = QStandardItemModel()
        asm_root = asm_model.invisibleRootItem()

        self.basic_id_to_asm = []
        self.current_function = name
        op_idx = 0
        basic_idx = 0
        for op in func["asm"]:
            if "label" in op:
                asm_item = QStandardItem(op["label"] + "\n    " + op["asm_op"])
            else:
                asm_item = QStandardItem("    " + op["asm_op"])
            asm_item.setFont(monospaced_font)
            asm_item.setEditable(False)
            asm_root.appendRow(asm_item)

            if "basic_op" in op:
                if "label" in op:
                    basic_item = QStandardItem(op["label"] + "\n    " +
                                               op["basic_op"])
                else:
                    basic_item = QStandardItem("    " + op["basic_op"])
                basic_item.setFont(monospaced_font)
                basic_item.setEditable(False)
                basic_op_root.appendRow(basic_item)
                self.basic_id_to_asm.append(op_idx)
                basic_idx = basic_idx + 1
            op_idx = op_idx + 1
        self.basic_id_to_asm.append(op_idx)
        self.basic_op_pane.setModel(basic_op_model)
        self.asm_pane.setModel(asm_model)
        self.warnings_label.setText(func["warnings"])
        self.asm_display.setPlainText("")
        self.function_header_label.setText(
            "{}, type: {}\nfunc: {} obj: {}".format(name, func["type"],
                                                    func["name"],
                                                    func["parent_object"]))

    def basic_op_clicked(self, item):
        text = ""
        added_reg = 0
        asm_idx = self.basic_id_to_asm[item.row()]

        asm_op = self.functions_by_name[self.current_function]["asm"][asm_idx]
        if "type_map" in asm_op:
            for reg, type_name in asm_op["type_map"].items():
                text += "{}: {} ".format(reg, type_name)
                added_reg += 1
                if added_reg >= 4:
                    text += "\n"
                    added_reg = 0
            text += "\n"

        for i in range(asm_idx, self.basic_id_to_asm[item.row() + 1]):
            text += self.functions_by_name[
                self.current_function]["asm"][i]["asm_op"] + "\n"
        op = self.functions_by_name[self.current_function]["asm"][asm_idx]
        if "referenced_string" in op:
            text += op["referenced_string"]
        self.asm_display.setPlainText(text)
        self.asm_display.setFont(get_monospaced_font())
        self.asm_pane.setCurrentIndex(self.asm_pane.model().index(asm_idx, 0))
Example #10
0
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        #uic.loadUi('gui_template.ui',self)

        try:
            self.path_home = os.path.expanduser("~\\Desktop\\")
        except Exception:
            self.path_home = ""

        for curren_dir in ["interim_image"]:
            if os.path.exists(curren_dir):
                if os.path.isdir(curren_dir):
                    print(curren_dir + " is here")
                else:
                    try:
                        os.mkdir(curren_dir)
                    except OSError:
                        print("Error generate dir " + curren_dir)
            else:
                try:
                    os.mkdir(curren_dir)
                except OSError:
                    print("Error generate dir " + curren_dir)

        # Load last path for files
        try:
            with open('last_path.json', "r") as f:
                path_dict = {i: j for i, j in json.load(f).items()}
            self.path_image = path_dict["path_image"]
            self.path_dir_images = path_dict["path_dir_images"]
            self.path_dir_dirs = path_dict["path_dir_dirs"]
            self.path_excel = path_dict["path_excel"]
            self.path_excels = path_dict["path_excels"]
            self.path_vez_excel = path_dict["path_vez_excel"]
            self.path_ro_excel = path_dict["path_ro_excel"]
            self.path_ro_word = path_dict["path_ro_word"]
        except Exception:
            self.path_image = self.path_home
            self.path_dir_images = self.path_home
            self.path_dir_dirs = self.path_home
            self.path_excel = self.path_home
            self.path_excels = self.path_home
            self.path_vez_excel = self.path_home
            self.path_ro_excel = self.path_home
            self.path_ro_word = self.path_home

        self.lv_c = 5
        self.t_c = 0.5
        self.imnam = "слои"

        desktop = QApplication.desktop()
        wd = desktop.width()
        hg = desktop.height()
        ww = 1000
        wh = 500
        if ww > wd: ww = int(0.7 * wd)
        if wh > hg: wh = int(0.7 * hg)
        x = (wd - ww) // 2
        y = (hg - wh) // 2
        self.setGeometry(x, y, ww, wh)

        topVBoxLayout = QVBoxLayout(self)
        topVBoxLayout.setContentsMargins(0, 0, 0, 0)

        SPFrame = QFrame()
        SPFrame.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        SPFrame.setMinimumSize(QSize(150, 100))

        self.ImFrame = QFrame()
        self.ImFrame.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        #self.ImFrame.setMinimumSize(QSize(300, 100))

        TbFrame = QFrame()
        TbFrame.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        TbFrame.setMinimumSize(QSize(0, 100))

        RFrame = QFrame()
        RFrame.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        RFrame.setMinimumSize(QSize(0, 100))

        self.listView = CustomList()  #QListView()
        self.listView.clicked.connect(self.OpenPict)
        self.select_able = True
        self.listView.setcloseEditorSignal(self.Rename)
        #self.listView.editingFinished.connect(self.Rename)
        #self.listView.edit.connect(self.Rename)

        BoxLayout1 = QVBoxLayout()
        self.progress_bar = QProgressBar()
        self.progress_bar.setAlignment(Qt.AlignHCenter)
        BoxLayout1.addWidget(self.progress_bar)
        BoxLayout1.addWidget(self.listView)

        SPFrame.setLayout(BoxLayout1)

        self.Table = CustomTable()  #QTableWidget()
        self.Table.setcloseEditorSignal(
            lambda: self.WriteTable(who_edited="table"))
        #self.Table.itemChanged(lambda:print("change2"))
        self.Table.cellClicked[int, int].connect(self.PosChangedCell)
        self.Table.setColumnCount(3)
        self.Table.setHorizontalHeaderLabels(["p", "h", "d"])
        self.Table.setRowCount(30)
        self.Table.setColumnWidth(0, 50)
        self.Table.setColumnWidth(1, 50)
        self.Table.setColumnWidth(2, 50)
        self.Table.setItemDelegate(DownloadDelegate(self))
        BoxLayout2 = QHBoxLayout()
        BoxLayout2.addWidget(self.Table)
        TbFrame.setLayout(BoxLayout2)

        self.pe1 = QLabel("Рэ1=")
        self.pe2 = QLabel("Рэ2=")
        self.pe = QLabel("Рэ=")
        lb1 = QLabel("Длинна вертикального")
        lb2 = QLabel("заземлителя lв, м")
        lb3 = QLabel("Глубина заложения")
        lb4 = QLabel("вертикального заземлителя t, м")
        lb5 = QLabel("Эквивалентное сопротивление")
        lb6 = QLabel("Двухслойная модель")
        lb7 = QLabel("Однослойная модель")
        lb8 = QLabel("Шаблон искомого изображения")
        lb9 = QLabel("Название проекта")
        lb10 = QLabel("Название ВЛ")
        self.vl = QDoubleSpinBox()
        self.vl.setValue(self.lv_c)
        self.vl.valueChanged.connect(self.WriteTable)
        self.t = QDoubleSpinBox()
        self.t.setValue(self.t_c)
        self.t.valueChanged.connect(self.WriteTable)
        self.pe1_le = QLineEdit()
        self.pe2_le = QLineEdit()
        self.pe_le = QLineEdit()
        self.ImageName = QLineEdit()
        self.ImageName.setText(self.imnam)
        self.NPrj = QLineEdit()
        self.NVL = QLineEdit()
        self.ImageName.editingFinished.connect(self.ReadImName)
        spacerItem = QSpacerItem(2, 20, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        BoxLayout3 = QVBoxLayout()
        BoxLayout4 = QHBoxLayout()
        BoxLayout5 = QHBoxLayout()
        BoxLayout6 = QHBoxLayout()
        BoxLayout3.addWidget(lb8)
        BoxLayout3.addWidget(self.ImageName)
        BoxLayout3.addWidget(lb9)
        BoxLayout3.addWidget(self.NPrj)
        BoxLayout3.addWidget(lb10)
        BoxLayout3.addWidget(self.NVL)
        BoxLayout3.addWidget(lb1)
        BoxLayout3.addWidget(lb2)
        BoxLayout3.addWidget(self.vl)
        BoxLayout3.addWidget(lb3)
        BoxLayout3.addWidget(lb4)
        BoxLayout3.addWidget(self.t)
        BoxLayout3.addWidget(lb5)
        BoxLayout3.addWidget(lb6)
        BoxLayout4.addWidget(self.pe1)
        BoxLayout4.addWidget(self.pe1_le)
        BoxLayout3.addLayout(BoxLayout4)
        BoxLayout5.addWidget(self.pe2)
        BoxLayout5.addWidget(self.pe2_le)
        BoxLayout3.addLayout(BoxLayout5)
        BoxLayout3.addWidget(lb7)
        BoxLayout6.addWidget(self.pe)
        BoxLayout6.addWidget(self.pe_le)
        BoxLayout3.addLayout(BoxLayout6)
        BoxLayout3.addItem(spacerItem)
        RFrame.setLayout(BoxLayout3)

        Splitter1 = QSplitter(Qt.Horizontal)
        Splitter1.addWidget(SPFrame)
        Splitter1.addWidget(self.ImFrame)
        Splitter1.addWidget(TbFrame)
        Splitter1.addWidget(RFrame)
        Splitter1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        Splitter1.setStretchFactor(1, 4)
        Splitter1.setStretchFactor(1, 1)

        topVBoxLayout.addWidget(Splitter1)

        self.central_widget = QWidget()
        self.central_widget.setLayout(topVBoxLayout)
        self.setCentralWidget(self.central_widget)

        #self.resize()
        #self.central_widget.show()
        self.PaintForm = MyFrame(False, parent=self.ImFrame)

        self.statusBar()
        menubar = self.menuBar()

        exitAction = QAction('&Выход', self)  #QIcon('exit.png'),
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Выход и программы')
        exitAction.triggered.connect(lambda: self.closeEvent(QCloseEvent()))

        Open0Action = QAction('&Открыть изображение',
                              self)  #QIcon('exit.png'),
        Open0Action.setShortcut('Ctrl+1')
        Open0Action.setStatusTip(
            'Результаты ВЭЗ предоставлены одиночными изображениями')
        Open0Action.triggered.connect(self.Op0)

        Open1Action = QAction('&Открыть папку изображений',
                              self)  #QIcon('exit.png'),
        Open1Action.setShortcut('Ctrl+2')
        Open1Action.setStatusTip(
            'Результаты ВЭЗ предоставлены одиночными изображениями')
        Open1Action.triggered.connect(lambda: self.Op12(0))

        Open2Action = QAction('&Открыть папку каталогов',
                              self)  #QIcon('exit.png'),
        Open2Action.setShortcut('Ctrl+3')
        Open2Action.setStatusTip('Результаты ВЭЗ предоставлены набором файлов')
        Open2Action.triggered.connect(lambda: self.Op12(1))

        Open3Action = QAction('&Открыть файл Ecxel', self)  #QIcon('exit.png'),
        Open3Action.setShortcut('Ctrl+4')
        Open3Action.setStatusTip('Результаты ВЭЗ файле Ecxel')
        Open3Action.triggered.connect(self.Op3)

        Open4Action = QAction('&Открыть файлы Ecxel',
                              self)  #QIcon('exit.png'),
        Open4Action.setShortcut('Ctrl+5')
        Open4Action.setStatusTip('Результаты ВЭЗ в нескольких файлах Ecxel')
        Open4Action.triggered.connect(self.Op4)

        NewPick = QAction("Добавить точку", self)
        NewPick.setShortcut('Ctrl+A')
        NewPick.setStatusTip('Добавить новую точку')
        NewPick.triggered.connect(self.NewPick)

        DelPick = QAction("Удалить точку", self)
        DelPick.setShortcut('Ctrl+D')
        DelPick.setStatusTip('Удалить точку из списка')
        DelPick.triggered.connect(self.DelPick)

        ReRead = QAction("Прочитать изображение", self)
        ReRead.setShortcut('Ctrl+R')
        ReRead.setStatusTip('Принудительно считывает информацию с изображения')
        ReRead.triggered.connect(self.ReReadImage)

        Select = QAction("Выбрать все точки", self)
        Select.setShortcut('Ctrl+W')
        Select.setStatusTip('Выбираем все точки из списка')
        Select.triggered.connect(self.select)

        ClearTable = QAction("Очистить таблицу", self)
        ClearTable.setShortcut('Ctrl+Shift+D')
        ClearTable.setStatusTip('Очищает текущую таблицу')
        ClearTable.triggered.connect(self.ClearTable)

        SetLvCheck = QAction("Установить lв выбранным точкам", self)
        SetLvCheck.setShortcut('Ctrl+E')
        SetLvCheck.setStatusTip('Изменяет lв выбраных точек на текущее')
        SetLvCheck.triggered.connect(self.SetLvCheck)

        SetTCheck = QAction("Установить t выбранным точкам", self)
        SetTCheck.setShortcut('Ctrl+T')
        SetTCheck.setStatusTip('Изменяет t выбраных точек на текущее')
        SetTCheck.triggered.connect(self.SetTCheck)

        Save1VEZExcel = QAction("Сохранить ВЭЗ в Excel", self)
        Save1VEZExcel.setShortcut('Ctrl+6')
        Save1VEZExcel.setStatusTip('Сохраняет выбраные ВЭЗ в Excel файл')
        Save1VEZExcel.triggered.connect(lambda: self.Save1VEZExcel(1))

        Save2VEZExcel = QAction("Сохранить Pэ в Excel", self)
        Save2VEZExcel.setShortcut('Ctrl+7')
        Save2VEZExcel.setStatusTip('Сохраняет выбраные Рэ в Excel файл')
        Save2VEZExcel.triggered.connect(lambda: self.Save1VEZExcel(2))

        Save3VEZExcel = QAction("Сохранить Pэ в Word", self)
        Save3VEZExcel.setShortcut('Ctrl+8')
        Save3VEZExcel.setStatusTip('Сохраняет выбраные Рэ в Word файл')
        Save3VEZExcel.triggered.connect(lambda: self.Save1VEZExcel(3))

        EditWord = QAction("Редактировать шаблон Word", self)
        EditWord.setShortcut('Ctrl+G')
        EditWord.setStatusTip('Запускает окно для редактирования шаблона Word')
        EditWord.triggered.connect(self.EditWord)

        zoomIn = QAction("Увеличить изображение", self)
        zoomIn.setShortcut('Ctrl++')
        zoomIn.setStatusTip('Увеличивает открытое изображение')
        zoomIn.triggered.connect(self.PaintForm.zoomIn)

        zoomOut = QAction("Уменьшить изображение", self)
        zoomOut.setShortcut('Ctrl+-')
        zoomOut.setStatusTip('Уменьшает открытое изображение')
        zoomOut.triggered.connect(self.PaintForm.zoomOut)

        Rotate1 = QAction("Повернуть изображение по ч.с", self)
        Rotate1.setShortcut('Ctrl+Shift++')
        Rotate1.setStatusTip('Поворачивает изображение по часовой стрелке')
        Rotate1.triggered.connect(lambda: self.PaintForm.Rotate(1))

        Rotate2 = QAction("Повернуть изображение против ч.с", self)
        Rotate2.setShortcut('Ctrl+Shift+-')
        Rotate2.setStatusTip(
            'Поворачивает изображение ппротив часовой стрелке')
        Rotate2.triggered.connect(lambda: self.PaintForm.Rotate(-1))

        NormalSize = QAction("Вернуть исходный размер", self)
        NormalSize.setShortcut('Ctrl+F')
        NormalSize.setStatusTip('Вернуть исходный размер изображения')
        NormalSize.triggered.connect(self.PaintForm.normalSize)

        fileMenu = menubar.addMenu('&Файл')
        fileMenu.addAction(Open0Action)
        fileMenu.addAction(Open1Action)
        fileMenu.addAction(Open2Action)
        fileMenu.addAction(Open3Action)
        fileMenu.addAction(Open4Action)
        fileMenu.addAction(exitAction)

        editMenu = menubar.addMenu('&Правка')
        editMenu.addAction(NewPick)
        editMenu.addAction(DelPick)
        editMenu.addAction(ReRead)
        editMenu.addAction(Select)
        editMenu.addAction(SetLvCheck)
        editMenu.addAction(SetTCheck)
        editMenu.addAction(ClearTable)

        imageMenu = menubar.addMenu('&Изображение')
        imageMenu.addAction(zoomIn)
        imageMenu.addAction(zoomOut)
        imageMenu.addAction(Rotate1)
        imageMenu.addAction(Rotate2)
        imageMenu.addAction(NormalSize)

        reportMenu = menubar.addMenu('&Отчёт')
        reportMenu.addAction(Save1VEZExcel)
        reportMenu.addAction(Save2VEZExcel)
        reportMenu.addAction(Save3VEZExcel)
        reportMenu.addAction(EditWord)

        self.setWindowTitle('VEZRead')
        self.setWindowIcon(QIcon('images\\op1.png'))

        self.d = {}
        self.sp_m = []
        self.file_path = []
        self.file_name = []
        self.arr = []
        self.stst = []
        self.arr_lv = []
        self.arr_t = []
        self.adres = None
        self.ski = QStandardItemModel()
        self.listView.setModel(self.ski)
        self.listView.pressed.connect(self.presseditem)

        self.sel = True
        self.block = True
        self.back_colors = ((255, 255, 255, 255), (255, 0, 0, 50),
                            (255, 255, 0, 50), (0, 255, 0, 50))

        self.pos_changed_cell = (0, 0)
Example #11
0
    def create_top_group_box(self):
        top_splitter = QSplitter()
        top_splitter.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        # 좌
        top_left_group_box = QGroupBox("레이드 함수 목록")
        top_left_group_box.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)

        names = list(map(lambda i: i.get_name(), self._methods))
        model = QStringListModel(names)
        view = QListView()
        view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        view.setModel(model)
        view.clicked.connect(self.on_show_method)

        add_function = QPushButton("함수 추가")

        layout = QVBoxLayout()
        layout.addWidget(add_function)
        layout.addWidget(view)

        top_left_group_box.setLayout(layout)

        # 우
        top_right_group_box = QGroupBox("레이드 함수")

        # 우 - 텍스트
        tab_method_body = QTabWidget()

        tab_block = QWidget()

        tab_plain = QWidget()
        self._edit_method_body_plain = QTextEdit()
        tab_hbox_plain = QHBoxLayout()
        tab_hbox_plain.setContentsMargins(5, 5, 5, 5)
        tab_hbox_plain.addWidget(self._edit_method_body_plain)

        self._edit_method_body_block = PyJavaCode()
        self._edit_method_body_block.set_plain_view(
            self._edit_method_body_plain)
        tab_hbox_block = QHBoxLayout()
        tab_hbox_block.setContentsMargins(5, 5, 5, 5)
        tab_hbox_block.addWidget(self._edit_method_body_block)

        tab_block.setLayout(tab_hbox_block)
        tab_plain.setLayout(tab_hbox_plain)

        tab_method_body.addTab(tab_block, "&Block")
        tab_method_body.addTab(tab_plain, "&Plain")

        # 배치
        label_method_name = QLabel("name")
        self._edit_method_name = QLineEdit()
        label_method_body = QLabel("body")
        self._edit_method_body = tab_method_body

        #
        layout = QVBoxLayout()
        layout.addWidget(label_method_name)
        layout.addWidget(self._edit_method_name)
        layout.addWidget(label_method_body)
        layout.addWidget(self._edit_method_body)

        top_right_group_box.setLayout(layout)

        # test
        # top_left_group_box.setStyleSheet("color: blue;"
        #                       "background-color: #87CEFA;"
        #                       "border-style: dashed;"
        #                       "border-width: 3px;"
        #                       "border-color: #1E90FF")
        #
        # top_right_group_box.setStyleSheet("color: blue;"
        #                       "background-color: #87CEFA;"
        #                       "border-style: dashed;"
        #                       "border-width: 3px;"
        #                       "border-color: #1E90FF")

        # spliter
        top_splitter.addWidget(top_left_group_box)
        top_splitter.addWidget(top_right_group_box)

        return top_splitter
Example #12
0
class NavigationBar(QWidget):
    """
    Class implementing the navigation bar.
    """
    def __init__(self, mainWindow, parent=None):
        """
        Constructor
        
        @param mainWindow reference to the browser main window
        @type WebBrowserWindow
        @param parent reference to the parent widget
        @type QWidget
        """
        super(NavigationBar, self).__init__(parent)
        self.setObjectName("navigationbar")

        self.__mw = mainWindow

        self.__layout = QHBoxLayout(self)
        margin = self.style().pixelMetric(QStyle.PM_ToolBarItemMargin, None,
                                          self)
        self.__layout.setContentsMargins(margin, margin, margin, margin)
        self.__layout.setSpacing(self.style().pixelMetric(
            QStyle.PM_ToolBarItemSpacing, None, self))
        self.setLayout(self.__layout)

        self.__backButton = E5ToolButton(self)
        self.__backButton.setObjectName("navigation_back_button")
        self.__backButton.setToolTip(self.tr("Move one screen backward"))
        self.__backButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.__backButton.setFocusPolicy(Qt.NoFocus)
        self.__backButton.setAutoRaise(True)
        self.__backButton.setIcon(UI.PixmapCache.getIcon("back.png"))
        self.__backButton.setEnabled(False)

        self.__forwardButton = E5ToolButton(self)
        self.__forwardButton.setObjectName("navigation_forward_button")
        self.__forwardButton.setToolTip(self.tr("Move one screen forward"))
        self.__forwardButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.__forwardButton.setFocusPolicy(Qt.NoFocus)
        self.__forwardButton.setAutoRaise(True)
        self.__forwardButton.setIcon(UI.PixmapCache.getIcon("forward.png"))
        self.__forwardButton.setEnabled(False)

        self.__backNextLayout = QHBoxLayout()
        self.__backNextLayout.setContentsMargins(0, 0, 0, 0)
        self.__backNextLayout.setSpacing(0)
        self.__backNextLayout.addWidget(self.__backButton)
        self.__backNextLayout.addWidget(self.__forwardButton)

        self.__reloadStopButton = ReloadStopButton(self)

        self.__homeButton = E5ToolButton(self)
        self.__homeButton.setObjectName("navigation_home_button")
        self.__homeButton.setToolTip(self.tr("Move to the initial screen"))
        self.__homeButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.__homeButton.setFocusPolicy(Qt.NoFocus)
        self.__homeButton.setAutoRaise(True)
        self.__homeButton.setIcon(UI.PixmapCache.getIcon("home.png"))

        self.__exitFullScreenButton = E5ToolButton(self)
        self.__exitFullScreenButton.setObjectName(
            "navigation_exitfullscreen_button")
        self.__exitFullScreenButton.setIcon(
            UI.PixmapCache.getIcon("windowRestore.png"))
        self.__exitFullScreenButton.setToolTip(self.tr("Exit Fullscreen"))
        self.__exitFullScreenButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.__exitFullScreenButton.setFocusPolicy(Qt.NoFocus)
        self.__exitFullScreenButton.setAutoRaise(True)
        self.__exitFullScreenButton.clicked.connect(self.__mw.toggleFullScreen)
        self.__exitFullScreenButton.setVisible(False)

        self.__downloadManagerButton = DownloadManagerButton(self)

        self.__superMenuButton = E5ToolButton(self)
        self.__superMenuButton.setObjectName("navigation_supermenu_button")
        self.__superMenuButton.setIcon(UI.PixmapCache.getIcon("superMenu.png"))
        self.__superMenuButton.setToolTip(self.tr("Main Menu"))
        self.__superMenuButton.setPopupMode(QToolButton.InstantPopup)
        self.__superMenuButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.__superMenuButton.setFocusPolicy(Qt.NoFocus)
        self.__superMenuButton.setAutoRaise(True)
        self.__superMenuButton.setShowMenuInside(True)

        self.__navigationSplitter = QSplitter(self)
        urlBar = self.__mw.tabWidget().stackedUrlBar()
        self.__navigationSplitter.addWidget(urlBar)

        from WebBrowser.WebBrowserWebSearchWidget import (
            WebBrowserWebSearchWidget)
        self.__searchEdit = WebBrowserWebSearchWidget(self.__mw, self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(2)
        sizePolicy.setVerticalStretch(0)
        self.__searchEdit.setSizePolicy(sizePolicy)
        self.__searchEdit.search.connect(self.__mw.openUrl)
        self.__navigationSplitter.addWidget(self.__searchEdit)

        self.__navigationSplitter.setSizePolicy(QSizePolicy.Expanding,
                                                QSizePolicy.Maximum)
        self.__navigationSplitter.setCollapsible(0, False)

        self.__layout.addLayout(self.__backNextLayout)
        self.__layout.addWidget(self.__reloadStopButton)
        self.__layout.addWidget(self.__homeButton)
        self.__layout.addWidget(self.__navigationSplitter)
        self.__layout.addWidget(self.__downloadManagerButton)
        self.__layout.addWidget(self.__exitFullScreenButton)
        self.__layout.addWidget(self.__superMenuButton)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.__contextMenuRequested)

        self.__backMenu = QMenu(self)
        self.__backMenu.triggered.connect(self.__navigationMenuActionTriggered)
        self.__backButton.setMenu(self.__backMenu)
        self.__backButton.aboutToShowMenu.connect(self.__showBackMenu)

        self.__forwardMenu = QMenu(self)
        self.__forwardMenu.triggered.connect(
            self.__navigationMenuActionTriggered)
        self.__forwardButton.setMenu(self.__forwardMenu)
        self.__forwardButton.aboutToShowMenu.connect(self.__showForwardMenu)

        self.__backButton.clicked.connect(self.__goBack)
        self.__backButton.middleClicked.connect(self.__goBackInNewTab)
        self.__backButton.controlClicked.connect(self.__goBackInNewTab)
        self.__forwardButton.clicked.connect(self.__goForward)
        self.__forwardButton.middleClicked.connect(self.__goForwardInNewTab)
        self.__forwardButton.controlClicked.connect(self.__goForwardInNewTab)
        self.__reloadStopButton.reloadClicked.connect(self.__reload)
        self.__reloadStopButton.stopClicked.connect(self.__stopLoad)
        self.__homeButton.clicked.connect(self.__goHome)
        self.__homeButton.middleClicked.connect(self.__goHomeInNewTab)
        self.__homeButton.controlClicked.connect(self.__goHomeInNewTab)

    def superMenuButton(self):
        """
        Public method to get a reference to the super menu button.
        
        @return reference to the super menu button
        @rtype QToolButton
        """
        return self.__superMenuButton

    def backButton(self):
        """
        Public method to get a reference to the back button.
        
        @return reference to the back button
        @rtype QToolButton
        """
        return self.__backButton

    def forwardButton(self):
        """
        Public method to get a reference to the forward button.
        
        @return reference to the forward button
        @rtype QToolButton
        """
        return self.__forwardButton

    def reloadStopButton(self):
        """
        Public method to get a reference to the reload/stop button.
        
        @return reference to the reload/stop button
        @rtype QToolButton
        """
        return self.__reloadStopButton

    def exitFullScreenButton(self):
        """
        Public method to get a reference to the exit full screen button.
        
        @return reference to the exit full screen button
        @rtype QToolButton
        """
        return self.__exitFullScreenButton

    def searchEdit(self):
        """
        Public method to get a reference to the web search edit.
        
        @return reference to the web search edit
        @rtype WebBrowserWebSearchWidget
        """
        return self.__searchEdit

    def __showBackMenu(self):
        """
        Private slot showing the backwards navigation menu.
        """
        self.__backMenu.clear()
        history = self.__mw.currentBrowser().history()
        historyCount = history.count()
        backItems = history.backItems(historyCount)

        count = 0
        for index in range(len(backItems) - 1, -1, -1):
            item = backItems[index]
            act = QAction(self)
            act.setData(-1 * (index + 1))
            icon = WebBrowserWindow.icon(item.url())
            act.setIcon(icon)
            act.setText(item.title())
            self.__backMenu.addAction(act)

            count += 1
            if count == 20:
                break

        self.__backMenu.addSeparator()
        self.__backMenu.addAction(self.tr("Clear History"),
                                  self.__clearHistory)

    def __showForwardMenu(self):
        """
        Private slot showing the forwards navigation menu.
        """
        self.__forwardMenu.clear()
        history = self.__mw.currentBrowser().history()
        historyCount = history.count()
        forwardItems = history.forwardItems(historyCount)

        count = 0
        for index in range(len(forwardItems)):
            item = forwardItems[index]
            act = QAction(self)
            act.setData(index + 1)
            icon = WebBrowserWindow.icon(item.url())
            act.setIcon(icon)
            act.setText(item.title())
            self.__forwardMenu.addAction(act)

            count += 1
            if count == 20:
                break

        self.__forwardMenu.addSeparator()
        self.__forwardMenu.addAction(self.tr("Clear History"),
                                     self.__clearHistory)

    def __navigationMenuActionTriggered(self, act):
        """
        Private slot to go to the selected page.
        
        @param act reference to the action selected in the navigation menu
            (QAction)
        """
        offset = act.data()
        if offset is not None:
            history = self.__mw.currentBrowser().history()
            historyCount = history.count()
            if offset < 0:
                # go back
                history.goToItem(
                    history.backItems(historyCount)[-1 * offset - 1])
            else:
                # go forward
                history.goToItem(
                    history.forwardItems(historyCount)[offset - 1])

    def __goBack(self):
        """
        Private slot called to handle the backward button.
        """
        self.__mw.currentBrowser().backward()

    def __goBackInNewTab(self):
        """
        Private slot handling a middle click or Ctrl left click of the
        backward button.
        """
        history = self.__mw.currentBrowser().history()
        if history.canGoBack():
            backItem = history.backItem()
            self.__mw.newTab(link=backItem.url(),
                             addNextTo=self.__mw.currentBrowser(),
                             background=True)

    def __goForward(self):
        """
        Private slot called to handle the forward button.
        """
        self.__mw.currentBrowser().forward()

    def __goForwardInNewTab(self):
        """
        Private slot handling a middle click or Ctrl left click of the
        forward button.
        """
        history = self.__mw.currentBrowser().history()
        if history.canGoForward():
            forwardItem = history.forwardItem()
            self.__mw.newTab(link=forwardItem.url(),
                             addNextTo=self.__mw.currentBrowser(),
                             background=True)

    def __goHome(self):
        """
        Private slot called to handle the home button.
        """
        self.__mw.currentBrowser().home()

    def __goHomeInNewTab(self):
        """
        Private slot handling a middle click or Ctrl left click of the
        home button.
        """
        homeUrl = QUrl(Preferences.getWebBrowser("HomePage"))
        self.__mw.newTab(link=homeUrl,
                         addNextTo=self.__mw.currentBrowser(),
                         background=True)

    def __reload(self):
        """
        Private slot called to handle the reload button.
        """
        self.__mw.currentBrowser().reloadBypassingCache()

    def __stopLoad(self):
        """
        Private slot called to handle loading of the current page.
        """
        self.__mw.currentBrowser().stop()

    def __clearHistory(self):
        """
        Private slot to clear the history of the current web browser tab.
        """
        cb = self.__mw.currentBrowser()
        if cb is not None:
            cb.history().clear()
            self.__mw.setForwardAvailable(cb.isForwardAvailable())
            self.__mw.setBackwardAvailable(cb.isBackwardAvailable())

    def __contextMenuRequested(self, pos):
        """
        Private method to handle a context menu request.
        
        @param pos position of the request
        @type QPoint
        """
        menu = self.__mw.createPopupMenu()
        menu.exec_(self.mapToGlobal(pos))