Esempio n. 1
0
    def create_toolbar(self, parent):
        from PyQt5.QtWidgets import QAction, QToolBar, QActionGroup
        from PyQt5.QtGui import QIcon
        from PyQt5.QtCore import Qt, QSize
        tb = QToolBar(self.display_name, parent)
        tb.setStyleSheet('QToolBar{spacing:0px;}\n'
                         'QToolButton{padding:0px; margin:0px; border:none;}')
        s = self._icon_size
        tb.setIconSize(QSize(s, s))
        parent.add_tool_bar(self, Qt.LeftToolBarArea, tb)
        group = QActionGroup(tb)
        for mode in self.modes:
            action = QAction(self._icon(mode.icon_path), mode.name, group)
            action.setCheckable(True)

            def button_press_cb(event, mode=mode):
                mname = mode.name
                if ' ' in mname:
                    mname = '"%s"' % mname
                from chimerax.core.commands import run
                run(self.session,
                    'ui mousemode %s %s' % (self.button_to_bind, mname))

            action.triggered.connect(button_press_cb)
            action.vr_mode = lambda m=mode: m  # To handle virtual reality button clicks.
            group.addAction(action)
        tb.addActions(group.actions())
        tb.show()
        return tb
    def createNavBar(self) -> None:
        navbar = NavBar()
        self.addToolBar(navbar)
        self.addToolBarBreak()

        backButton = Action("Go Back", self)
        backButton.triggered.connect(self.browserEngineView.back)

        forwardButton = Action("Go Forward", self)
        forwardButton.triggered.connect(self.browserEngineView.forward)

        reloadButton = Action("Reload Page", self)
        reloadButton.triggered.connect(self.browserEngineView.reload)

        homeButton = Action("Go to Home", self)
        homeButton.triggered.connect(self.navigateHome)

        networkDetailsButton = Action("Network Details", self)
        networkDetailsButton.triggered.connect(self.fetchNetworkDetails)

        ipConfigButton = Action("IP Config", self)
        ipConfigButton.triggered.connect(self.fetchIpConfig)

        navbar.addActions([
            backButton,
            forwardButton,
            reloadButton,
            homeButton,
            networkDetailsButton,
            ipConfigButton,
        ])
        self.urlBar = LineEdit()
        self.urlBar.returnPressed.connect(self.navigateToUrl)
        navbar.addWidget(self.urlBar)
Esempio n. 3
0
    def init_menu(self):
        load_rom = self.create_action('載入Rom', self.load_rom)
        save_rom = self.create_action('保存Rom', self.save_rom)
        save_rom.setEnabled(False)
        save_as = self.create_action('另存為', self.save_as)
        save_as.setEnabled(False)
        close_child = self.create_action('關閉窗口', self.close_child)
        exit_editor = self.create_action('退出', self.close)
        file_menu = self.create_menu(
            '文件(&F)', None,
            [load_rom, save_rom, save_as, close_child, exit_editor])

        value_editors = [
            self.create_action(editor_name, self.open_editor_frame)
            for editor_name in CHILD_MAPPING
        ]

        edit_menu = self.create_menu('編輯(&E)', None, value_editors)
        edit_menu.setEnabled(False)

        self.menuBar().addMenu(file_menu)
        self.menuBar().addMenu(edit_menu)

        tool_bar = QToolBar('顯示標籤')
        tool_bar.setObjectName('工具')
        tool_bar.addActions(value_editors)
        tool_bar.setEnabled(False)
        tool_bar.setMovable(False)
        tool_bar.setVisible(False)
        self.addToolBar(tool_bar)

        action_group = QActionGroup(self)
        [(action_group.addAction(i), i.setCheckable(True))
         for i in value_editors]
        action_group.setExclusive(True)
Esempio n. 4
0
    def init_menu(self):
        """初始化菜单"""
        # menubar = self.menuBar()
        # menu = menubar.addMenu('开始')

        # new_act = QAction('保存', self)
        # new_act.setShortcut('Ctrl+A')
        # exit_act = QAction('退出', self)
        # exit_act.setShortcut('Ctrl+Q')
        # exit_act.setStatusTip('退出应用')
        # menu.addActions([new_act])

        next_action = QAction('下一步', self)
        next_action.triggered.connect(self.next_)
        next_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_N))

        result_action = QAction('计算', self)
        result_action.triggered.connect(self.result)
        result_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_R))

        exit_action = QAction('退出', self)
        exit_action.triggered.connect(sys.exit)

        toolbar = QToolBar("Main Toolbar")
        toolbar.addActions([next_action, result_action, exit_action])
        self.addToolBar(toolbar)
Esempio n. 5
0
    def __init__(self, textBox):
        super(ImageViewer_2, self).__init__()

        self.textBox = textBox
        sep = QAction(self)
        sep.setSeparator(True)

        projAct = QAction(QIcon('images/icons-403.png'), 'Project', self)
        projAct.setShortcut('Ctrl+j')
        toolAct = QAction(QIcon('images/Tool_Application.png'), 'Tool', self)
        toolAct.setShortcut('Ctrl+t')
        protAct = QAction(QIcon('images/Protocol_record.png'), 'Protocol',
                          self)
        protAct.setShortcut('Ctrl+p')
        creatAct = QAction(QIcon('images/create.png'), 'Create ROI', self)
        creatAct.setShortcut('Ctrl+r')
        openAct = QAction(QIcon('images/open.png'), 'Open ROI', self)
        openAct.setShortcut('Ctrl+o')
        plotAct = QAction(QIcon('images/plot.png'), 'Plotting', self)
        plotAct.setShortcut('Ctrl+g')
        prefAct = QAction(QIcon('images/pref.png'), 'Preferences', self)
        prefAct.setShortcut('Ctrl+h')

        toolbar = QToolBar()
        toolbar.setIconSize(QSize(50, 50))
        toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)

        toolbar.addActions((projAct, sep, toolAct, protAct, creatAct, openAct,
                            plotAct, prefAct))
        toolbar.actionTriggered[QAction].connect(self.btnPressed)

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.addWidget(toolbar)
Esempio n. 6
0
    def __init__(self, window, genotypes, fitness, forces, bridge, fitness_graph=None, threshold_graph=None):
        super().__init__(window)

        self.genotypes = genotypes
        self.fitness = fitness
        self.forces = forces
        self.bridge = bridge
        self.threshold_graph = threshold_graph
        self.fitness_graph = fitness_graph
        self.cached_canvas = [None]*len(genotypes)
        self.current_fig = None
        self.current_toolbar = None
        self.current_canvas = None

        toolbar = QToolBar("Individuals")
        self.addToolBar(Qt.BottomToolBarArea, toolbar)

        self.actiongroup = QActionGroup(self)

        for i in range(len(self.genotypes)):
            action = QAction(QIcon(), str(i+1), self)
            action.setCheckable(True)
            self.actiongroup.addAction(action)

        self.actiongroup.triggered.connect(self.plot_genotype)
        self.boxlayout = QVBoxLayout()

        toolbar.addActions(self.actiongroup.actions())
        self.actiongroup.setExclusive(True)
        self.actiongroup.actions()[0].activate(QAction.Trigger)
Esempio n. 7
0
class MainWindow(QMainWindow):
    """ This is the main window of the Qt application. """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # ---------------------------------------------------------------------
        # Setup Window
        # ---------------------------------------------------------------------
        self.setWindowTitle("Developer Dashboard")
        self.setWindowIcon(QIcon('logo.png'))
        # ---------------------------------------------------------------------
        # Menus/ Widgets
        # ---------------------------------------------------------------------
        # Create an instance of an Actions object. This contains all the QActions
        # to be used in this application.
        self.actions = Actions()

        # Create a MainWidget object. Note the Actions are being passed in.
        self.mainWidget = CentralWidget(self.actions)

        # Set the central widget
        self.setCentralWidget(self.mainWidget)

        # Create an application menu (this will be a sub-menu)
        self.dashboardMenu = QMenu("dashboard")

        # Add actions to the application menu
        self.dashboardMenu.addActions(self.actions.getDashboardActions())

        # Create an options menu
        self.optionsMenu = QMenu("Options")

        # Add the dashboard menu to the options menu
        self.optionsMenu.addMenu(self.dashboardMenu)

        # Add actions to the options menu
        self.optionsMenu.addActions(self.actions.getOptionsActions())

        # Add the options menu to the menu bar
        self.menuBar().addMenu(self.optionsMenu)

        # Create a tool bar
        self.toolBar = QToolBar()

        # Add actions to the tool bar
        self.toolBar.addActions(self.actions.getToolBarActions())

        # Add the tool bar to this MainWindow
        self.addToolBar(self.toolBar)

        # Connect the signals
        self.actions.exitAction.triggered.connect(self.quit)
        self.mainWidget.quitApplication.connect(self.quit)
        self.actions.clearAction.triggered.connect(self.mainWidget.clearForm)
        self.actions.resetAction.triggered.connect(self.mainWidget.resetScores)
        self.actions.aboutAction.triggered.connect(self.mainWidget.aboutInfo)

    def quit(self):
        exit(0)
Esempio n. 8
0
    def init_ui(self):
        self.set_and_center_the_window(1024, 768)
        self.setWindowTitle('Список желаний')
        self.setWindowIcon(QIcon(r'img/star.png'))

        wish_action = QAction(
            QIcon(r'img/star.png'), 'Добавить новое желание', self
        )
        wish_action.triggered.connect(self.add_wish)

        toolbar = QToolBar()
        self.addToolBar(Qt.LeftToolBarArea, toolbar)
        toolbar.addActions(
            [wish_action]
        )
Esempio n. 9
0
 def initToolbar(self, toolbarManager):
     """
     Public slot to initialize the multi project toolbar.
     
     @param toolbarManager reference to a toolbar manager object
         (E5ToolBarManager)
     @return the toolbar generated (QToolBar)
     """
     tb = QToolBar(self.tr("Multiproject"), self.ui)
     tb.setIconSize(UI.Config.ToolBarIconSize)
     tb.setObjectName("MultiProjectToolbar")
     tb.setToolTip(self.tr('Multiproject'))
     
     tb.addActions(self.actGrp1.actions())
     tb.addAction(self.closeAct)
     tb.addSeparator()
     tb.addAction(self.saveAct)
     tb.addAction(self.saveasAct)
     
     toolbarManager.addToolBar(tb, tb.windowTitle())
     toolbarManager.addAction(self.addProjectAct, tb.windowTitle())
     toolbarManager.addAction(self.propsAct, tb.windowTitle())
     
     return tb
Esempio n. 10
0
    def __init__(self):
        super().__init__()

        self.setWindowIcon(QIcon('images/icon.ico'))
        self.screenWidth, self.screenHeight = self.geometry().width(
        ), self.geometry().height()
        self.resize(self.screenWidth, self.screenHeight)

        self.filterTypes = 'All files(*);; Text Document (*.txt);; Python(*.py);; Markdown (*.md) '

        self.path = None

        fixedFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        fixedFont.setPointSize(12)

        mainLayout = QVBoxLayout()

        #editor
        self.editor = QPlainTextEdit()
        self.editor.setFont(fixedFont)
        mainLayout.addWidget(self.editor)

        #status bar
        self.statusBar = self.statusBar()

        #app container
        container = QWidget()
        container.setLayout(mainLayout)
        self.setCentralWidget(container)

        #--------------------------------
        #File Menu
        #--------------------------------
        fileMenu = self.menuBar().addMenu('&File')

        #-----------------------------------
        # File Toolbar
        #-----------------------------------
        fileToolbar = QToolBar('File')
        fileToolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.BottomToolBarArea, fileToolbar)
        ''''open, save, save as'''
        openFileAction = QAction(QIcon('images/open.ico'), 'Open File...',
                                 self)
        openFileAction.setStatusTip('Open File')
        openFileAction.setShortcut(QKeySequence.Open)
        openFileAction.triggered.connect(self.fileOpen)

        saveFileAction = self.createAction(self, 'images/save.ico',
                                           'Save File', 'Save file',
                                           self.fileSave)
        saveFileAction.setShortcut(QKeySequence.Save)

        saveFileAsAction = self.createAction(self, 'images/save_as.ico',
                                             'Save As File', 'Save As file',
                                             self.fileSaveAs)
        saveFileAsAction.setShortcut(QKeySequence('Ctrl+Shift+S'))

        fileMenu.addActions([openFileAction, saveFileAction, saveFileAsAction])
        fileToolbar.addActions(
            [openFileAction, saveFileAction, saveFileAsAction])

        #Print Action(Print Document)
        printAction = self.createAction(self, 'images/print.ico', 'Print File',
                                        'Print File', self.printFile)
        printAction.setShortcut(QKeySequence.Print)

        fileMenu.addAction(printAction)
        fileToolbar.addAction(printAction)

        #--------------------------------
        #Edit Menu
        #--------------------------------
        editMenu = self.menuBar().addMenu('&Edit')

        #--------------------------------
        #Edit Toolbar
        #--------------------------------
        editToolbar = QToolBar()
        editToolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.BottomToolBarArea, editToolbar)
        '''undo redo actions'''
        undoAction = self.createAction(self, 'images/undo.ico', 'Undo', 'Undo',
                                       self.editor.undo)
        undoAction.setShortcut(QKeySequence.Undo)

        redoAction = self.createAction(self, 'images/redo.ico', 'Redo', 'Redo',
                                       self.editor.redo)
        redoAction.setShortcut(QKeySequence.Redo)

        editMenu.addActions([undoAction, redoAction])
        editToolbar.addActions([undoAction, redoAction])

        # Clear action
        clearAction = self.createAction(self, 'images/clean.ico', 'Clear',
                                        'Clear', self.clearContent)
        editMenu.addAction(clearAction)
        editToolbar.addAction(clearAction)

        editMenu.addSeparator()
        editToolbar.addSeparator()

        cutAction = self.createAction(self, 'images/cut.ico', 'Cut', 'Cut',
                                      self.editor.cut)
        copyAction = self.createAction(self, 'images/copy.ico', 'Copy', 'Copy',
                                       self.editor.copy)
        pasteAction = self.createAction(self, 'images/paste.ico', 'Paste',
                                        'Paste', self.editor.paste)
        selectAllAction = self.createAction(self, 'images/cut.ico',
                                            'Select all', 'Select all',
                                            self.editor.selectAll)

        cutAction.setShortcut(QKeySequence.Cut)
        copyAction.setShortcut(QKeySequence.Copy)
        pasteAction.setShortcut(QKeySequence.Paste)
        selectAllAction.setShortcut(QKeySequence.SelectAll)

        editMenu.addActions(
            [cutAction, copyAction, pasteAction, selectAllAction])
        editToolbar.addActions(
            [cutAction, copyAction, pasteAction, selectAllAction])
        editToolbar.addSeparator()

        #Wrap text
        wrapTextAction = self.createAction(self, 'images/cut.ico', 'Wrap text',
                                           'Wrap text', self.toggleWrapText)
        wrapTextAction.setShortcut(QKeySequence('Ctrl+Shift+W'))
        editMenu.addAction(wrapTextAction)
        editToolbar.addAction(wrapTextAction)

        self.updateTitle()
Esempio n. 11
0
class VoiceEditor(QWidget):
    """ This class implements an editor capable to load, edit and save pages.
    """

    # signal emitted when asking to load the next voice
    loadNextVoice = pyqtSignal(name='loadNextVoice')

    def __init__(self, connection, diff):
        """ Object initialization.

        Parameters
        ----------
        self : QWidget
        connection : Connection
            Object managing the connection to the wiki.
        diff : Diff
            Diff widget to be used by this editor.
        """

        super().__init__()

        self.connection = connection
        self.diff = diff
        self.originalContent = ''

        ## ACTIONS

        # save voice
        saveVoiceAction = QAction(
                QIcon('icons/document-save'),
                'Save voice', self)
        saveVoiceAction.setStatusTip('Save the voice content in the wiki')
        saveVoiceAction.triggered.connect(self.savePageContent)
        # save voice and load next one
        saveAndNextAction = QAction(
                QIcon('icons/save-and-next.svg'),
                'Save and next', self)
        saveAndNextAction.setStatusTip('Save the voice and load next one')
        saveAndNextAction.triggered.connect(self.saveAndNextVoice)
        # load next voice discarding changes
        nextVoiceAction = QAction(
                QIcon('icons/arrow-right'),
                'Next', self)
        nextVoiceAction.setStatusTip('Load the next voice discarding changes')
        nextVoiceAction.triggered.connect(self.loadNextVoice.emit)
        # clean editor discarding changes
        clearAction = QAction(
                QIcon('icons/window-close'),
                'Clear', self)
        clearAction.setStatusTip('Clean the editor discarding changes')
        clearAction.triggered.connect(self.clear)
        # show diff
        diffAction = QAction(
                QIcon('icons/sort-presence'),
                'Show changes', self)
        diffAction.setStatusTip('Show changes for the current the edit')
        diffAction.triggered.connect(self.showDiff)

        ## TOOLBARS

        # Actions
        self.actionsToolbar = QToolBar('Actions')
        self.actionsToolbar.addActions([
            diffAction,
            saveVoiceAction,
            saveAndNextAction,
            nextVoiceAction,
            clearAction])
        self.actionsToolbar.setOrientation(Qt.Vertical)

        ## WIDGETS

        self.pageTitle = QLineEdit()
        self.pageTitle.setDisabled(True)
        titleLayout = QHBoxLayout()
        titleLayout.addWidget(QLabel('Title:'))
        titleLayout.addWidget(self.pageTitle)
        titleWidget = QWidget()
        titleWidget.setLayout(titleLayout)

        self.pageContent = QPlainTextEdit()
        self.pageContent.setTabChangesFocus(True)

        summaryLabel = QLabel('Summary:')
        self.summary = QLineEdit()
        summaryHBox = QHBoxLayout()
        summaryHBox.addWidget(summaryLabel)
        summaryHBox.addWidget(self.summary)
        summaryWidget = QWidget()
        summaryWidget.setLayout(summaryHBox)

        self.editToolbar = EditToolbar(self, self.pageContent)

        vbox = QVBoxLayout()
        vbox.addWidget(titleWidget)
        vbox.addWidget(self.editToolbar)
        vbox.addWidget(self.pageContent)
        vbox.addWidget(summaryWidget)

        hbox = QHBoxLayout()
        hbox.addLayout(vbox)
        hbox.addWidget(self.actionsToolbar)

        self.setLayout(hbox)

    def savePageContent(self):
        """ Save the page content making an edit in the wiki.
        """
        # ensure there is an opened voice
        if self.pageTitle.text() == '':
            return

        self.connection.edit(
                self.pageTitle.text(),
                self.pageContent.toPlainText(),
                self.summary.text())

    def saveAndNextVoice(self):
        """ Save the page content and load the next voice in the list.
        """
        # save current voice
        self.savePageContent()
        # ask to load next voice
        self.loadNextVoice.emit()

    def clear(self):
        """ Clear the editor content.
        """
        self.pageContent.setPlainText('')
        self.pageTitle.setText('')
        self.originalContent = ''

    def showDiff(self):
        """ Show the diff between the original text and the current text in
        the editor.
        """

        # ensure there is an opened voice
        if self.pageTitle.text() == '':
            return

        # show diff widget if disabled
        if not self.diff.isVisible():
            self.diff.setVisible(True)

        self.diff.showDiff(self.originalContent, self.pageContent.toPlainText())
Esempio n. 12
0
class TransCodaEditor(QWidget):
    encoder_changed = pyqtSignal('PyQt_PyObject', 'PyQt_PyObject')

    def __init__(self, caption="Trans:Coda Editor"):
        super().__init__()
        self.encoder = EncoderSelector()
        self.encoder_view = EncoderView()
        self.actions = QToolBar()
        self.caption = caption
        self.add_action = CommonUtils.create_action(
            tooltip="Add Encoder",
            icon=TransCoda.theme.ico_add_item,
            func=self.action_add,
            name="Add",
            parent=self)
        self.del_action = CommonUtils.create_action(
            tooltip="Delete Encoder",
            icon=TransCoda.theme.ico_clear,
            func=self.action_del,
            name="Delete",
            parent=self)
        self.mod_action = CommonUtils.create_action(
            tooltip="Edit Encoder",
            icon=TransCoda.theme.ico_edit,
            func=self.action_mod,
            name="Edit",
            parent=self)
        self.ref_action = CommonUtils.create_action(
            tooltip="Refresh Encoder",
            icon=TransCoda.theme.ico_refresh,
            func=self.action_ref,
            name="Refresh",
            parent=self)
        self._init_ui()

    def _init_ui(self):
        self.encoder.encoder_changed.connect(self._configure_toolbar)
        self.actions.setOrientation(Qt.Horizontal)
        self.actions.addActions([
            self.add_action, self.del_action, self.mod_action, self.ref_action
        ])
        self.actions.setContentsMargins(0, 0, 0, 0)
        q_size = QSize(16, 16)
        self.actions.setIconSize(q_size)
        self._configure_toolbar(None, None)

        h_layout = QHBoxLayout()
        h_layout.setContentsMargins(0, 0, 0, 0)
        h_layout.addWidget(QLabel(f"<u>{self.caption}</u>"), 1)
        h_layout.addWidget(self.actions)
        v_layout = QVBoxLayout()
        v_layout.setContentsMargins(0, 0, 0, 0)
        v_layout.addLayout(h_layout)
        v_layout.addWidget(self.encoder)
        self.setMinimumWidth(400)

        self.setLayout(v_layout)

    def action_add(self, _):
        self.encoder_view.update_view("Add Encoder")
        if self.encoder_view.exec() == QDialog.Accepted:
            media_type, encoder_group, name, command, executable, extension = self.encoder_view.get_details(
            )
            self.encoder.add_encoder(media_type, encoder_group, name, command,
                                     executable, extension)

    def action_del(self, _):
        path, _ = self.encoder.get_encoder()
        tokens = path.split(EncoderSelector.__PATH_SEPARATOR__)
        self.encoder.del_encoder(tokens[0], tokens[1], tokens[2])

    def action_mod(self, _):
        path, encoder = self.encoder.get_encoder()
        self.encoder_view.update_view("Modify Encoder",
                                      encoder_path=path,
                                      encoder=encoder)
        if self.encoder_view.exec() == QDialog.Accepted:
            media_type, encoder_group, name, command, executable, extension = self.encoder_view.get_details(
            )
            self.encoder.update_encoder(media_type, encoder_group, name,
                                        command, executable, extension)

    def action_ref(self, _):
        self.encoder.refresh_encoders()

    def select_encoder(self, encoder_name):
        return self.encoder.select_encoder(encoder_name)

    def _configure_toolbar(self, path, encoder):
        self.mod_action.setEnabled(True if encoder else False)
        self.del_action.setEnabled(True if encoder else False)
        if encoder:
            self.encoder_changed.emit(path, encoder)
Esempio n. 13
0
    def __init__(self):
        super().__init__()
        self.setWindowIcon(QIcon('./icons/notepad-dev.ico'))
        self.screen_width, self.scren_height = self.geometry().width(
        ), self.geometry().height()
        self.resize(self.screen_width * 2, self.scren_height * 2)

        self.filterTypes = 'Text Document (*.txt);; Python (*.py);; Javascript (*.js);; Java (*.java);; HTML (*.html);; CSS (*.css);; Bash script (*.sh);; C (*.c);; C++ (*.cpp);; C# (*.cs);; Markdown (*.md)'

        self.path = None

        fixedFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        fixedFont.setPointSize(12)

        mainLayout = QVBoxLayout()

        # editor
        self.editor = QPlainTextEdit()
        self.editor.setFont(fixedFont)
        mainLayout.addWidget(self.editor)

        self.statusBar = self.statusBar()

        # app container
        container = QWidget()
        container.setLayout(mainLayout)
        self.setCentralWidget(container)

        # -------------------------------
        # File menu
        # -------------------------------
        file_menu = self.menuBar().addMenu('&File')

        # -------------------------------
        # File Toolbar
        # -------------------------------
        file_toolbar = QToolBar('File')
        file_toolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.TopToolBarArea, file_toolbar)
        """
        open, save, save as
        """
        open_file_action = QAction(QIcon("./icons/open-file.ico"), 'Open File',
                                   self)
        open_file_action.setStatusTip('Open File')
        open_file_action.setShortcut(QKeySequence.Open)
        open_file_action.triggered.connect(self.file_open)  #TODO

        save_file_action = self.create_action(self, './icons/save-file.ico',
                                              'Save File', 'Save File',
                                              self.file_save)
        save_file_action.setShortcut(QKeySequence.Save)

        save_fileAs_action = self.create_action(self,
                                                './icons/save-as-file.ico',
                                                'Save As File', 'Save As File',
                                                self.file_saveAs)
        save_fileAs_action.setShortcut(QKeySequence('Ctrl+Shift+S'))

        file_menu.addActions(
            [open_file_action, save_file_action, save_fileAs_action])
        file_toolbar.addActions(
            [open_file_action, save_file_action, save_fileAs_action])

        # Print Action (Print Document)
        print_action = self.create_action(self, './icons/print-file.ico',
                                          'Print File', 'Print File',
                                          self.print_file)
        print_action.setShortcut(QKeySequence.Print)
        file_menu.addAction(print_action)
        file_toolbar.addAction(print_action)

        # -------------------------------
        # Edit Menu
        # -------------------------------
        edit_menu = self.menuBar().addMenu('&Edit')

        # -------------------------------
        # Edit Toolbar
        # -------------------------------
        edit_toolbar = QToolBar('Edit')
        edit_toolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.TopToolBarArea, edit_toolbar)

        # Undo, Redo Actions
        undo_action = self.create_action(self, './icons/undo.ico', 'Undo',
                                         'Undo', self.editor.undo)
        undo_action.setShortcut(QKeySequence.Undo)

        redo_action = self.create_action(self, './icons/redo.ico', 'Redo',
                                         'Redo', self.editor.redo)
        redo_action.setShortcut(QKeySequence.Redo)

        edit_menu.addActions([undo_action, redo_action])
        edit_toolbar.addActions([undo_action, redo_action])

        # Clear
        clear_action = self.create_action(self, './icons/clear.ico', 'Clear',
                                          'Clear', self.clear_content)
        edit_menu.addAction(clear_action)
        edit_toolbar.addAction(clear_action)

        # add separator
        edit_menu.addSeparator()
        edit_toolbar.addSeparator()

        # cut, copy, paste, select all
        cut_action = self.create_action(self, './icons/cut.ico', 'Cut', 'Cut',
                                        self.editor.cut)
        copy_action = self.create_action(self, './icons/copy.ico', 'Copy',
                                         'Copy', self.editor.copy)
        paste_action = self.create_action(self, './icons/paste.ico', 'Paste',
                                          'Paste', self.editor.paste)
        select_all_action = self.create_action(self, './icons/select-all.ico',
                                               'Select All', 'Select All',
                                               self.editor.selectAll)

        cut_action.setShortcut(QKeySequence.Cut)
        copy_action.setShortcut(QKeySequence.Copy)
        paste_action.setShortcut(QKeySequence.Paste)
        select_all_action.setShortcut(QKeySequence.SelectAll)

        edit_menu.addActions(
            [cut_action, copy_action, paste_action, select_all_action])
        edit_toolbar.addActions(
            [cut_action, copy_action, paste_action, select_all_action])

        # add separator
        edit_menu.addSeparator()
        edit_toolbar.addSeparator()

        # wrap text action
        wrap_text_action = self.create_action(self, './icons/wrap-text.ico',
                                              'Wrap Text', 'Wrap Text',
                                              self.toggle_wrap_text)
        wrap_text_action.setShortcut('Ctrl+Shift+W')

        edit_menu.addAction(wrap_text_action)
        edit_toolbar.addAction(wrap_text_action)

        self.update_title()
Esempio n. 14
0
class MainWindow(QMainWindow):
    def __init__(self, filename=None, parent=None):
        super(MainWindow, self).__init__(parent)

        font = QFont("Courier", 11)
        self.toolbar = QToolBar()
        font.setFixedPitch(True)
        self.editor = TextEdit()
        self.editor.setFont(font)
        self.highlighter = AssemblyHighlighter(self.editor.document())
        self.setCentralWidget(self.editor)

        status = self.statusBar()
        status.setSizeGripEnabled(False)
        status.showMessage("Ready", 5000)

        fileNewAction = self.createAction("&New...", self.fileNew,
                                          QKeySequence.New, "filenew",
                                          "Create a Assembly file")
        fileOpenAction = self.createAction("&Open...", self.fileOpen,
                                           QKeySequence.Open, "fileopen",
                                           "Open an existing Assembly file")
        self.fileSaveAction = self.createAction("&Save", self.fileSave,
                                                QKeySequence.Save, "filesave",
                                                "Save the file")
        self.fileSaveAsAction = self.createAction(
            "Save &As...",
            self.fileSaveAs,
            icon="filesaveas",
            tip="Save the file using a new name")
        self.connect_boardAction = self.createAction("&connect JTTAG",
                                                     self.connect_board,
                                                     icon='connect',
                                                     tip="connect the jttag")

        fileQuitAction = self.createAction("&Quit", self.close, "Ctrl+Q",
                                           "filequit", "Close the application")
        self.editCopyAction = self.createAction("&Copy", self.editor.copy,
                                                QKeySequence.Copy, "editcopy",
                                                "Copy text to the clipboard")
        self.editCutAction = self.createAction("Cu&t", self.editor.cut,
                                               QKeySequence.Cut, "editcut",
                                               "Cut text to the clipboard")
        self.editPasteAction = self.createAction(
            "&Paste", self.editor.paste, QKeySequence.Paste, "editpaste",
            "Paste in the clipboard's text")
        self.change_binAction = self.createAction("&change into binary",
                                                  self.change_bin, "Ctrl+]",
                                                  "change_bin",
                                                  "change asm into binary")
        self.change_coeAction = self.createAction("&change into coe",
                                                  self.change_coe, "Ctrl+e",
                                                  "change_coe",
                                                  "change asm into coe")
        self.change_hexAction = self.createAction("&change into hex",
                                                  self.change_hex, "Ctrl+[",
                                                  "change_hex",
                                                  "change asm into hex")
        self.editIndentAction = self.createAction(
            "&Indent", self.editIndent, "Ctrl+u", "editindent",
            "Indent the current line or selection")
        self.editUnindentAction = self.createAction(
            "&Unindent", self.editUnindent, "Ctrl+i", "editunindent",
            "Unindent the current line or selection")

        fileMenu = self.menuBar().addMenu("&File")
        self.addActions(fileMenu, (
            fileNewAction,
            fileOpenAction,
            self.fileSaveAction,
            self.fileSaveAsAction,
            self.connect_boardAction,
            None,
            fileQuitAction,
        ))
        editMenu = self.menuBar().addMenu("&Edit")
        self.addActions(
            editMenu,
            (self.editCopyAction, self.editCutAction, self.editPasteAction,
             None, self.change_binAction, self.change_hexAction,
             self.editIndentAction, self.editUnindentAction))
        fileToolbar = self.addToolBar("File")
        fileToolbar.setObjectName("FileToolBar")
        self.addActions(fileToolbar,
                        (fileNewAction, fileOpenAction, self.fileSaveAction,
                         self.connect_boardAction))

        #editToolbar = self.addToolBar("Edit")
        editToolbar = self.addToolBar(Qt.LeftToolBarArea, self.toolbar)
        #editToolbar.setObjectName("EditToolBar")
        self.toolbar.addActions(
            (self.editCopyAction, self.editCutAction, self.editPasteAction,
             None, self.change_binAction, self.change_hexAction,
             self.change_coeAction, self.editIndentAction,
             self.editUnindentAction))
        #editToolbar = self.addToolBar(Qt.LeftToolBarArea,QToolBar())

        self.editor.selectionChanged.connect(self.updateUi)
        self.editor.document().modificationChanged.connect(self.updateUi)
        QApplication.clipboard().dataChanged.connect(self.updateUi)

        self.resize(800, 600)
        self.setWindowTitle("PRV332 ide")
        self.filename = filename
        self.bin_name = None
        if self.filename is not None:
            self.loadFile()
        self.updateUi()

    def updateUi(self, arg=None):
        self.fileSaveAction.setEnabled(self.editor.document().isModified())
        enable = not self.editor.document().isEmpty()
        self.fileSaveAsAction.setEnabled(enable)
        self.connect_boardAction.setEnabled(enable)
        self.change_binAction.setEnabled(enable)
        self.change_hexAction.setEnabled(enable)
        self.change_coeAction.setEnabled(enable)
        self.editIndentAction.setEnabled(enable)
        self.editUnindentAction.setEnabled(enable)
        enable = self.editor.textCursor().hasSelection()
        self.editCopyAction.setEnabled(enable)
        self.editCutAction.setEnabled(enable)
        self.editPasteAction.setEnabled(self.editor.canPaste())

    def createAction(self,
                     text,
                     slot=None,
                     shortcut=None,
                     icon=None,
                     tip=None,
                     checkable=False,
                     signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon("{0}.ico".format(icon)))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)
        if checkable:
            action.setCheckable(True)
        return action

    def addActions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def closeEvent(self, event):
        if not self.okToContinue():
            event.ignore()

    def okToContinue(self):
        if self.editor.document().isModified():
            reply = QMessageBox.question(
                self, "PRV332 ide - Unsaved Changes", "Save unsaved changes?",
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
            if reply == QMessageBox.Cancel:
                return False
            elif reply == QMessageBox.Yes:
                return self.fileSave()
        return True

    def fileNew(self):
        if not self.okToContinue():
            return
        document = self.editor.document()
        document.clear()
        document.setModified(False)
        self.filename = None
        self.setWindowTitle("PRV332 ide - Unnamed")
        self.updateUi()

    def fileOpen(self):
        if not self.okToContinue():
            return
        dir = (os.path.dirname(self.filename)
               if self.filename is not None else ".")
        fname = str(
            QFileDialog.getOpenFileName(
                self, "PRV332 ide - Choose File", dir,
                "Assembly language sourse file (*.asm)")[0])
        if fname:
            self.filename = fname
            self.loadFile()

    def loadFile(self):
        fh = None
        try:
            fh = QFile(self.filename)
            if not fh.open(QIODevice.ReadOnly):
                raise IOError(str(fh.errorString()))
            stream = QTextStream(fh)
            stream.setCodec("UTF-8")

            self.editor.setPlainText(stream.readAll())
            self.editor.document().setModified(False)
        except EnvironmentError as e:
            QMessageBox.warning(
                self, "PRV332 ide -- Load Error",
                "Failed to load {0}: {1}".format(self.filename, e))
        finally:
            if fh is not None:
                fh.close()
        self.setWindowTitle("PRV332 ide - {0}".format(
            QFileInfo(self.filename).fileName()))

    def fileSave(self):
        if self.filename is None:
            return self.fileSaveAs()
        fh = None
        try:
            fh = QFile(self.filename)
            #print(fh)
            if not fh.open(QIODevice.WriteOnly):
                raise IOError(str(fh.errorString()))
            stream = QTextStream(fh)
            stream.setCodec("UTF-8")
            stream << self.editor.toPlainText()

            self.editor.document().setModified(False)
        except EnvironmentError as e:
            QMessageBox.warning(
                self, "PRV332 ide -- Save Error",
                "Failed to save {0}: {1}".format(self.filename, e))
            return False
        finally:
            if fh is not None:
                fh.close()
        return True

    def fileSaveAs(self):
        filename = self.filename if self.filename is not None else "."
        filename, filetype = QFileDialog.getSaveFileName(
            self, "PRV332 ide -- Save File As", filename,
            "Assembly language sourse file (*.asm)")
        if filename:
            self.filename = filename
            self.setWindowTitle("PRV332 ide - {0}".format(
                QFileInfo(self.filename).fileName()))
            return self.fileSave()
        return False

    def run_socket(self):
        #os.system("python t_server.py")
        os.system("t_server.exe")

    def connect_board(self):
        threadsockct = Thread(target=self.run_socket)
        threadsockct.start()

    def bin_fileSave(self):
        line0 = 0
        err = 0
        try:

            fname = QFileDialog.getSaveFileName(self, "Write File", "./",
                                                "All (*.*)")  # 写入文件首先获取文件路径
        except:
            err = 1
        if fname[0]:  # 如果获取的路径非空
            with open('asm.txt', "r") as ass_file:
                with open(fname[0], "w+") as bin_file:
                    for line in ass_file:
                        line0 += 1
                        try:
                            changed = change_into_bin(line)
                            chan = changed.after_change_str + '\n'
                            bin_file.write(chan)

                        except:
                            if (not (line == '\n')):
                                QMessageBox.critical(
                                    self, "错误",
                                    "第" + str(line0) + "行出错未能生成bin\n" + line)
                            err = 1
        if not err:
            QMessageBox.about(self, "成功", "成功生成bin于\n" + fname[0])

    def change_bin(self):

        te = self.editor.toPlainText()
        with open('asm.txt', 'w+') as assfile:
            assfile.write(te)
        #with open('ass.txt', 'r+') as assfile:
        #   with open('bin.txt', 'w+') as binfile:
        #       for line in assfile:
        #           changed = change_into_bin(line)

        #           chan = changed.after_change_str + '\n'
        #           binfile.write(chan)
        self.bin_fileSave()
        '''
        这一段原来是作为一个indent
        但是后来觉得可能不大会用到
        '''

    def coe_fileSave(self):
        line0 = 0
        err = 0
        #c = self.count
        try:
            fname = QFileDialog.getSaveFileName(self, "Write File", "./",
                                                "All (*.*)")  # 写入文件首先获取文件路径
        except:
            err = 1
        if fname[0]:  # 如果获取的路径非空
            with open('asm.txt', "r") as ass_file:
                count = 0
                #f = open("filepath", "r")

                with open(fname[0], "w+") as coe_file:
                    coe_file.write(
                        ';this coe file is made by prv332 ide \n;if you have any questions you can e-mail [email protected]\n'
                    )
                    coe_file.write(
                        'memory_initialization_radix = 2;\nmemory_initialization_vector =\n'
                    )
                    for line in ass_file:
                        line0 += 1
                        try:
                            changed = change_into_bin(line)
                            if line0 == self.count:
                                chan = changed.after_change_str + ';' + '\n'
                            else:
                                chan = changed.after_change_str + ',' + '\n'
                            coe_file.write(chan)

                        except:
                            if (not (line == '\n')):
                                QMessageBox.critical(
                                    self, "错误",
                                    "第" + str(line0) + "行出错未能生成coe\n" + line)
                            err = 1
        if not err:
            QMessageBox.about(self, "成功", "成功生成coe于\n" + fname[0])

    def change_coe(self):
        te = self.editor.toPlainText()
        with open('asm.txt', 'w+') as assfile:
            assfile.write(te)
        self.count = 0
        for index, line in enumerate(open('asm.txt', 'r')):
            self.count += 1
        print(self.count)
        self.coe_fileSave()

    def editIndent(self):
        cursor = self.editor.textCursor()
        cursor.beginEditBlock()
        if cursor.hasSelection():
            start = pos = cursor.anchor()
            end = cursor.position()
            if start > end:
                start, end = end, start
                pos = start
            cursor.clearSelection()
            cursor.setPosition(pos)
            cursor.movePosition(QTextCursor.StartOfLine)
            while pos <= end:
                cursor.insertText("    ")
                cursor.movePosition(QTextCursor.Down)
                cursor.movePosition(QTextCursor.StartOfLine)
                pos = cursor.position()
            cursor.setPosition(start)
            cursor.movePosition(QTextCursor.NextCharacter,
                                QTextCursor.KeepAnchor, end - start)
        else:
            pos = cursor.position()
            cursor.movePosition(QTextCursor.StartOfBlock)
            cursor.insertText("    ")
            cursor.setPosition(pos + 4)
        cursor.endEditBlock()

    def hex_fileSave(self):
        err = 0
        try:
            fname = QFileDialog.getSaveFileName(self, "Write File", "./",
                                                "All (*.*)")  # 写入文件首先获取文件路径
        except:
            err = 1
        if fname[0]:  # 如果获取的路径非空
            #a = change_into_hex('asm.txt', fname[0])

            try:
                a = change_into_hex('asm.txt', fname[0])
            except:

                QMessageBox.critical(self, "错误", "未能生成hex\n")
                err = 1
        if not err:
            a.write_hex()
            QMessageBox.about(self, "成功", "成功生成hex于\n" + fname[0])

    '''
    from_file = 'asm.txt'
    filea = 'hex.txt'
    a = change_into_hex(from_file, filea)
    print('地址.......', a.location_dict)

    print('global_label_data_dict', global_label_data_dict)
    print('end')
    a.write_hex()
    '''

    def change_hex(self):
        '''
        from_file = 'asm.txt'
        filea = 'hex.txt'
        a = change_into_hex(from_file,filea)
        print('地址',a.location_dict)
        print('end')
        a.write_hex()
        '''
        te = self.editor.toPlainText()
        with open('asm.txt', 'w+') as assfile:
            assfile.write(te)
        self.hex_fileSave()

    def editUnindent(self):
        cursor = self.editor.textCursor()
        cursor.beginEditBlock()
        if cursor.hasSelection():
            start = pos = cursor.anchor()
            end = cursor.position()
            if start > end:
                start, end = end, start
                pos = start
            cursor.setPosition(pos)
            cursor.movePosition(QTextCursor.StartOfLine)
            while pos <= end:
                cursor.clearSelection()
                cursor.movePosition(QTextCursor.NextCharacter,
                                    QTextCursor.KeepAnchor, 4)
                if cursor.selectedText() == "    ":
                    cursor.removeSelectedText()
                cursor.movePosition(QTextCursor.Down)
                cursor.movePosition(QTextCursor.StartOfLine)
                pos = cursor.position()
            cursor.setPosition(start)
            cursor.movePosition(QTextCursor.NextCharacter,
                                QTextCursor.KeepAnchor, end - start)
        else:
            cursor.clearSelection()
            cursor.movePosition(QTextCursor.StartOfBlock)
            cursor.movePosition(QTextCursor.NextCharacter,
                                QTextCursor.KeepAnchor, 4)
            if cursor.selectedText() == "    ":
                cursor.removeSelectedText()
        cursor.endEditBlock()
Esempio n. 15
0
    def __init__(self, pageContent):
        """ Object initialization.

        Parameters
        ----------
        self : QWidget
        pageContent : VoiceEditor
            Widget on which the actions should be performed.
        """

        super().__init__('Find and replace')

        self.pageContent = pageContent

        ## ACTIONS

        # find
        findAction = QAction(
                QIcon('icons/edit-find'),
                'Find', self)
        findAction.setStatusTip('Find the pattern')
        findAction.triggered.connect(self.find)
        # replace
        replaceAction = QAction(
                QIcon('icons/edit-find-replace'),
                'Replace', self)
        replaceAction.setStatusTip('Replace the pattern')
        replaceAction.triggered.connect(self.replace)
        # find all
        findAllAction = QAction(
                QIcon('icons/document-preview'),
                'Find all', self)
        findAllAction.setStatusTip(
                'Find all the occourrences of the pattern')
        findAllAction.triggered.connect(self.findAll)
        # replace all
        replaceAllAction = QAction(
                QIcon('icons/document-edit-decrypt-verify'),
                'Replace all', self)
        replaceAllAction.setStatusTip(
                'Replace all the occourrences of the pattern')
        replaceAllAction.triggered.connect(self.replaceAll)
        # clear search results
        clearAction = QAction(
                QIcon('icons/window-close'),
                'Clear', self)
        clearAction.setStatusTip('Clear the highlighted search results')
        clearAction.triggered.connect(self.removeHighlighting)

        ## WIDGETS

        self.regex = QLineEdit()
        self.regex.returnPressed.connect(self.find)
        QShortcut(QKeySequence('Ctrl+F'), self, self.selectFind)

        self.replacement = QLineEdit()
        self.replacement.returnPressed.connect(self.replace)
        QShortcut(QKeySequence('Ctrl+R'), self, self.selectReplace)

        QShortcut(QKeySequence('Esc'), self, self.pageContent.setFocus)

        findToolbar = QToolBar('Find')
        findToolbar.addActions([
            findAction,
            replaceAction])
        findAllToolbar = QToolBar('Find all')
        findAllToolbar.addActions([
            findAllAction,
            replaceAllAction,
            clearAction])

        layout = QGridLayout()
        layout.addWidget(QLabel('Regex'), 0, 0)
        layout.addWidget(self.regex, 0, 1)
        layout.addWidget(QLabel('Replacement'), 1, 0)
        layout.addWidget(self.replacement, 1, 1)
        layout.addWidget(findToolbar, 0, 3)
        layout.addWidget(findAllToolbar, 1, 3)

        widget = QWidget()
        widget.setLayout(layout)

        self.setWidget(widget)
Esempio n. 16
0
class LibraryGroupingManager(CollapsibleWidget):
    def __init__(self):
        super().__init__("Library Tree Group Manager")
        self.source = QListWidget()
        self.target = QListWidget()
        self.action_toolbar = QToolBar()
        self.add_action = CommonUtils.create_toolbar_action(
            "Add selected key to grouping",
            QIcon.fromTheme("media-skip-forward"), self.add)
        self.sub_action = CommonUtils.create_toolbar_action(
            "Remove selected key to grouping",
            QIcon.fromTheme("media-skip-backward"), self.sub)
        self.reset_action = CommonUtils.create_toolbar_action(
            "Reset to library type default",
            QIcon.fromTheme("document-revert"), self.reset)
        self.apply_action = CommonUtils.create_toolbar_action(
            "Apply this view", QIcon.fromTheme("document-save"), self.save)
        self.icon = QIcon.fromTheme("folder")
        self._init_ui()

    def _init_ui(self):
        self.action_toolbar.setOrientation(Qt.Vertical)
        dummy = QWidget()
        dummy.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.action_toolbar.addWidget(dummy)
        self.action_toolbar.addActions([
            self.add_action, self.sub_action, self.reset_action,
            self.apply_action
        ])
        self.action_toolbar.setContentsMargins(0, 0, 0, 0)
        q_size = QSize(16, 16)
        self.action_toolbar.setIconSize(q_size)
        self.source.setIconSize(q_size)
        self.source.setMaximumHeight(120)
        self.target.setIconSize(q_size)
        self.target.setMaximumHeight(120)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.source)
        layout.addWidget(self.action_toolbar)
        layout.addWidget(self.target)
        self.set_content_layout(layout)

    def update_grouping(self, grouping):
        self.source.clear()
        for key in grouping:
            item = QListWidgetItem(self.icon, key)
            self.source.addItem(item)

    def add(self):
        self.swap_items(self.source, self.target)

    def sub(self):
        self.swap_items(self.target, self.source)

    def save(self):
        pass

    def reset(self):
        pass

    @staticmethod
    def swap_items(source, target):
        list_items = source.selectedItems()
        if not list_items:
            return
        for item in list_items:
            source.takeItem(source.row(item))
            target.addItem(item)
Esempio n. 17
0
    def __init__(self):
        super().__init__()
        # settings file
        self.settings = QSettings('martinopilia', 'wikied')
        # label for the permanent message in the status bar
        self.permanentMessage = QLabel('Disconnected')
        # window for the regex sandbox
        self.regexSandbox = RegexSandbox()
        # object for the connection to the site
        self.connection = Connection(self.settings)
        self.connection.statusMessage.connect(self.statusBar().showMessage)
        self.connection.permanentMessage.connect(self.permanentMessage.setText)
        # window for the account settings
        self.accountDialog = AccountDialog(self.settings)

        # add permanent widget to the status bar
        self.statusBar().addPermanentWidget(self.permanentMessage)

        # actions
        # quit
        exitAction = QAction(
                QIcon('icons/window-close'),
                'Exit', self)
        exitAction.setStatusTip('Quit the application (Ctrl+Q)')
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(self.close)
        # open RegexSandbox
        sandboxAction = QAction(
                QIcon('icons/code-context'),
                'Regex sandbox', self)
        sandboxAction.setStatusTip(
                'Open the regex test environment (Ctrl+Shif+S)')
        sandboxAction.setShortcut('Ctrl+Shift+S')
        sandboxAction.triggered.connect(self.regexSandbox.show)
        # connect
        connectAction = QAction(
                QIcon('icons/network-connect'),
                'Connect', self)
        connectAction.setStatusTip('Connect to the project')
        connectAction.triggered.connect(self.connection.connect)
        # disconnect
        disconnectAction = QAction(
                QIcon('icons/network-disconnect'),
                'Disconnect', self)
        disconnectAction.setStatusTip('Disconnect from the project')
        disconnectAction.triggered.connect(self.connection.disconnect)
        # set account
        setAccountAction = QAction(
                QIcon('icons/user-identity'),
                'Set account', self)
        setAccountAction.setStatusTip('Manage the account settings')
        setAccountAction.triggered.connect(self.accountDialog.exec_)

        # central widget and docks
        diff = Diff()
        diff.setObjectName('Diff')
        diff.setVisible(False)
        self.addDockWidget(Qt.TopDockWidgetArea, diff)

        editorWidget = VoiceEditor(self.connection, diff)
        self.setCentralWidget(editorWidget)

        substWidget = FindAndReplace(editorWidget.pageContent)
        substWidget.setObjectName('Find and replace')
        substWidget.statusMessage.connect(self.statusBar().showMessage)
        self.addDockWidget(Qt.BottomDockWidgetArea, substWidget)

        voiceSelector = VoiceSelector(self.connection, editorWidget)
        voiceSelector.setObjectName('Select voices')
        voiceSelector.statusMessage.connect(self.statusBar().showMessage)
        self.addDockWidget(Qt.LeftDockWidgetArea, voiceSelector)

        # toolbars
        # Connection
        connectionToolbar = QToolBar('Connection')
        connectionToolbar.setObjectName('connectionToolbar')
        connectionToolbar.addActions(
                [connectAction, disconnectAction, setAccountAction])
        self.addToolBar(connectionToolbar)

        # menu bar
        # File
        fileMenu = self.menuBar().addMenu('File')
        fileMenu.addAction(connectAction)
        fileMenu.addAction(disconnectAction)
        fileMenu.addAction(setAccountAction)
        fileMenu.addSeparator()
        fileMenu.addAction(exitAction)
        # Tools
        toolsMenu = self.menuBar().addMenu('Tools')
        toolsMenu.addAction(sandboxAction)
        # View
        viewMenu = self.menuBar().addMenu('View')
        viewMenu.addAction(voiceSelector.toggleViewAction())
        viewMenu.addAction(substWidget.toggleViewAction())
        viewMenu.addAction(connectionToolbar.toggleViewAction())
        viewMenu.addAction(editorWidget.actionsToolbar.toggleViewAction())
        viewMenu.addAction(diff.toggleViewAction())
        viewMenu.addAction(editorWidget.editToolbar.toggleViewAction())

        # view details
        self.setGeometry(200, 200, 1000, 800)
        self.setWindowTitle('WikiEd')
        self.setWindowIcon(QIcon(''))
        editorWidget.pageContent.setFocus()

        # restore state and geometry (lazy initialization)
        if (not self.settings.value('window/geometry') or
            not self.settings.value('window/state')):
            self.saveWindow()
        self.restoreGeometry(self.settings.value('window/geometry'))
        self.restoreState(self.settings.value('window/state'))

        self.show()
Esempio n. 18
0
    def setupTextActions(self):
        tb = QToolBar(self)
        tb.setWindowTitle("Format Actions")
        self.addToolBar(tb)

        menu = QMenu("F&ormat", self)
        self.menuBar().addMenu(menu)

        self.actionTextBold = QAction(QIcon.fromTheme(
            'format-text-bold', QIcon(rsrcPath + '/textbold.png')),
                                      "&Bold",
                                      self,
                                      priority=QAction.LowPriority,
                                      shortcut=Qt.CTRL + Qt.Key_B,
                                      triggered=self.textBold,
                                      checkable=True)
        bold = QFont()
        bold.setBold(True)
        self.actionTextBold.setFont(bold)
        tb.addAction(self.actionTextBold)
        menu.addAction(self.actionTextBold)

        self.actionTextItalic = QAction(QIcon.fromTheme(
            'format-text-italic', QIcon(rsrcPath + '/textitalic.png')),
                                        "&Italic",
                                        self,
                                        priority=QAction.LowPriority,
                                        shortcut=Qt.CTRL + Qt.Key_I,
                                        triggered=self.textItalic,
                                        checkable=True)
        italic = QFont()
        italic.setItalic(True)
        self.actionTextItalic.setFont(italic)
        tb.addAction(self.actionTextItalic)
        menu.addAction(self.actionTextItalic)

        self.actionTextUnderline = QAction(QIcon.fromTheme(
            'format-text-underline', QIcon(rsrcPath + '/textunder.png')),
                                           "&Underline",
                                           self,
                                           priority=QAction.LowPriority,
                                           shortcut=Qt.CTRL + Qt.Key_U,
                                           triggered=self.textUnderline,
                                           checkable=True)
        underline = QFont()
        underline.setUnderline(True)
        self.actionTextUnderline.setFont(underline)
        tb.addAction(self.actionTextUnderline)
        menu.addAction(self.actionTextUnderline)

        menu.addSeparator()

        grp = QActionGroup(self, triggered=self.textAlign)

        # Make sure the alignLeft is always left of the alignRight.
        if QApplication.isLeftToRight():
            self.actionAlignLeft = QAction(
                QIcon.fromTheme('format-justify-left',
                                QIcon(rsrcPath + '/textleft.png')), "&Left",
                grp)
            self.actionAlignCenter = QAction(
                QIcon.fromTheme('format-justify-center',
                                QIcon(rsrcPath + '/textcenter.png')),
                "C&enter", grp)
            self.actionAlignRight = QAction(
                QIcon.fromTheme('format-justify-right',
                                QIcon(rsrcPath + '/textright.png')), "&Right",
                grp)
        else:
            self.actionAlignRight = QAction(
                QIcon.fromTheme('format-justify-right',
                                QIcon(rsrcPath + '/textright.png')), "&Right",
                grp)
            self.actionAlignCenter = QAction(
                QIcon.fromTheme('format-justify-center',
                                QIcon(rsrcPath + '/textcenter.png')),
                "C&enter", grp)
            self.actionAlignLeft = QAction(
                QIcon.fromTheme('format-justify-left',
                                QIcon(rsrcPath + '/textleft.png')), "&Left",
                grp)

        self.actionAlignJustify = QAction(
            QIcon.fromTheme('format-justify-fill',
                            QIcon(rsrcPath + '/textjustify.png')), "&Justify",
            grp)

        self.actionAlignLeft.setShortcut(Qt.CTRL + Qt.Key_L)
        self.actionAlignLeft.setCheckable(True)
        self.actionAlignLeft.setPriority(QAction.LowPriority)

        self.actionAlignCenter.setShortcut(Qt.CTRL + Qt.Key_E)
        self.actionAlignCenter.setCheckable(True)
        self.actionAlignCenter.setPriority(QAction.LowPriority)

        self.actionAlignRight.setShortcut(Qt.CTRL + Qt.Key_R)
        self.actionAlignRight.setCheckable(True)
        self.actionAlignRight.setPriority(QAction.LowPriority)

        self.actionAlignJustify.setShortcut(Qt.CTRL + Qt.Key_J)
        self.actionAlignJustify.setCheckable(True)
        self.actionAlignJustify.setPriority(QAction.LowPriority)

        tb.addActions(grp.actions())
        menu.addActions(grp.actions())
        menu.addSeparator()

        pix = QPixmap(16, 16)
        pix.fill(Qt.black)
        self.actionTextColor = QAction(QIcon(pix),
                                       "&Color...",
                                       self,
                                       triggered=self.textColor)
        tb.addAction(self.actionTextColor)
        menu.addAction(self.actionTextColor)

        tb = QToolBar(self)
        tb.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea)
        tb.setWindowTitle("Format Actions")
        self.addToolBarBreak(Qt.TopToolBarArea)
        self.addToolBar(tb)

        comboStyle = QComboBox(tb)
        tb.addWidget(comboStyle)
        comboStyle.addItem("Standard")
        comboStyle.addItem("Bullet List (Disc)")
        comboStyle.addItem("Bullet List (Circle)")
        comboStyle.addItem("Bullet List (Square)")
        comboStyle.addItem("Ordered List (Decimal)")
        comboStyle.addItem("Ordered List (Alpha lower)")
        comboStyle.addItem("Ordered List (Alpha upper)")
        comboStyle.addItem("Ordered List (Roman lower)")
        comboStyle.addItem("Ordered List (Roman upper)")
        comboStyle.activated.connect(self.textStyle)

        self.comboFont = QFontComboBox(tb)
        tb.addWidget(self.comboFont)
        self.comboFont.activated[str].connect(self.textFamily)

        self.comboSize = QComboBox(tb)
        self.comboSize.setObjectName("comboSize")
        tb.addWidget(self.comboSize)
        self.comboSize.setEditable(True)

        db = QFontDatabase()
        for size in db.standardSizes():
            self.comboSize.addItem("%s" % (size))

        self.comboSize.activated[str].connect(self.textSize)
        self.comboSize.setCurrentIndex(
            self.comboSize.findText("%s" % (QApplication.font().pointSize())))
Esempio n. 19
0
    def __init__(self):
        super().__init__()
        self.setWindowIcon(QIcon('./Icons/notepad.ico'))
        self.screen_width, self.screen_height = self.geometry().width(
        ), self.geometry().height()
        self.resize(self.screen_width * 2, self.screen_height * 2)

        self.filterTypes = 'Text Document (*.txt);; Python (*.py);; Markdown (*.md)'

        self.path = None

        fixedFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        fixedFont.setPointSize(12)

        mainLayout = QVBoxLayout()

        # editor
        self.editor = QPlainTextEdit()
        self.editor.setFont(fixedFont)
        mainLayout.addWidget(self.editor)

        # stautsBar
        self.statusBar = self.statusBar()

        # app container
        container = QWidget()
        container.setLayout(mainLayout)
        self.setCentralWidget(container)

        # File Menu

        file_menu = self.menuBar().addMenu('&File')

        # File ToolBar
        file_toolbar = QToolBar('File')
        file_toolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.BottomToolBarArea, file_toolbar)

        # Open, save, saveAs
        open_file_action = QAction(QIcon('./Icons/open_files.ico'),
                                   'Open File...', self)
        open_file_action.setStatusTip('Open file')
        open_file_action.setShortcut(QKeySequence.Open)
        open_file_action.triggered.connect(self.file_open)

        save_file_action = self.create_action(self, './Icons/save.ico',
                                              'Save File', 'Save file',
                                              self.file_save)
        save_file_action.setShortcut(QKeySequence.Save)

        save_fileAs_action = self.create_action(self, './Icons/save.ico',
                                                'Save File As...',
                                                'Save file as',
                                                self.file_saveAs)
        save_fileAs_action.setShortcut(QKeySequence('Ctrl+Shift+S'))

        file_menu.addActions(
            [open_file_action, save_file_action, save_fileAs_action])
        file_toolbar.addActions(
            [open_file_action, save_file_action, save_fileAs_action])

        # Print Document
        print_action = self.create_action(self, './Icons/printer.ico',
                                          'Print File', 'Print file',
                                          self.print_file)
        print_action.setShortcut(QKeySequence.Print)
        file_menu.addAction(print_action)
        file_toolbar.addAction(print_action)

        #Menu
        edit_menu = self.menuBar().addMenu('&Edit')

        #ToolBar
        edit_toolbar = QToolBar('Edit')
        edit_toolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.BottomToolBarArea, edit_toolbar)

        # Undo, Redo Actions
        undo_action = self.create_action(self, './Icons/undo.ico', 'Undo',
                                         'Undo', self.editor.undo)
        undo_action.setShortcut(QKeySequence.Undo)

        redo_action = self.create_action(self, './Icons/redo.ico', 'Redo',
                                         'Redo', self.editor.redo)
        redo_action.setShortcut(QKeySequence.Redo)

        edit_menu.addActions([undo_action, redo_action])
        edit_toolbar.addActions([undo_action, redo_action])

        # Clear action
        clear_action = self.create_action(self, './Icons/clear.ico', 'Clear',
                                          'Clear', self.clear_content)
        edit_menu.addAction(clear_action)
        edit_toolbar.addAction(clear_action)

        # add separator
        edit_menu.addSeparator()
        edit_toolbar.addSeparator()

        # cut, copy, paste, select all
        cut_action = self.create_action(self, './Icons/cut.ico', 'Cut', 'Cut',
                                        self.editor.cut)
        copy_action = self.create_action(self, './Icons/copy.ico', 'Copy',
                                         'Copy', self.editor.copy)
        paste_action = self.create_action(self, './Icons/paste.ico', 'Paste',
                                          'Paste', self.editor.paste)
        select_all_action = self.create_action(self, './Icons/select_all.ico',
                                               'Select All', 'Select all',
                                               self.editor.selectAll)

        cut_action.setShortcut(QKeySequence.Cut)
        copy_action.setShortcut(QKeySequence.Copy)
        paste_action.setShortcut(QKeySequence.Paste)
        select_all_action.setShortcut(QKeySequence.SelectAll)

        edit_menu.addActions(
            [cut_action, copy_action, paste_action, select_all_action])
        edit_toolbar.addActions(
            [cut_action, copy_action, paste_action, select_all_action])

        #separator
        edit_menu.addSeparator()
        edit_toolbar.addSeparator()

        # wrap text
        wrap_text_action = self.create_action(self, './Icons/wrap_text.ico',
                                              'Wrap Text', 'Wrap text',
                                              self.toggle_wrap_text)
        wrap_text_action.setShortcut('Ctrl+Shift+W')
        edit_menu.addAction(wrap_text_action)
        edit_toolbar.addAction(wrap_text_action)

        self.update_title()
Esempio n. 20
0
    def __init__(self):
        super().__init__()
        self.setWindowIcon(QIcon('./Icons/notepad.png'))
        self.setGeometry(700, 400, 700, 700)

        # These are the types of files our notepad can open/read/use
        self.filterTypes = 'Text Document (*.txt);; Python (*.py);; PDF (*.pdf)'

        # This initializes the path to None so we can tell if we have a new note open
        # or if we are loading up an old note.
        self.path = None

        # Actual Notepad editor (and coloring and font and font size)
        mainLayout = QVBoxLayout()
        self.editor = QTextEdit()
        fixedFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        fixedFont.setPointSize(18)
        self.editor.setFont(fixedFont)
        self.setStyleSheet(
            "color: lime; background-color: black; selection-color: white; selection-background-color: blue;"
        )
        mainLayout.addWidget(self.editor)
        self.editor.setAutoFormatting(QTextEdit.AutoAll)

        # Status Bar
        self.statusBar = self.statusBar()

        # App Container
        container = QWidget()
        container.setLayout(mainLayout)
        self.setCentralWidget(container)

        # File Menus
        file_menu = self.menuBar().addMenu('&File')

        # File ToolBar (Bottom)
        file_toolbar = QToolBar('File')
        file_toolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.BottomToolBarArea, file_toolbar)

        # Open, Save, SaveAs
        openNote = self.create_action(self, './Icons/open', 'Open File...',
                                      'Opens a file', self.file_open)

        saveNote = self.create_action(self, './Icons/save_file.png',
                                      'Save File', 'Saves the file',
                                      self.file_save)
        saveNote.setShortcut(QKeySequence.Save)

        saveNoteAs = self.create_action(self, './Icons/save_as.png',
                                        'Save As...', 'Saves the file as',
                                        self.file_saveAs)
        saveNoteAs.setShortcut('Ctrl+Shift+S')

        file_menu.addActions([openNote, saveNote, saveNoteAs])
        file_toolbar.addActions([openNote, saveNote, saveNoteAs])

        # Edit Menu
        edit_menu = self.menuBar().addMenu('&Edit')

        # Edit ToolBar
        edit_toolbar = QToolBar('Edit')
        edit_toolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.BottomToolBarArea, edit_toolbar)

        # Undo and Redo Actions
        undo = self.create_action(self, './Icons/undo.png', 'Undo',
                                  'Undoes the last edit', self.editor.undo)
        undo.setShortcut(QKeySequence.Undo)

        redo = self.create_action(self, './Icons/redo.png', 'Redo',
                                  'Redoes the last edit', self.editor.redo)
        redo.setShortcut(QKeySequence.Redo)

        edit_menu.addActions([undo, redo])
        edit_toolbar.addActions([undo, redo])

        edit_menu.addSeparator
        edit_toolbar.addSeparator

        # Wrap Text
        wrapText_action = self.create_action(self, './Icons/wrap_text.png',
                                             'Wrap Text', 'Wrap Text',
                                             self.toggle_wrap_text)
        wrapText_action.setShortcut('Ctrl+Shift+w')
        edit_menu.addAction(wrapText_action)
        edit_toolbar.addAction(wrapText_action)

        # Change text color
        ChooseColor = self.create_action(self, './Icons/ColorWheel.png',
                                         'Set Text Color', 'Set Text Color',
                                         self.PickColor)
        ChooseColor.setShortcut('Ctrl+Shift+b')
        edit_menu.addAction(ChooseColor)
        edit_toolbar.addAction(ChooseColor)

        # Format Menu
        format_menu = self.menuBar().addMenu('&Format')

        # Format ToolBar
        format_toolbar = QToolBar('Format')
        format_toolbar.setIconSize(QSize(60, 60))
        self.addToolBar(Qt.BottomToolBarArea, format_toolbar)

        # Bold, Italicisze, and Underline
        boldText = self.create_action(
            self, './Icons/bold.png', 'Bold', 'Bold Text',
            lambda x: self.editor.setFontWeight(QFont.Bold
                                                if x else QFont.Normal))
        boldText.setShortcut(QKeySequence.Bold)
        boldText.setCheckable(True)

        italicText = self.create_action(self, './Icons/italic.png', 'Italics',
                                        'Italicize Text',
                                        self.editor.setFontItalic)
        italicText.setShortcut(QKeySequence.Italic)
        italicText.setCheckable(True)

        underlineText = self.create_action(self, './Icons/underline.png',
                                           'Underline', 'Underline Text',
                                           self.editor.setFontUnderline)
        underlineText.setShortcut(QKeySequence.Underline)
        underlineText.setCheckable(True)

        format_menu.addActions([boldText, italicText, underlineText])
        format_toolbar.addActions([boldText, italicText, underlineText])

        format_menu.addSeparator
        format_toolbar.addSeparator

        self.update_title()
Esempio n. 21
0
    def setupTextActions(self):
        tb = QToolBar(self)
        tb.setWindowTitle("Format Actions")
        self.addToolBar(tb)

        menu = QMenu("F&ormat", self)
        self.menuBar().addMenu(menu)

        self.actionTextBold = QAction(
                QIcon.fromTheme('format-text-bold',
                        QIcon(rsrcPath + '/textbold.png')),
                "&Bold", self, priority=QAction.LowPriority,
                shortcut=Qt.CTRL + Qt.Key_B, triggered=self.textBold,
                checkable=True)
        bold = QFont()
        bold.setBold(True)
        self.actionTextBold.setFont(bold)
        tb.addAction(self.actionTextBold)
        menu.addAction(self.actionTextBold)

        self.actionTextItalic = QAction(
                QIcon.fromTheme('format-text-italic',
                        QIcon(rsrcPath + '/textitalic.png')),
                "&Italic", self, priority=QAction.LowPriority,
                shortcut=Qt.CTRL + Qt.Key_I, triggered=self.textItalic,
                checkable=True)
        italic = QFont()
        italic.setItalic(True)
        self.actionTextItalic.setFont(italic)
        tb.addAction(self.actionTextItalic)
        menu.addAction(self.actionTextItalic)

        self.actionTextUnderline = QAction(
                QIcon.fromTheme('format-text-underline',
                        QIcon(rsrcPath + '/textunder.png')),
                "&Underline", self, priority=QAction.LowPriority,
                shortcut=Qt.CTRL + Qt.Key_U, triggered=self.textUnderline,
                checkable=True)
        underline = QFont()
        underline.setUnderline(True)
        self.actionTextUnderline.setFont(underline)
        tb.addAction(self.actionTextUnderline)
        menu.addAction(self.actionTextUnderline)

        menu.addSeparator()

        grp = QActionGroup(self, triggered=self.textAlign)

        # Make sure the alignLeft is always left of the alignRight.
        if QApplication.isLeftToRight():
            self.actionAlignLeft = QAction(
                    QIcon.fromTheme('format-justify-left',
                            QIcon(rsrcPath + '/textleft.png')),
                    "&Left", grp)
            self.actionAlignCenter = QAction(
                    QIcon.fromTheme('format-justify-center',
                            QIcon(rsrcPath + '/textcenter.png')),
                    "C&enter", grp)
            self.actionAlignRight = QAction(
                    QIcon.fromTheme('format-justify-right',
                            QIcon(rsrcPath + '/textright.png')),
                    "&Right", grp)
        else:
            self.actionAlignRight = QAction(
                    QIcon.fromTheme('format-justify-right',
                            QIcon(rsrcPath + '/textright.png')),
                    "&Right", grp)
            self.actionAlignCenter = QAction(
                    QIcon.fromTheme('format-justify-center',
                            QIcon(rsrcPath + '/textcenter.png')),
                    "C&enter", grp)
            self.actionAlignLeft = QAction(
                    QIcon.fromTheme('format-justify-left',
                            QIcon(rsrcPath + '/textleft.png')),
                    "&Left", grp)
 
        self.actionAlignJustify = QAction(
                QIcon.fromTheme('format-justify-fill',
                        QIcon(rsrcPath + '/textjustify.png')),
                "&Justify", grp)

        self.actionAlignLeft.setShortcut(Qt.CTRL + Qt.Key_L)
        self.actionAlignLeft.setCheckable(True)
        self.actionAlignLeft.setPriority(QAction.LowPriority)

        self.actionAlignCenter.setShortcut(Qt.CTRL + Qt.Key_E)
        self.actionAlignCenter.setCheckable(True)
        self.actionAlignCenter.setPriority(QAction.LowPriority)

        self.actionAlignRight.setShortcut(Qt.CTRL + Qt.Key_R)
        self.actionAlignRight.setCheckable(True)
        self.actionAlignRight.setPriority(QAction.LowPriority)

        self.actionAlignJustify.setShortcut(Qt.CTRL + Qt.Key_J)
        self.actionAlignJustify.setCheckable(True)
        self.actionAlignJustify.setPriority(QAction.LowPriority)

        tb.addActions(grp.actions())
        menu.addActions(grp.actions())
        menu.addSeparator()

        pix = QPixmap(16, 16)
        pix.fill(Qt.black)
        self.actionTextColor = QAction(QIcon(pix), "&Color...", self,
                triggered=self.textColor)
        tb.addAction(self.actionTextColor)
        menu.addAction(self.actionTextColor)

        tb = QToolBar(self)
        tb.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea)
        tb.setWindowTitle("Format Actions")
        self.addToolBarBreak(Qt.TopToolBarArea)
        self.addToolBar(tb)

        comboStyle = QComboBox(tb)
        tb.addWidget(comboStyle)
        comboStyle.addItem("Standard")
        comboStyle.addItem("Bullet List (Disc)")
        comboStyle.addItem("Bullet List (Circle)")
        comboStyle.addItem("Bullet List (Square)")
        comboStyle.addItem("Ordered List (Decimal)")
        comboStyle.addItem("Ordered List (Alpha lower)")
        comboStyle.addItem("Ordered List (Alpha upper)")
        comboStyle.addItem("Ordered List (Roman lower)")
        comboStyle.addItem("Ordered List (Roman upper)")
        comboStyle.activated.connect(self.textStyle)

        self.comboFont = QFontComboBox(tb)
        tb.addWidget(self.comboFont)
        self.comboFont.activated[str].connect(self.textFamily)

        self.comboSize = QComboBox(tb)
        self.comboSize.setObjectName("comboSize")
        tb.addWidget(self.comboSize)
        self.comboSize.setEditable(True)

        db = QFontDatabase()
        for size in db.standardSizes():
            self.comboSize.addItem("%s" % (size))

        self.comboSize.activated[str].connect(self.textSize)
        self.comboSize.setCurrentIndex(
                self.comboSize.findText(
                        "%s" % (QApplication.font().pointSize())))
Esempio n. 22
0
class LibraryManagerPanel(QDockWidget):
    def __init__(self, task_executor):
        super().__init__()
        self.lib_selector = QComboBox()
        self.libraries = self._setup_libraries(self.lib_selector)
        self.lib_selector.currentIndexChanged.connect(self._lib_changed)
        self.info_ico_lbl = QLabel("ico")
        self.info_lbl = QLabel("Library Information")
        self.info_lbl.setStyleSheet('font-size: 8pt;')
        self.task_executor = task_executor
        self.group_manager = LibraryGroupingManager()
        self.treeView = QTreeView()

        self.toolbar = QToolBar()
        self.refresh_action = CommonUtils.create_toolbar_action(
            "Refresh/Rescan this Library", QIcon.fromTheme("view-refresh"),
            self.refresh)
        self.edit_action = CommonUtils.create_toolbar_action(
            "Configure this Library", QIcon.fromTheme("preferences-system"),
            self.edit)
        self.delete_action = CommonUtils.create_toolbar_action(
            "Delete this Library", QIcon.fromTheme("list-remove"), self.delete)
        self.add_action = CommonUtils.create_toolbar_action(
            "Add a new Library", QIcon.fromTheme("list-add"), self.add)

        self._init_ui()

    def _init_ui(self):
        h_layout = QHBoxLayout()
        h_layout.addWidget(self.info_ico_lbl)
        h_layout.addWidget(self.lib_selector, 1)
        dummy = QWidget()
        dummy.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.toolbar.addWidget(dummy)
        self.toolbar.addActions([
            self.refresh_action, self.edit_action, self.delete_action,
            self.add_action
        ])
        self.toolbar.setContentsMargins(0, 0, 0, 0)
        self.toolbar.setIconSize(QSize(16, 16))

        layout = QVBoxLayout()
        layout.setContentsMargins(5, 0, 0, 0)
        layout.setMenuBar(self.toolbar)
        layout.addLayout(h_layout)
        layout.addWidget(self.info_lbl)
        layout.addWidget(self.group_manager)
        layout.addWidget(self.treeView, 1)
        container = QWidget()
        container.setLayout(layout)
        self.setFeatures(QDockWidget.DockWidgetFloatable
                         | QDockWidget.DockWidgetClosable)
        self.setWidget(container)
        self.setWindowTitle("Library Manager")
        if self.lib_selector.count() > 0:
            self._lib_changed()

    def refresh(self):
        lib = self.libraries[self.lib_selector.currentText()]
        task_name = f"Refreshing {lib['name']}"
        task_id = f"{time.time()} {task_name}"
        self.task_executor.execute_with_progress(
            LibraryManagement.refresh_library, (lib, task_id),
            (task_name, task_id))

    def delete(self):
        lib_name = self.lib_selector.currentText()
        choice = QMessageBox.question(
            self, "Confirm Library Deletion",
            f"Are you sure you want to delete {lib_name}. "
            f"Please note this action cannot be undone")
        if choice == QMessageBox.Yes:
            lib = self.libraries.pop(lib_name)
            self.task_executor.execute(LibraryManagement.delete_library,
                                       (lib, ))
            self.lib_selector.removeItem(self.lib_selector.currentIndex())

    def edit(self):
        library = self.libraries[self.lib_selector.currentText()]
        dialog = LibraryEditorPanel(library)
        result = dialog.exec()
        if result == QDialog.Accepted:
            self.libraries.pop(self.lib_selector.currentText())
            lib_new = dialog.get_library()
            self.libraries[self.lib_selector.currentText()] = lib_new
            task_name = f"Adding {lib_new['name']}"
            task_id = f"{time.time()} {task_name}"
            self.task_executor.execute(LibraryManagement.update_library,
                                       (lib_new, ))
            self._lib_changed()

    def add(self):
        dialog = LibraryEditorPanel()
        result = dialog.exec()
        if result == QDialog.Accepted:
            lib = dialog.get_library()
            self.libraries[lib['name']] = lib
            self.lib_selector.addItem(lib['name'])
            task_name = f"Adding {lib['name']}"
            task_id = f"{time.time()} {task_name}"
            self.task_executor.execute_with_progress(
                LibraryManagement.create_library,
                (lib['name'], lib['type'], lib['dirs'], None, task_id),
                (task_name, task_id))

    def _lib_changed(self):
        library = self.libraries[self.lib_selector.currentText()]
        info_ico = QIcon.fromTheme(
            LibraryManagement.Library_Types[library["type"]]["icon"])
        self.info_ico_lbl.setPixmap(info_ico.pixmap(28, 28))
        updated = 'Not updated'
        if library.__contains__('updated'):
            updated = f"Updated on {library['updated']}"
        dir_count = len(library['dirs'])
        lib_dir_details = f"{dir_count} directories"
        if dir_count == 1:
            lib_dir_details = f"{dir_count} directory"
        self.info_lbl.setText(
            f"Created on {library['created']}<br>{updated}<br>{lib_dir_details}"
        )
        self.group_manager.update_grouping(
            LibraryManagement.get_group_keys(library["type"]))

    @staticmethod
    def _setup_libraries(lib_combo_selector):
        libraries = LibraryManagement.get_all_libraries()
        lib_lookup = {}
        for lib_type in libraries:
            for lib in libraries[lib_type]:
                key = f"[{lib_type}] {lib['name']}"
                lib_lookup[key] = lib
                lib_combo_selector.addItem(key)
        return lib_lookup
Esempio n. 23
0
class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setup_ui()

        # UI connections
        self.action_open_amazon_view.triggered.connect(self.open_amazon)
        self.action_open_vendor_view.triggered.connect(self.open_vendor)
        self.action_open_operations.triggered.connect(self.open_operations)
        self.action_edit_vendors.triggered.connect(self.on_edit_vendors)

        self.tabs.tabCloseRequested.connect(self.close_tab)
        self.tabs.currentChanged.connect(self.tab_changed)

        self.current_tab = None

        # Set up the database connection.
        self.dbengine = create_engine('sqlite:///prowler.db')
        self.dbsession = Session(bind=self.dbengine)

        Base.metadata.create_all(self.dbengine)

        amazon = Vendor(id=0, name='Amazon', url='www.amazon.com')
        self.dbsession.add(self.dbsession.merge(amazon))
        self.dbsession.commit()

    def setup_ui(self):
        """Initialize the main window's UI components"""
        # Scale the window to the size of the screen
        desktop = QApplication.desktop()
        size = desktop.availableGeometry()

        self.resize(size.width() * .9, size.height() * .9)

        # Set up the toolbar
        self.toolBar = QToolBar(self)
        self.addToolBar(self.toolBar)

        # Create toolbar actions
        self.action_open_amazon_view = QAction(QIcon('icons/amazon.png'), 'Open Amazon view', self)
        self.action_open_vendor_view = QAction(QIcon('icons/folder.png'), 'Open Vendor view', self)
        self.action_open_operations = QAction(QIcon('icons/ops_view.png'), 'Open Operations', self)
        self.action_edit_vendors = QAction(QIcon('icons/vendor.png'), 'Edit vendors', self)

        # Add actions and separators to the toolbar
        self.toolBar.addActions([self.action_open_amazon_view,
                                self.action_open_vendor_view,
                                self.action_open_operations])

        self.toolBar.addSeparator()
        self.toolBar.addAction(self.action_edit_vendors)
        self.toolBar.addSeparator()

        # Create the central tab widget
        self.tabs = QTabWidget(self)
        self.tabs.setDocumentMode(True)
        self.tabs.setTabsClosable(True)

        self.setCentralWidget(self.tabs)

    def on_edit_vendors(self):
        """Show the Edit Vendors dialog."""
        dialog = EditVendorDialog(parent=self)
        dialog.exec()

    def open_amazon(self):
        """Open a new AmazonView."""
        view = AmazonView(self)
        idx = self.tabs.addTab(view, 'Amazon')
        self.tabs.setCurrentIndex(idx)

    def open_vendor(self):
        """Open a new VendorView."""
        view = VendorView(self)
        idx = self.tabs.addTab(view, 'Sources')
        self.tabs.setCurrentIndex(idx)

    def open_operations(self):
        """Open, or re-focus, the Operations view."""
        # We only want one operations view open at a time
        for i in range(self.tabs.count()):
            if isinstance(self.tabs.widget(i), OperationsView):
                self.tabs.setCurrentIndex(i)
                return

        view = OperationsView(self)
        idx = self.tabs.addTab(view, 'Operations')
        self.tabs.setCurrentIndex(idx)

    def close_tab(self, index):
        """Respond to a tabCloseRequested signal."""
        self.tabs.removeTab(index)

    def tab_changed(self, index):
        """Re-populate the toolbar with the actions specific to the new tab."""
        if self.current_tab:
            for action in self.current_tab.toolbar_actions:
                self.toolBar.removeAction(action)

        self.current_tab = self.tabs.currentWidget()

        if self.current_tab:
            for action in self.current_tab.toolbar_actions:
                self.toolBar.addAction(action)
Esempio n. 24
0
class MainDesign(QMainWindow):
    def setupUI(self):
        # setting window
        self.showMaximized()
        self.setMouseTracking(True)

        scroll = QScrollArea(self)
        centWidget = QWidget(self)
        paintWidget = PaintWidget(self, self)

        # setup layout with image on  the center
        vbox = QHBoxLayout()
        vbox.addStretch(1)

        if self.defaultPix:
            paintWidget.setFixedSize(self.defaultPix.size())
        else:
            paintWidget.setFixedSize(self.size())

        vbox.addWidget(paintWidget)
        vbox.addStretch(1)

        centWidget.setLayout(vbox)
        scroll.setWidget(paintWidget)

        self.setCentralWidget(scroll)
        self.setWindowTitle('Paint')

        # create menu
        menu = self.menuBar()
        fileMenu = menu.addMenu('File')

        commandsGroup = QActionGroup(self)

        self.saveAction = QAction('Save', self)
        self.saveAction.setShortcut('Ctrl+S')
        fileMenu.addAction(self.saveAction)

        self.saveBufferAction = QAction('Save to buffer', self)
        self.saveBufferAction.setShortcut('Ctrl+Shift+S')
        fileMenu.addAction(self.saveBufferAction)

        self.saveServerAction = QAction('Save on server', self)
        self.saveServerAction.setShortcut('Ctrl+Alt+S')
        fileMenu.addAction(self.saveServerAction)

        self.clearAction = QAction('Clear', self)
        self.clearAction.setShortcut('Ctrl+F')
        fileMenu.addAction(self.clearAction)

        self.unExecuteAction = QAction('Unexecute', self)
        self.unExecuteAction.setShortcut('Ctrl+Z')
        fileMenu.addAction(self.unExecuteAction)

        self.quitAction = QAction('Quit', self)
        self.quitAction.setShortcut('Ctrl+Q')
        fileMenu.addAction(self.quitAction)

        self.LineAction = QAction('Line', self)
        self.LineAction.setIcon(QIcon('./Images/line.png'))
        self.LineAction.setCheckable(True)
        self.LineAction.setChecked(True)
        commandsGroup.addAction(self.LineAction)

        self.RectAction = QAction('Rect', self)
        self.RectAction.setIcon(QIcon('./Images/rect.png'))
        self.RectAction.setCheckable(True)
        commandsGroup.addAction(self.RectAction)

        self.CircleAction = QAction('Ellipse', self)
        self.CircleAction.setIcon(QIcon('./Images/ellipse.png'))
        self.CircleAction.setCheckable(True)
        commandsGroup.addAction(self.CircleAction)

        self.ArrowAction = QAction('Arrow', self)
        self.ArrowAction.setCheckable(True)
        self.ArrowAction.setIcon(QIcon('./Images/arrow.png'))
        commandsGroup.addAction(self.ArrowAction)

        self.PenAction = QAction('Pen', self)
        self.PenAction.setIcon(QIcon('./Images/poly.png'))
        self.PenAction.setCheckable(True)
        commandsGroup.addAction(self.PenAction)

        self.PencilAction = QAction('Pencil', self)
        self.PencilAction.setCheckable(True)
        self.PencilAction.setIcon(QIcon('./Images/pencil.png'))
        commandsGroup.addAction(self.PencilAction)

        self.ImageAction = QAction('Image', self)
        self.ImageAction.setCheckable(True)
        self.ImageAction.setIcon(QIcon('./Images/image.png'))
        commandsGroup.addAction(self.ImageAction)

        self.TextAction = QAction('Text', self)
        self.TextAction.setCheckable(True)
        self.TextAction.setIcon(QIcon('./Images/text.png'))
        commandsGroup.addAction(self.TextAction)

        self.EditAction = QAction('Edit', self)
        self.EditAction.setCheckable(True)
        self.EditAction.setIcon(QIcon('./Images/move.png'))
        commandsGroup.addAction(self.EditAction)

        self.deleteAction = QAction('Delete', self)
        self.deleteAction.setDisabled(True)
        self.deleteAction.setShortcut('Delete')

        self.copyAction = QAction('Copy', self)
        self.copyAction.setDisabled(True)
        self.copyAction.setShortcut(QKeySequence('Ctrl+C'))

        self.pasteAction = QAction('Paste', self)
        self.pasteAction.setShortcut(QKeySequence('Ctrl+V'))

        menu.addAction(self.deleteAction)
        menu.addAction(self.copyAction)
        menu.addAction(self.pasteAction)

        self.commandsToolbar = QToolBar('Commands')
        self.commandsToolbar.setMovable(False)
        self.commandsToolbar.addActions(commandsGroup.actions())

        self.setToolbar(NoneToolbar('Context'))
        self.contextToolbar.setMovable(False)
        self.contextToolbar.destroy()

        self.addToolBar(Qt.LeftToolBarArea, self.commandsToolbar)
        self.addToolBar(Qt.TopToolBarArea, self.contextToolbar)
Esempio n. 25
0
class Window(QMainWindow):
    def __init__(self,
                 x=DEFAULT_X,
                 y=DEFAULT_Y,
                 w=DEFAULT_WIDTH,
                 h=DEFAULT_HEIGHT):
        super(Window, self).__init__()
        self.setGeometry(x, y, w, h)
        self.setWindowTitle(WINDOW_NAME)
        self.setWindowIcon(QIcon(MAIN_ICON))
        self.home()

    def home(self):

        self.folderLoader = FolderLoader()

        self.saved = True

        #Parameters
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)

        self.createMainMenu()

        self.canvas = Canvas(parent=self)

        self.scrollArea = QScrollArea()
        self.scrollArea.setWidget(self.canvas)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setStyleSheet(STYLE_SHEET)

        self.labelCoordinates = QLabel('')
        self.statusBar.addPermanentWidget(self.labelCoordinates)

        self.toolbar = QToolBar(TOOLBAR_NAME, self)
        self.toolbar.setStyleSheet(STYLE_SHEET)
        self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.addToolBar(Qt.LeftToolBarArea, self.toolbar)

        self.mapper = QSignalMapper()
        self.createColorComboBox()
        self.createToolbarActions()
        self.createFileDock()

        self.setCentralWidget(self.scrollArea)
        self.update()
        self.showMaximized()

    def createMainMenu(self):

        #Main Menu
        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu(FILE_MENU_TEXT)
        editMenu = mainMenu.addMenu(EDIT_MENU_TEXT)
        helpMenu = mainMenu.addMenu(HELP_MENU_TEXT)

        #File Menu Actions
        openFileAction = self.createAction(OPEN_FILE_TEXT, OPEN_FILE_SHORTCUT,
                                           self.openFile)
        openFolderAction = self.createAction(OPEN_FOLDER_TEXT,
                                             OPEN_FOLDER_SHORTCUT,
                                             self.openFolder)
        saveAction = self.createAction(SAVE_TEXT, SAVE_SHORTCUT, self.save)

        fileMenu.addActions([openFileAction, openFolderAction, saveAction])

        #Edit Menu Actions
        copyAction = self.createAction(COPY_TEXT, COPY_SHORTCUT, self.copy)
        pasteAction = self.createAction(PASTE_TEXT, PASTE_SHORTCUT, self.paste)

        editMenu.addActions([copyAction, pasteAction])

        #Help Menu Actions
        howToUseAction = self.createAction(HOW_TO_USE_TEXT, EMPTY,
                                           self.howToUse)
        helpMenu.addActions([howToUseAction])

    def createToolbarActions(self):

        self.toolbar.addSeparator()

        #Polygons
        drawPolygonAction = self.createActionWithIcon(DRAW_POLYGON_ICON,
                                                      DRAW_POLYGON_TEXT,
                                                      DRAW_POLYGON_SHORTCUT,
                                                      self.setDrawingState,
                                                      DRAW_POLYGON_TOOLTIP)

        deletePolygonAction = self.createActionWithIcon(
            DELETE_POLYGON_ICON, DELETE_POLYGON_TEXT, DELETE_POLYGON_SHORTCUT,
            self.canvas.deletePolygon, DELETE_POLYGON_TOOLTIP)

        self.toolbar.addActions([drawPolygonAction, deletePolygonAction])
        self.toolbar.addSeparator()

        ##Controls
        addControlAction = self.createActionWithIcon(
            ADD_CONTROL_ICON, ADD_CONTROL_TEXT, ADD_CONTROL_SHORTCUT,
            self.canvas.addControlToSelectedPolygon, ADD_CONTROL_TOOLTIP)

        deleteControlAction = self.createActionWithIcon(
            DELETE_CONTROL_ICON, DELETE_CONTROL_TEXT, DELETE_CONTROL_SHORTCUT,
            self.canvas.deleteControlFromSelectedPolygon,
            DELETE_CONTROL_TOOLTIP)

        self.toolbar.addActions([addControlAction, deleteControlAction])
        self.toolbar.addSeparator()

        nextImageAction = self.createActionWithIcon(NEXT_IMAGE_ICON,
                                                    NEXT_IMAGE_TEXT,
                                                    NEXT_IMAGE_SHORTCUT,
                                                    self.nextImage,
                                                    NEXT_IMAGE_TOOLTIP)

        previousImageAction = self.createActionWithIcon(
            PREVIOUS_IMAGE_ICON, PREVIOUS_IMAGE_TEXT, PREVIOUS_IMAGE_SHORTCUT,
            self.previousImage, PREVIOUS_IMAGE_TOOLTIP)

        self.toolbar.addActions([nextImageAction, previousImageAction])

        self.copyPolygonsCheckbox = QCheckBox()
        self.copyPolygonsCheckbox.setStyleSheet(STYLE_SHEET)
        self.toolbar.addWidget(self.copyPolygonsCheckbox)

        copyPolygonsLabel = QLabel(COPY_POLGONS_FOR_NEXT_IMAGE)
        copyPolygonsLabel.setAlignment(Qt.AlignCenter)
        self.toolbar.addWidget(copyPolygonsLabel)

        self.hideControlsCheckBox = QCheckBox()
        self.hideControlsCheckBox.setStyleSheet(STYLE_SHEET)
        self.hideControlsCheckBox.stateChanged.connect(
            self.canvas.changeHideControlsState)
        self.toolbar.addWidget(self.hideControlsCheckBox)

        hideControlsLabel = QLabel(HIDE_CONTROLS_TEXT)
        hideControlsLabel.setAlignment(Qt.AlignCenter)
        self.toolbar.addWidget(hideControlsLabel)

    def createColorComboBox(self):
        colorLabel = QLabel("Polygon Color")
        colorLabel.setAlignment(Qt.AlignCenter)
        self.toolbar.addWidget(colorLabel)

        self.colorComboBox = QComboBox()
        self.colorComboBox.setStyleSheet(STYLE_SHEET)
        self.colorComboBox.activated[int].connect(self.changeColor)
        self.toolbar.addWidget(self.colorComboBox)
        model = self.colorComboBox.model()

        for i in range(len(POLY_COLORS_TEXT)):
            colorText = POLY_COLORS_TEXT[i]
            colorStyle = POLY_COLORS_STYLE[i]
            item = QStandardItem(colorText)
            item.setBackground(QColor(colorStyle))
            item.setData(colorStyle)
            model.appendRow(item)

        self.customColor = self.createActionWithIcon(CUSTOM_COLOR_ICON,
                                                     CUSTOM_COLOR_TEXT, EMPTY,
                                                     self.addCustomColor,
                                                     CUSTOM_COLOR_TOOLTIP)
        self.toolbar.addAction(self.customColor)

        self.changeColor = self.createActionWithIcon(
            CHANGE_COLOR_ICON, CHANGE_COLOR_TEXT, EMPTY,
            self.canvas.askForColorChange, CHANGE_COLOR_TOOLTIP)
        self.toolbar.addAction(self.changeColor)

    def createFileDock(self):
        self.fileDock = QDockWidget(FILE_DOCK_TITLE, self)

        self.fileListWidget = QListWidget()
        self.fileListWidget.setStyleSheet(STYLE_SHEET)
        self.fileListWidget.itemDoubleClicked.connect(self.fileItemChanged)
        fileListLayout = QVBoxLayout()
        fileListLayout.addWidget(self.fileListWidget)
        fileListContainter = QWidget()
        fileListContainter.setLayout(fileListLayout)

        self.fileDock.setWidget(fileListContainter)
        self.fileDock.setStyleSheet(STYLE_SHEET)
        self.fileDock.setFeatures(QDockWidget.DockWidgetFloatable
                                  | QDockWidget.DockWidgetMovable)

        self.addDockWidget(Qt.RightDockWidgetArea, self.fileDock)

    def createAction(self, text, shortcut, triggered=None):
        action = QAction(text, self)
        action.setShortcut(shortcut)
        action.setToolTip(EMPTY)
        action.triggered.connect(triggered)

        return action

    def createActionWithIcon(self,
                             iconPath,
                             text,
                             shortcut,
                             triggered,
                             tooltip=""):
        action = QAction(QIcon(iconPath), text, self)
        action.triggered.connect(triggered)
        action.setToolTip(tooltip)
        action.setShortcut(shortcut)

        return action

    def freeDrawCheckBoxChanged(self):
        if (self.freeDrawCheckbox.checkState() > 0):
            self.canvas.setState(FREE_DRAW)
        else:
            self.canvas.setState(MOVE_CONTROLS)

    def fileItemChanged(self):
        filepath = self.fileListWidget.selectedItems()[0].text()
        self.canvas.loadImage(filepath)

    def nextImage(self):
        if (self.checkContinue()):
            image = self.folderLoader.getNextImageFilename()
            if (image is not None):
                copyPolygons = self.copyPolygonsCheckbox.checkState() > 0
                self.canvas.loadImage(image, copyPolygons)
                self.saved = True

                fileWidgetItem = self.fileListWidget.item(
                    self.folderLoader.index)
                if (fileWidgetItem is not None):
                    fileWidgetItem.setSelected(True)

    def previousImage(self):
        if (self.checkContinue()):
            image = self.folderLoader.getPreviousImageFilename()

            if (image is not None):
                self.canvas.loadImage(image)
                self.saved = True

                fileWidgetItem = self.fileListWidget.item(
                    self.folderLoader.index)
                if (fileWidgetItem is not None):
                    fileWidgetItem.setSelected(True)

    def checkContinue(self):
        if (not self.saved):
            choice = QMessageBox.question(self, NOT_SAVED_TITLE,
                                          NOT_SAVED_TEXT)
            if (choice == QMessageBox.Yes):
                return True
            else:
                return False
        else:
            return True

    def addColoredPolygon(self, color):
        self.canvas.addPolygon(color)
        self.saved = False

    def addCustomColor(self):
        color = QColorDialog.getColor()

        if (QColor.isValid(color)):
            self.canvas.setColor(color)
            self.saved = False

    def calculateCenter(self):
        self.centerX = self.rect().width() // 2
        self.centerY = self.rect().height() // 2
        self.center = QPoint(self.centerX, self.centerY)

    def resizeEvent(self, event):
        self.calculateCenter()
        self.canvas.resizedParent()
        self.canvas.adjustSize()

    def keyPressEvent(self, event):
        if (event.key() == Qt.Key_Escape):
            self.canvas.setState(MOVE_CONTROLS)
        else:
            for number in NUMBERS:
                if (event.text() == number):
                    self.colorComboBox.setCurrentIndex(int(number) - 1)
                    self.colorComboBox.activated.emit(int(number) - 1)

    def openFile(self):
        filename, _ = QFileDialog.getOpenFileName(self, OPEN_FILE_DIALOG_TEXT,
                                                  EMPTY,
                                                  OPEN_FILE_DIALOG_FILTER)
        if any(x in filename for x in OPEN_FOLDER_FILTERS):
            self.folderLoader.loadSingleFile(filename)
            self.canvas.loadImage(filename)

    def openFolder(self):
        folder = QFileDialog.getExistingDirectory(self,
                                                  OPEN_FOLDER_DIALOG_TEXT)
        if (folder is not EMPTY):
            firstImage = self.folderLoader.loadFolder(folder)
            self.canvas.loadImage(firstImage)

            for imagePath in self.folderLoader.imagesInFolder:
                self.fileListWidget.addItem(QListWidgetItem(imagePath))

    def save(self):
        self.saved = True
        self.canvas.saveImage()

    def setDrawingState(self):
        self.canvas.setState(DRAW_POLYGON)

    def changeColor(self, index):
        color = QColor(POLY_COLORS_STYLE[index])
        self.colorComboBox.setStyleSheet(
            f'background-color: {POLY_COLORS_STYLE[index]}')
        self.canvas.setColor(color)

    def howToUse(self):
        webbrowser.open(HELP_PAGE_WEBSITE)

    def copy(self):
        self.canvas.copyPolygon()

    def paste(self):
        self.canvas.pastePolygon()