def on_show_prompt_instance_delay_menu(self):
        prompt_instance_state = cmds.optionVar(query='MTT_prompt_instance_state')

        if prompt_instance_state == PROMPT_INSTANCE_WAIT:
            elapsed_time = time() - cmds.optionVar(query='MTT_prompt_instance_suspend')
            if elapsed_time > PROMPT_INSTANCE_WAIT_DURATION:
                prompt_instance_state = PROMPT_INSTANCE_ASK
                cmds.optionVar(iv=['MTT_prompt_instance_state', prompt_instance_state])
            else:
                mtt_log('Remaining %.2fs' % (PROMPT_INSTANCE_WAIT_DURATION - elapsed_time))
        elif prompt_instance_state == PROMPT_INSTANCE_SESSION:
            if 'mtt_prompt_session' not in __main__.__dict__:
                prompt_instance_state = PROMPT_INSTANCE_ASK
                cmds.optionVar(iv=['MTT_prompt_instance_state', prompt_instance_state])

        self.instance_menu.clear()

        prompt_delay = QActionGroup(self)
        prompt_delay.setExclusive(True)
        for i in range(len(PROMPT_INSTANCE_STATE.keys())):
            current_delay_action = QAction(PROMPT_INSTANCE_STATE[i], prompt_delay)
            current_delay_action.setCheckable(True)
            current_delay_action.setChecked(prompt_instance_state == i)
            current_delay_action.triggered.connect(
                partial(self.view.on_choose_instance_delay, i, prompt=i != 0))
            self.instance_menu.addAction(current_delay_action)
    def on_show_prompt_instance_delay_menu(self):
        prompt_instance_state = cmds.optionVar(
            query='MTT_prompt_instance_state')

        if prompt_instance_state == PROMPT_INSTANCE_WAIT:
            elapsed_time = time() - cmds.optionVar(
                query='MTT_prompt_instance_suspend')
            if elapsed_time > PROMPT_INSTANCE_WAIT_DURATION:
                prompt_instance_state = PROMPT_INSTANCE_ASK
                cmds.optionVar(
                    iv=['MTT_prompt_instance_state', prompt_instance_state])
            else:
                mtt_log('Remaining %.2fs' %
                        (PROMPT_INSTANCE_WAIT_DURATION - elapsed_time))
        elif prompt_instance_state == PROMPT_INSTANCE_SESSION:
            if 'mtt_prompt_session' not in __main__.__dict__:
                prompt_instance_state = PROMPT_INSTANCE_ASK
                cmds.optionVar(
                    iv=['MTT_prompt_instance_state', prompt_instance_state])

        self.instance_menu.clear()

        prompt_delay = QActionGroup(self)
        prompt_delay.setExclusive(True)
        for i in range(len(PROMPT_INSTANCE_STATE.keys())):
            current_delay_action = QAction(PROMPT_INSTANCE_STATE[i],
                                           prompt_delay)
            current_delay_action.setCheckable(True)
            current_delay_action.setChecked(prompt_instance_state == i)
            current_delay_action.triggered.connect(
                partial(self.view.on_choose_instance_delay, i, prompt=i != 0))
            self.instance_menu.addAction(current_delay_action)
Ejemplo n.º 3
0
 def showContextMenu(self, point):
     'Show the Columns context menu'
     if self.model() is None:
         return
     
     # If we are viewing a proxy model, skip to the source model
     mdl = self.model()
     while isinstance(mdl, QAbstractProxyModel):
         mdl = mdl.sourceModel()
     
     if mdl is None or not hasattr(mdl, 'columns'):
         return
     
     # Generate and show the Menu
     m = QMenu()
     for i in range(len(mdl.columns)):
         c = mdl.columns[i]
         if c.internal:
             continue
         
         a = QAction(mdl.headerData(i, Qt.Horizontal, Qt.DisplayRole), m)
         a.setCheckable(True)
         a.setChecked(not self.isColumnHidden(i))
         a.triggered.connect(partial(self.showHideColumn, c=i, s=self.isColumnHidden(i)))
         m.addAction(a)
         
     m.exec_(self.header().mapToGlobal(point))
    def on_show_debug_menu(self):
        self.debug_menu.clear()

        if self.is_master_cmd or self.power_user:
            power_user_mode = QAction('Power User Mode', self)
            power_user_mode.setCheckable(True)
            power_user_mode.setChecked(MTTSettings.value('powerUser'))
            power_user_mode.triggered.connect(self.__on_toggle_power_user)
            self.debug_menu.addAction(power_user_mode)
            self.is_master_cmd = False

            self.debug_menu.addSeparator()

        open_pref_folder_action = QAction('Open Preferences Folder', self)
        open_pref_folder_action.setStatusTip('Open MTT preference folder')
        open_pref_folder_action.triggered.connect(
            self.on_open_preference_folder)
        self.debug_menu.addAction(open_pref_folder_action)

        self.debug_menu.addSeparator()

        database_dump_csv = QAction('Dump Database as CSV', self)
        database_dump_csv.triggered.connect(self.view.model.database_dump_csv)
        self.debug_menu.addAction(database_dump_csv)

        database_dump_sql = QAction('Dump Database as SQL', self)
        database_dump_sql.triggered.connect(self.view.model.database_dump_sql)
        self.debug_menu.addAction(database_dump_sql)

        self.debug_menu.addSeparator()

        support_info = QMenu(self)
        support_info.setTitle('Supported Node Type')
        support_info.aboutToShow.connect(self.on_show_supported_type)
        self.debug_menu.addMenu(support_info)
    def _create_theme_menu(self):
        theme_menu = QMenu(self)
        theme_menu.setTitle('Buttons Theme')
        theme_menu.setTearOffEnabled(True)
        theme_menu.setWindowTitle(TAG)
        theme_actions = QActionGroup(self)
        theme_actions.setExclusive(True)
        # create ordered theme list
        custom_order_theme = sorted(THEMES.iterkeys())
        custom_order_theme.remove('Maya Theme')
        custom_order_theme.insert(0, 'Maya Theme')
        default_item = True
        for theme in custom_order_theme:
            current_theme_action = QAction(theme, theme_actions)
            current_theme_action.setCheckable(True)
            current_theme_action.setChecked(
                MTTSettings.value('theme', 'Maya Theme') == theme)
            current_theme_action.triggered.connect(self.on_change_theme)
            theme_menu.addAction(current_theme_action)

            if default_item:
                theme_menu.addSeparator()
                default_item = False

        return theme_menu
Ejemplo n.º 6
0
    def setup_ui(self):
        """ Setup the UI for the window.

        """
        central_widget = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.clock_view)
        layout.addWidget(self.message_view)
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        menubar = self.menuBar()

        file_menu = QMenu('File')

        preferences_action = QAction('Preferences', file_menu)
        preferences_action.triggered.connect(self.on_preferences_triggered)

        quit_action = QAction('Quit', file_menu)
        quit_action.triggered.connect(self.on_quit_triggered)

        file_menu.addAction(preferences_action)
        file_menu.addAction(quit_action)
        menubar.addMenu(file_menu)

        view_menu = QMenu('View')

        fullscreen_action = QAction('Fullscreen', view_menu)
        fullscreen_action.setCheckable(True)
        fullscreen_action.setChecked(Config.get('FULLSCREEN', True))
        fullscreen_action.setShortcut('Ctrl+Meta+F')
        fullscreen_action.toggled.connect(self.on_fullscreen_changed)

        view_menu.addAction(fullscreen_action)
        menubar.addMenu(view_menu)
    def _create_theme_menu(self):
        theme_menu = QMenu(self)
        theme_menu.setTitle('Buttons Theme')
        theme_menu.setTearOffEnabled(True)
        theme_menu.setWindowTitle(TAG)
        theme_actions = QActionGroup(self)
        theme_actions.setExclusive(True)
        # create ordered theme list
        custom_order_theme = sorted(THEMES.iterkeys())
        custom_order_theme.remove('Maya Theme')
        custom_order_theme.insert(0, 'Maya Theme')
        default_item = True
        for theme in custom_order_theme:
            current_theme_action = QAction(theme, theme_actions)
            current_theme_action.setCheckable(True)
            current_theme_action.setChecked(
                MTTSettings.value('theme', 'Maya Theme') == theme)
            current_theme_action.triggered.connect(self.on_change_theme)
            theme_menu.addAction(current_theme_action)

            if default_item:
                theme_menu.addSeparator()
                default_item = False

        return theme_menu
    def on_show_debug_menu(self):
        self.debug_menu.clear()

        if self.is_master_cmd or self.power_user:
            power_user_mode = QAction('Power User Mode', self)
            power_user_mode.setCheckable(True)
            power_user_mode.setChecked(MTTSettings.value('powerUser'))
            power_user_mode.triggered.connect(self.__on_toggle_power_user)
            self.debug_menu.addAction(power_user_mode)
            self.is_master_cmd = False

            self.debug_menu.addSeparator()

        open_pref_folder_action = QAction('Open Preferences Folder', self)
        open_pref_folder_action.setStatusTip('Open MTT preference folder')
        open_pref_folder_action.triggered.connect(self.on_open_preference_folder)
        self.debug_menu.addAction(open_pref_folder_action)

        self.debug_menu.addSeparator()

        database_dump_csv = QAction('Dump Database as CSV', self)
        database_dump_csv.triggered.connect(self.view.model.database_dump_csv)
        self.debug_menu.addAction(database_dump_csv)

        database_dump_sql = QAction('Dump Database as SQL', self)
        database_dump_sql.triggered.connect(self.view.model.database_dump_sql)
        self.debug_menu.addAction(database_dump_sql)

        self.debug_menu.addSeparator()

        support_info = QMenu(self)
        support_info.setTitle('Supported Node Type')
        support_info.aboutToShow.connect(self.on_show_supported_type)
        self.debug_menu.addMenu(support_info)
Ejemplo n.º 9
0
 def create_rev_action(self, repo, *revs):
     action = QAction(self.revs_menu)
     action.revs = revs
     action.setText(', '.join(str(rev) for rev in revs))
     action.setCheckable(True)
     action.setActionGroup(self.rev_actions)
     action.triggered.connect(self._revs_action_triggered)
     return action
Ejemplo n.º 10
0
        def add_action(lbl, tip, cmd, checkable=False, checked=False):
            a = QAction(lbl, self)
            a.setStatusTip(tip)
            a.triggered.connect(cmd)
            if checkable:
                a.setCheckable(True)
                a.setChecked(checked)

            return a
        def add_action(lbl, tip, cmd, checkable=False, checked=False):
            a = QAction(lbl, self)
            a.setStatusTip(tip)
            a.triggered.connect(cmd)
            if checkable:
                a.setCheckable(True)
                a.setChecked(checked)

            return a
Ejemplo n.º 12
0
Archivo: app.py Proyecto: lite/pystut
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        #        self.setObjectName("MainWindow")
        self.resize(731, 475)
        centralwidget = QWidget(self)
        #        centralwidget.setObjectName("centralwidget")
        gridLayout = QGridLayout(centralwidget)
        #        gridLayout.setObjectName("gridLayout")
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
        #        self.textEdit.setObjectName("textEdit")
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
        #        menubar.setObjectName("menubar")
        menu_File = QMenu(menubar)
        #        menu_File.setObjectName("menu_File")
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
        #        statusbar.setObjectName("statusbar")
        self.setStatusBar(statusbar)
        actionShow_GPL = QAction(self)
        #        actionShow_GPL.setObjectName("actionShow_GPL")
        actionShow_GPL.triggered.connect(self.showGPL)
        action_About = QAction(self)
        #        action_About.setObjectName("action_About")
        action_About.triggered.connect(self.about)
        iconToolBar = self.addToolBar("iconBar.png")
        #------------------------------------------------------
        # Add icons to appear in tool bar - step 1
        actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")
        action_Close.setIcon(QIcon(":/quit.png"))
        #------------------------------------------------------
        # Show a tip on the Status Bar - step 2
        actionShow_GPL.setStatusTip("Show GPL Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
        #------------------------------------------------------
        menu_File.addAction(actionShow_GPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())

        iconToolBar.addAction(actionShow_GPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)
Ejemplo n.º 13
0
Archivo: app.py Proyecto: lite/pystut
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
#        self.setObjectName("MainWindow")
        self.resize(731, 475)
        centralwidget = QWidget(self)
#        centralwidget.setObjectName("centralwidget")
        gridLayout = QGridLayout(centralwidget)
#        gridLayout.setObjectName("gridLayout")
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
#        self.textEdit.setObjectName("textEdit")
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
#        menubar.setObjectName("menubar")
        menu_File = QMenu(menubar)
#        menu_File.setObjectName("menu_File")
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
#        statusbar.setObjectName("statusbar")
        self.setStatusBar(statusbar)
        actionShow_GPL = QAction(self)
#        actionShow_GPL.setObjectName("actionShow_GPL")
        actionShow_GPL.triggered.connect(self.showGPL)
        action_About = QAction(self)
#        action_About.setObjectName("action_About")
        action_About.triggered.connect(self.about)       
        iconToolBar = self.addToolBar("iconBar.png")
#------------------------------------------------------
# Add icons to appear in tool bar - step 1
        actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")       
        action_Close.setIcon(QIcon(":/quit.png"))
#------------------------------------------------------
# Show a tip on the Status Bar - step 2
        actionShow_GPL.setStatusTip("Show GPL Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
#------------------------------------------------------
        menu_File.addAction(actionShow_GPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())
 
        iconToolBar.addAction(actionShow_GPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)
    def on_show_supported_type(self):
        node_types = sorted(
            [n_type for (n_type, nice, attr) in MTTSettings.SUPPORTED_TYPE] +
            MTTSettings.UNSUPPORTED_TYPE)
        support_info = self.sender()
        support_info.clear()

        for node_type in node_types:
            current = QAction(node_type, self)
            current.setEnabled(False)
            current.setCheckable(True)
            current.setChecked(node_type not in MTTSettings.UNSUPPORTED_TYPE)
            support_info.addAction(current)
Ejemplo n.º 15
0
    def on_show_supported_type(self):
        node_types = sorted(
            [n_type for (n_type, nice, attr) in
             MTTSettings.SUPPORTED_TYPE] + MTTSettings.UNSUPPORTED_TYPE)
        support_info = self.sender()
        support_info.clear()

        for node_type in node_types:
            current = QAction(node_type, self)
            current.setEnabled(False)
            current.setCheckable(True)
            current.setChecked(node_type not in MTTSettings.UNSUPPORTED_TYPE)
            support_info.addAction(current)
Ejemplo n.º 16
0
Archivo: gui.py Proyecto: r3/r3tagger
 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}.png".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:
         getattr(action, signal).connect(slot)
     if checkable:
         action.setCheckable(True)
     return action
Ejemplo n.º 17
0
	def createactions(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(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:
			self.connect(action, SIGNAL(signal), slot)
		if checkable:
			action.setCheckable(True)
		return action
Ejemplo n.º 18
0
 def create_size_menu(self):
     """ Create the toolbar's buttons size menu
     """
     menu = QMenu(self)
     group = QActionGroup(self)
     sizes = (_("Tiny"), 16), (_("Small"), 32), (_("Medium"),
                                                 48), (_("Big"), 64)
     for name, size in sizes:
         action = QAction(name, menu)
         action.setCheckable(True)
         if size == self.base.toolbar_size:
             action.setChecked(True)
         action.triggered.connect(partial(self.set_btn_size, size))
         group.addAction(action)
         menu.addAction(action)
     return menu
Ejemplo n.º 19
0
    def __init__(self, parent=None):
        super(Status, self).__init__(parent)
        self.setupUi(self)
        self.base = parent

        self.wait_anim = QMovie(":/stuff/wait.gif")
        self.anim_lbl.setMovie(self.wait_anim)
        self.anim_lbl.hide()

        self.show_menu = QMenu(self)
        for i in [
                self.act_page, self.act_date, self.act_text, self.act_comment
        ]:
            self.show_menu.addAction(i)
            # noinspection PyUnresolvedReferences
            i.triggered.connect(self.on_show_items)
            i.setChecked(True)

        sort_menu = QMenu(self)
        ico_sort = QIcon(":/stuff/sort.png")
        group = QActionGroup(self)

        action = QAction(_("Date"), sort_menu)
        action.setCheckable(True)
        action.setChecked(not self.base.high_by_page)
        action.triggered.connect(self.base.set_highlight_sort)
        action.setData(False)
        group.addAction(action)
        sort_menu.addAction(action)

        action = QAction(_("Page"), sort_menu)
        action.setCheckable(True)
        action.setChecked(self.base.high_by_page)
        action.triggered.connect(self.base.set_highlight_sort)
        action.setData(True)
        group.addAction(action)
        sort_menu.addAction(action)

        sort_menu.setIcon(ico_sort)
        sort_menu.setTitle(_("Sort by"))
        self.show_menu.addMenu(sort_menu)

        self.show_items_btn.setMenu(self.show_menu)
Ejemplo n.º 20
0
    def __init__(self):
        QMainWindow.__init__(self)
        # setup ui (the pcef GenericEditor is created there using
        # the promoted widgets system)
        self.ui = simple_editor_ui.Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("PCEF - Generic Example")
        editor = self.ui.genericEditor

        # open this file
        try:
            openFileInEditor(self.ui.genericEditor, __file__)
        except:
            pass

        # install Panel where user can add its own markers
        p = UserMarkersPanel()
        editor.installPanel(p, editor.PANEL_ZONE_LEFT)

        # add a fold indicator around our class and the main
        editor.foldPanel.addIndicator(136, 141)

        # add styles actions
        allStyles = styles.getAllStyles()
        allStyles.sort()
        self.styleActionGroup = QActionGroup(self)
        for style in allStyles:
            action = QAction(unicode(style), self.ui.menuStyle)
            action.setCheckable(True)
            action.setChecked(style == "Default")
            self.styleActionGroup.addAction(action)
            self.ui.menuStyle.addAction(action)
        self.styleActionGroup.triggered.connect(
            self.on_styleActionGroup_triggered)

        # add panels actions
        allPanels = self.ui.genericEditor.panels()
        allPanels.sort()
        self.panels_actions = []
        for panel in allPanels:
            action = QAction(unicode(panel), self.ui.menuPanels)
            action.setCheckable(True)
            action.setChecked(panel.enabled)
            self.ui.menuPanels.addAction(action)
            self.panels_actions.append(action)
            action.triggered.connect(self.onPanelActionTriggered)

        # add panels actions
        allModes = self.ui.genericEditor.modes()
        allModes.sort()
        self.modes_actions = []
        for mode in allModes:
            action = QAction(unicode(mode), self.ui.menuModes)
            action.setCheckable(True)
            action.setChecked(mode.enabled)
            self.ui.menuModes.addAction(action)
            self.modes_actions.append(action)
            action.triggered.connect(self.onModeActionTriggered)
Ejemplo n.º 21
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.image_viewer = ImageView(parent=self)
        self.setCentralWidget(self.image_viewer)

        exit = QAction(QIcon.fromTheme('application-exit'), 'Exit', self)
        open_image = QAction(QIcon.fromTheme('document-open'),
                             'Open image ...', self)
        scaling = QAction(QIcon.fromTheme('transform-scale'),
                          'Scale pixmap', self)
        scaling.setCheckable(True)

        actions = self.addToolBar('Actions')
        actions.addAction(exit)
        actions.addSeparator()
        actions.addAction(open_image)

        image_viewer_actions = self.addToolBar('Image viewer')
        image_viewer_actions.addAction(scaling)

        exit.triggered.connect(QApplication.instance().quit)
        open_image.triggered.connect(self._open_image)
        scaling.triggered[bool].connect(self._update_scaling)
Ejemplo n.º 22
0
    def __init__(self):
        QMainWindow.__init__(self)
        # setup ui (the pcef PythonEditor is created in the Ui_MainWindow using
        # the promoted widgets system)
        self.ui = simple_python_editor_ui.Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("PCEF - Python Editor Example")
        self.acceptDrops()

        # open this file
        try:
            openFileInEditor(self.ui.genericEditor, __file__)
        except:
            pass

        # add styles actions
        allStyles = styles.getAllStyles()
        allStyles.sort()
        self.styleActionGroup = QActionGroup(self)
        for style in allStyles:
            action = QAction(unicode(style), self.ui.menuStyle)
            action.setCheckable(True)
            action.setChecked(style == "Default")
            self.styleActionGroup.addAction(action)
            self.ui.menuStyle.addAction(action)
        self.styleActionGroup.triggered.connect(
            self.on_styleActionGroup_triggered)

        # add panels actions
        allPanels = self.ui.genericEditor.panels()
        allPanels.sort()
        self.panels_actions = []
        for panel in allPanels:
            action = QAction(unicode(panel), self.ui.menuPanels)
            action.setCheckable(True)
            action.setChecked(panel.enabled)
            self.ui.menuPanels.addAction(action)
            self.panels_actions.append(action)
            action.triggered.connect(self.onPanelActionTriggered)

        # add panels actions
        allModes = self.ui.genericEditor.modes()
        allModes.sort()
        self.modes_actions = []
        for mode in allModes:
            action = QAction(unicode(mode), self.ui.menuModes)
            action.setCheckable(True)
            action.setChecked(mode.enabled)
            self.ui.menuModes.addAction(action)
            self.modes_actions.append(action)
            action.triggered.connect(self.onModeActionTriggered)
Ejemplo n.º 23
0
class Editor(QMainWindow):  # TODO: kill this god shit
    """Note editor"""

    def __init__(self, app, note, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.app = app
        self.note = note
        self.closed = False
        self.ui = Ui_Editor()
        self.ui.setupUi(self)
        self.setWindowIcon(get_icon())
        self.init_controls()
        self.load_note(note)
        self.update_title()
        self.mark_untouched()
        geometry = self.app.settings.value("note-geometry-%d" % self.note.id)
        if not geometry:
            geometry = self.app.settings.value("note-geometry-default")
        if geometry:
            self.restoreGeometry(geometry)
        self.resource_edit.note = note

    def init_controls(self):
        self.ui.menubar.hide()
        self.ui.resourceArea.hide()
        self.note_edit = ContentEdit(
            self, self.app, 
            self.ui.contentView, self.text_changed,
        )
        self.tag_edit = TagEdit(
            self, self.app, 
            self.ui.tags, self.mark_touched,
        )
        self.notebook_edit = NotebookEdit(
            self, self.app, 
            self.ui.notebook, self.mark_touched,
        )
        self.resource_edit = ResourceEdit(
            self, self.app, self.ui.resourceArea, 
            self.ui.resourceLabel, self.mark_touched,
        )
        self.findbar = FindBar(self)
        self.init_toolbar()

    def init_toolbar(self):
        self.save_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('document-save'), 
            self.tr('Save'), self.save,
        )
        self.ui.toolBar.addAction(
            QIcon.fromTheme('cancel'), 
            self.tr('Close without saving'), 
            self.close,
        )
        self.ui.toolBar.addAction(
            QIcon.fromTheme('edit-delete'),
            self.tr('Remove note'), 
            self.delete,
        )
        self.ui.toolBar.addSeparator()
        for action in self.note_edit.get_format_actions():
            self.ui.toolBar.addAction(action)
        self.ui.toolBar.addSeparator()
        self.find_action = QAction(QIcon.fromTheme('edit-find'),
                                   self.app.tr('Find'), self)
        self.find_action.setCheckable(True)
        self.find_action.triggered.connect(self.findbar.toggle_visible)
        self.ui.toolBar.addAction(self.find_action)
        self.ui.toolBar.addSeparator()
        self.pin = self.ui.toolBar.addAction(
            QIcon.fromTheme('edit-pin', QIcon.fromTheme('everpad-pin')),
            self.tr('Pin note'), self.mark_touched,
        )
        self.pin.setCheckable(True)
        self.pin.setChecked(self.note.pinnded)

    def load_note(self, note):
        self.resource_edit.resources = map(Resource.from_tuple,
            self.app.provider.get_note_resources(note.id),
        )
        self.notebook_edit.notebook = note.notebook
        self.note_edit.title = note.title
        self.note_edit.content = note.content
        self.tag_edit.tags = note.tags

    def update_note(self):
        self.note.notebook = self.notebook_edit.notebook
        self.note.title = self.note_edit.title
        self.note.content = self.note_edit.content
        self.note.tags = dbus.Array(self.tag_edit.tags, signature='s')
        self.note.pinnded = self.pin.isChecked()

    def closeEvent(self, event):
        event.ignore()
        if self.touched:
            self.save()
        self.close()

    def text_changed(self):
        self.update_title()
        self.mark_touched()

    def update_title(self):
        self.setWindowTitle(u'Everpad / %s' % self.note_edit.title)

    @Slot()
    def save(self):
        self.mark_untouched()
        self.update_note()
        self.app.provider.update_note(self.note.struct)
        self.app.provider.update_note_resources(
            self.note.struct, dbus.Array(map(lambda res:
                res.struct, self.resource_edit.resources,
            ), signature=Resource.signature),
        )
        self.app.send_notify(u'Note "%s" saved!' % self.note.title)

    @Slot()
    def save_and_close(self):
        self.save()
        self.close()

    @Slot()
    def delete(self):
        msgBox = QMessageBox(
            QMessageBox.Critical,
            self.tr("You are trying to delete a note"),
            self.tr("Are you sure want to delete this note?"),
            QMessageBox.Yes | QMessageBox.No
        )
        ret = msgBox.exec_()
        if ret == QMessageBox.Yes:
            self.update_note()
            self.app.provider.delete_note(self.note.id)
            self.app.send_notify(u'Note "%s" deleted!' % self.note.title)
            self.close()

    @Slot()
    def close(self):
        self.hide()
        self.closed = True
        self.app.settings.setValue(
            "note-geometry-%d" % self.note.id, 
            self.saveGeometry(),
        )
        self.app.settings.setValue(
            "note-geometry-default", self.saveGeometry(),
        )

    @Slot()
    def mark_touched(self):
        self.touched = True
        self.ui.actionSave.setEnabled(True)
        self.save_btn.setEnabled(True)

    def mark_untouched(self):
        self.touched = False
        self.ui.actionSave.setEnabled(False)
        self.save_btn.setEnabled(False)
Ejemplo n.º 24
0
class Editor(QMainWindow):  # TODO: kill this god shit
    """Note editor"""

    def __init__(self, app, note, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.app = app
        self.note = note
        self.closed = False
        self.ui = Ui_Editor()
        self.ui.setupUi(self)
        self.setWindowIcon(get_icon())
        self.init_controls()
        self.load_note(note)
        self.update_title()
        self.mark_untouched()
        geometry = self.app.settings.value("note-geometry-%d" % self.note.id)
        if not geometry:
            geometry = self.app.settings.value("note-geometry-default")
        if geometry:
            self.restoreGeometry(geometry)
        self.resource_edit.note = note

    def init_controls(self):
        self.ui.menubar.hide()
        self.ui.resourceArea.hide()
        self.note_edit = ContentEdit(
            self, self.app, 
            self.ui.contentView, self.text_changed,
        )
        self.tag_edit = TagEdit(
            self, self.app, 
            self.ui.tags, self.mark_touched,
        )
        self.notebook_edit = NotebookEdit(
            self, self.app, 
            self.ui.notebook, self.mark_touched,
        )
        self.resource_edit = ResourceEdit(
            self, self.app, self.ui.resourceArea, 
            self.ui.resourceLabel, self.mark_touched,
        )
        self.findbar = FindBar(self)
        self.init_toolbar()
        self.init_shortcuts()

    def init_shortcuts(self):
        self.save_btn.setShortcut(QKeySequence('Ctrl+s'))
        self.close_btn.setShortcut(QKeySequence('Ctrl+q'))

    def init_toolbar(self):
        self.save_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('document-save'), 
            self.tr('Save'), self.save,
        )
        self.close_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('window-close'), 
            self.tr('Close without saving'), 
            self.close,
        )
        self.ui.toolBar.addAction(
            QIcon.fromTheme('edit-delete'),
            self.tr('Remove note'), 
            self.delete,
        )
        self.ui.toolBar.addSeparator()
        for action in self.note_edit.get_format_actions():
            self.ui.toolBar.addAction(action)
        self.ui.toolBar.addSeparator()
        self.find_action = QAction(QIcon.fromTheme('edit-find'),
                                   self.app.tr('Find'), self)
        self.find_action.setCheckable(True)
        self.find_action.triggered.connect(self.findbar.toggle_visible)
        self.ui.toolBar.addAction(self.find_action)
        self.ui.toolBar.addSeparator()
        self.pin = self.ui.toolBar.addAction(
            QIcon.fromTheme('edit-pin', QIcon.fromTheme('everpad-pin')),
            self.tr('Pin note'), self.mark_touched,
        )
        self.pin.setCheckable(True)
        self.pin.setChecked(self.note.pinnded)

    def load_note(self, note):
        self.resource_edit.resources = map(Resource.from_tuple,
            self.app.provider.get_note_resources(note.id),
        )
        self.notebook_edit.notebook = note.notebook
        self.note_edit.title = note.title
        self.note_edit.content = note.content
        self.tag_edit.tags = note.tags

    def update_note(self):
        self.note.notebook = self.notebook_edit.notebook
        self.note.title = self.note_edit.title
        self.note.content = self.note_edit.content
        self.note.tags = dbus.Array(self.tag_edit.tags, signature='s')
        self.note.pinnded = self.pin.isChecked()

    def closeEvent(self, event):
        event.ignore()
        if self.touched:
            self.save()
        self.close()

    def text_changed(self):
        self.update_title()
        self.mark_touched()

    def update_title(self):
        self.setWindowTitle(u'Everpad / %s' % self.note_edit.title)

    @Slot()
    def save(self):
        self.mark_untouched()
        self.update_note()
        self.app.provider.update_note(self.note.struct)
        self.app.provider.update_note_resources(
            self.note.struct, dbus.Array(map(lambda res:
                res.struct, self.resource_edit.resources,
            ), signature=Resource.signature),
        )
        self.app.send_notify(u'Note "%s" saved!' % self.note.title)

    @Slot()
    def save_and_close(self):
        self.save()
        self.close()

    @Slot()
    def delete(self):
        msgBox = QMessageBox(
            QMessageBox.Critical,
            self.tr("You are trying to delete a note"),
            self.tr("Are you sure want to delete this note?"),
            QMessageBox.Yes | QMessageBox.No
        )
        ret = msgBox.exec_()
        if ret == QMessageBox.Yes:
            self.update_note()
            self.app.provider.delete_note(self.note.id)
            self.app.send_notify(u'Note "%s" deleted!' % self.note.title)
            self.close()

    @Slot()
    def close(self):
        self.hide()
        self.closed = True
        self.app.settings.setValue(
            "note-geometry-%d" % self.note.id, 
            self.saveGeometry(),
        )
        self.app.settings.setValue(
            "note-geometry-default", self.saveGeometry(),
        )

    @Slot()
    def mark_touched(self):
        self.touched = True
        self.ui.actionSave.setEnabled(True)
        self.save_btn.setEnabled(True)

    def mark_untouched(self):
        self.touched = False
        self.ui.actionSave.setEnabled(False)
        self.save_btn.setEnabled(False)
Ejemplo n.º 25
0
Archivo: gui.py Proyecto: tinavas/FSERP
class Gui():
    """main gui class"""
    def __init__(self):
        self.mainwindow = QMainWindow()
        settings.get_settings()
        self.access = tuple(settings.access.items())
        self.progress = QProgressDialog("Setting up modules...", "cancel", 0,
                                        7, self.mainwindow)
        self.progress.setWindowTitle(
            QApplication.translate("MainWindow", str(settings.company), None,
                                   QApplication.UnicodeUTF8))

    def setup(self):
        """initializes the uio of the erp client"""
        self.progress.setFixedWidth(1000)
        self.progress.setCancelButton(None)
        # self.progress.setWindowModality(Qt.WindowModal)
        self.progress.setValue(1)
        self.mainwindow.setObjectName("MainWindow")
        self.mainwindow.resize(832, 668)
        self.mainwindow.setStyleSheet(
            "QToolBar{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "QToolBar > QWidget{\n"
            "color:white;\n"
            "}\n"
            "QToolBar > QWidget:hover {\n"
            "background:transparent;\n"
            " }\n"
            "QToolBar > QWidget:checked {\n"
            "background:transparent;\n"
            " }\n"
            "#MainWindow{\n"
            "background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
            "stop:0 rgba(0,0,0),stop:1 rgb(162, 162, 162, 162));\n"
            "border: 0px;\n"
            "}\n"
            "")
        self.centralWidget = QWidget(self.mainwindow)
        self.centralWidget.setObjectName("centralWidget")
        self.gridLayout_2 = QGridLayout(self.centralWidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.stackedWidget = QStackedWidget(self.centralWidget)
        self.stackedWidget.setStyleSheet("")
        self.stackedWidget.setObjectName("stackedWidget")
        self.shortcut = NewShortcut()
        scroll = QScrollArea()
        scroll.setWidget(self.shortcut.shortcut_setting)
        self.stackedWidget.addWidget(self.shortcut.shortcut_setting)
        self.home_page = QWidget()
        self.home_page.setObjectName("home_page")
        self.gridLayout = QGridLayout(self.home_page)
        self.gridLayout.setObjectName("gridLayout")
        self.billing_frame_2 = QFrame(self.home_page)
        self.billing_frame_2.setStyleSheet(
            "background-image:url(:/images/billing_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#6CBED2;")
        self.billing_frame_2.setFrameShape(QFrame.StyledPanel)
        self.billing_frame_2.setFrameShadow(QFrame.Raised)
        self.billing_frame_2.setObjectName("billing_frame_2")
        self.verticalLayout_4 = QVBoxLayout(self.billing_frame_2)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        spacerItem = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout_4.addItem(spacerItem)
        self.label_10 = QLabel(self.billing_frame_2)
        self.label_10.setStyleSheet("background:transparent;")
        self.label_10.setObjectName("label_10")
        self.verticalLayout_4.addWidget(self.label_10)
        self.gridLayout.addWidget(self.billing_frame_2, 0, 1, 1, 1)
        self.employee_frame_3 = QFrame(self.home_page)
        self.employee_frame_3.setStyleSheet(
            "background-image:url(:/images/employee_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#0099CC;")
        self.employee_frame_3.setFrameShape(QFrame.StyledPanel)
        self.employee_frame_3.setFrameShadow(QFrame.Raised)
        self.employee_frame_3.setObjectName("employee_frame_3")
        self.verticalLayout_5 = QVBoxLayout(self.employee_frame_3)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        spacerItem1 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_5.addItem(spacerItem1)
        self.label_11 = QLabel(self.employee_frame_3)
        self.label_11.setStyleSheet("background:transparent;")
        self.label_11.setObjectName("label_11")
        self.verticalLayout_5.addWidget(self.label_11)
        self.gridLayout.addWidget(self.employee_frame_3, 0, 2, 1, 1)
        self.menu_frame_4 = QFrame(self.home_page)
        self.menu_frame_4.setStyleSheet(
            "background-image:url(:/images/menu_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#297ACC;")
        self.menu_frame_4.setFrameShape(QFrame.StyledPanel)
        self.menu_frame_4.setFrameShadow(QFrame.Raised)
        self.menu_frame_4.setObjectName("menu_frame_4")
        self.verticalLayout_3 = QVBoxLayout(self.menu_frame_4)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        spacerItem2 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_3.addItem(spacerItem2)
        self.label_12 = QLabel(self.menu_frame_4)
        self.label_12.setStyleSheet("background:transparent;")
        self.label_12.setObjectName("label_12")
        self.verticalLayout_3.addWidget(self.label_12)
        self.gridLayout.addWidget(self.menu_frame_4, 1, 0, 1, 1)
        self.report_frame_5 = QFrame(self.home_page)
        self.report_frame_5.setStyleSheet(
            "background-image:url(:/images/report_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#006BB2;")
        self.report_frame_5.setFrameShape(QFrame.StyledPanel)
        self.report_frame_5.setFrameShadow(QFrame.Raised)
        self.report_frame_5.setObjectName("report_frame_5")
        self.verticalLayout_6 = QVBoxLayout(self.report_frame_5)
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        spacerItem3 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_6.addItem(spacerItem3)
        self.label_13 = QLabel(self.report_frame_5)
        self.label_13.setStyleSheet("background:transparent;")
        self.label_13.setObjectName("label_13")
        self.verticalLayout_6.addWidget(self.label_13)
        self.gridLayout.addWidget(self.report_frame_5, 1, 1, 1, 1)
        self.waste_frame_6 = QFrame(self.home_page)
        self.waste_frame_6.setStyleSheet(
            "background-image:url(:/images/waste_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#003D7A;")
        self.waste_frame_6.setFrameShape(QFrame.StyledPanel)
        self.waste_frame_6.setFrameShadow(QFrame.Raised)
        self.waste_frame_6.setObjectName("waste_frame_6")
        self.verticalLayout_7 = QVBoxLayout(self.waste_frame_6)
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        spacerItem4 = QSpacerItem(20, 216, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_7.addItem(spacerItem4)
        self.label_14 = QLabel(self.waste_frame_6)
        self.label_14.setStyleSheet("background:transparent;")
        self.label_14.setObjectName("label_14")
        self.verticalLayout_7.addWidget(self.label_14)
        self.gridLayout.addWidget(self.waste_frame_6, 1, 2, 1, 1)
        self.inventory_frame_1 = QFrame(self.home_page)
        self.inventory_frame_1.setStyleSheet(
            "background-image:url(:/images/inventory_frame.png);\n"
            "background-repeat: no-repeat;\n"
            "background-position: center;\n"
            "background-color:#ADEBFF;")
        self.inventory_frame_1.setFrameShape(QFrame.StyledPanel)
        self.inventory_frame_1.setFrameShadow(QFrame.Raised)
        self.inventory_frame_1.setObjectName("inventory_frame_1")
        self.verticalLayout_2 = QVBoxLayout(self.inventory_frame_1)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        spacerItem5 = QSpacerItem(20, 217, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem5)
        self.label_9 = QLabel(self.inventory_frame_1)
        self.label_9.setStyleSheet("background:transparent;")
        self.label_9.setObjectName("label_9")
        self.verticalLayout_2.addWidget(self.label_9)
        self.gridLayout.addWidget(self.inventory_frame_1, 0, 0, 1, 1)
        self.stackedWidget.addWidget(self.home_page)
        self.detail_page = QWidget()
        self.detail_page.setObjectName("detail_page")
        self.horizontalLayout_2 = QHBoxLayout(self.detail_page)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.main_tabWidget = QTabWidget(self.detail_page)
        self.main_tabWidget.setAutoFillBackground(False)
        self.main_tabWidget.setStyleSheet("")
        self.main_tabWidget.setTabPosition(QTabWidget.West)
        self.main_tabWidget.setIconSize(QSize(60, 60))
        self.main_tabWidget.setElideMode(Qt.ElideNone)
        self.main_tabWidget.setObjectName("main_tabWidget")
        ##initializes the tabs
        self.add_tabs()
        self.main_tabWidget.setFocusPolicy(Qt.StrongFocus)
        self.main_tabWidget.focusInEvent = self.change_focus
        self.main_tabWidget.currentChanged.connect(self.change_focus)
        self.stackedWidget.currentChanged.connect(self.change_focus)
        ######
        self.horizontalLayout_2.addWidget(self.main_tabWidget)
        self.stackedWidget.addWidget(self.detail_page)
        if ('Admin', True) in self.access:
            self.stackedWidget.addWidget(Admin(self.mainwindow))
        notification = NotificationTab()
        tab = notification.notificationTab_tab_4
        tab.custom_class_object = notification  # class_object is used to access the api through the
        self.stackedWidget.addWidget(tab)
        self.gridLayout_2.addWidget(self.stackedWidget, 0, 0, 1, 1)
        self.mainwindow.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(self.mainwindow)
        self.menuBar.setGeometry(QRect(0, 0, 832, 29))
        self.menuBar.setObjectName("menuBar")
        self.mainwindow.setMenuBar(self.menuBar)
        self.mainToolBar = QToolBar(self.mainwindow)
        self.mainToolBar.setLayoutDirection(Qt.RightToLeft)
        self.mainToolBar.setStyleSheet("")
        self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.mainToolBar.setObjectName("mainToolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.mainToolBar)
        self.statusBar = QStatusBar(self.mainwindow)
        self.statusBar.setObjectName("statusBar")
        self.mainwindow.setStatusBar(self.statusBar)
        self.toolBar = QToolBar(self.mainwindow)
        self.toolBar.setLayoutDirection(Qt.RightToLeft)
        self.toolBar.setStyleSheet("")
        self.toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.toolBar.setObjectName("toolBar")
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.toolBar)
        self.actionNotification = QAction(self.mainwindow)
        self.actionNotification.setCheckable(True)
        self.actionNotification.setChecked(False)
        self.actionNotification.setEnabled(True)
        icon6 = QIcon()
        icon6.addPixmap(QPixmap(":/images/notification.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionNotification.setIcon(icon6)
        self.actionNotification.setAutoRepeat(True)
        self.actionNotification.setVisible(True)
        self.actionNotification.setIconVisibleInMenu(False)
        self.actionNotification.setObjectName("actionNotification")
        self.actionNotification
        self.actionAdmin = QAction(self.mainwindow)
        # self.actionAdmin.setCheckable(True)
        icon7 = QIcon()
        icon7.addPixmap(QPixmap(":/images/admin.png"), QIcon.Normal, QIcon.Off)
        self.actionAdmin.setIcon(icon7)
        self.actionAdmin.setObjectName("actionAdmin")
        self.actionRefresh = QAction(self.mainwindow)
        icon8 = QIcon()
        icon8.addPixmap(QPixmap(":/images/refresh.png"), QIcon.Normal,
                        QIcon.Off)
        self.actionRefresh.setIcon(icon8)
        self.actionRefresh.setObjectName("actionRefresh")
        self.actionHome = QAction(self.mainwindow)
        # self.actionHome.setCheckable(True)
        icon9 = QIcon()
        icon9.addPixmap(QPixmap(":/images/home.png"), QIcon.Normal, QIcon.Off)
        self.actionHome.setIcon(icon9)
        self.actionHome.setObjectName("actionHome")
        self.actionSettings = QAction(self.mainwindow)
        icon10 = QIcon()
        icon10.addPixmap(QPixmap(":/images/settings.png"), QIcon.Normal,
                         QIcon.Off)
        self.actionSettings.setIcon(icon10)
        self.actionSettings.setObjectName("actionRefresh")
        self.toolBar.addAction(self.actionNotification)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionAdmin)
        if ('Admin', True) in self.access:
            self.toolBar.addSeparator()
        else:
            self.actionAdmin.setVisible(False)
        self.toolBar.addAction(self.actionHome)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.actionSettings)
        ##retranslates
        self.mainwindow.setWindowTitle(
            QApplication.translate("MainWindow", settings.company, None,
                                   QApplication.UnicodeUTF8))
        self.label_10.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">BILLING</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_11.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">EMPLOYEE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_12.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">MENU</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_13.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">REPORT</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_14.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">WASTE</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.label_9.setText(
            QApplication.translate(
                "MainWindow",
                "<html><head/><body><p align=\"center\">INVENTORY</p></body></html>",
                None, QApplication.UnicodeUTF8))
        self.inventory_frame_1.setToolTip(
            QApplication.translate("MainWindow", "Go to the Inventory Tab",
                                   None, QApplication.UnicodeUTF8))
        self.billing_frame_2.setToolTip(
            QApplication.translate("MainWindow", "Go to the Billing Tab", None,
                                   QApplication.UnicodeUTF8))
        self.employee_frame_3.setToolTip(
            QApplication.translate("MainWindow", "Go to the Employee Tab",
                                   None, QApplication.UnicodeUTF8))
        self.menu_frame_4.setToolTip(
            QApplication.translate("MainWindow", "Go to the Menu Tab", None,
                                   QApplication.UnicodeUTF8))
        self.report_frame_5.setToolTip(
            QApplication.translate("MainWindow", "Go to the Report Tab", None,
                                   QApplication.UnicodeUTF8))
        self.waste_frame_6.setToolTip(
            QApplication.translate("MainWindow", "Go to the Waste Tab", None,
                                   QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(
            QApplication.translate("MainWindow", "toolBar", None,
                                   QApplication.UnicodeUTF8))
        self.actionNotification.setText("&&Notification")
        # QApplication.translate("MainWindow", "&Notification", None, QApplication.UnicodeUTF8))
        self.actionNotification.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to see new notifications", None,
                                   QApplication.UnicodeUTF8))
        # self.actionNotification.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+N", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setText('&&Admin')
        # QApplication.translate("MainWindow", "Admin", None, QApplication.UnicodeUTF8))
        self.actionAdmin.setToolTip(
            QApplication.translate("MainWindow",
                                   "Click to go to admin interface", None,
                                   QApplication.UnicodeUTF8))
        # self.actionAdmin.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+A", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setText("&&Refresh")
        # QApplication.translate("MainWindow", "Refresh", None, QApplication.UnicodeUTF8))
        self.actionRefresh.setToolTip(
            QApplication.translate("MainWindow",
                                   "refreshes the data from the server", None,
                                   QApplication.UnicodeUTF8))
        # self.actionRefresh.setShortcut(
        # QApplication.translate("MainWindow", "Ctrl+Shift+R", None, QApplication.UnicodeUTF8))
        self.actionHome.setText('&&Home')
        # QApplication.translate("MainWindow", "Home", None, QApplication.UnicodeUTF8))
        self.actionHome.setToolTip(
            QApplication.translate("MainWindow", "Go back to the home screen",
                                   None, QApplication.UnicodeUTF8))
        self.actionSettings.setText('&&Settings')
        # QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setToolTip(
            QApplication.translate("MainWindow", "Go to the settings panel",
                                   None, QApplication.UnicodeUTF8))
        # self.actionHome.setShortcut(
        #     QApplication.translate("MainWindow", "Ctrl+Shift+H", None, QApplication.UnicodeUTF8))
        self.stackedWidget.setCurrentIndex(1)
        self.main_tabWidget.setCurrentIndex(0)

        self.ob = self.main_tabWidget.tabBar()
        # self.add_tool_tip(self.ob) todo avoided due to segmentation fault error, left for future fixes
        self.tb = EventHandlerForTabBar()
        self.ob.installEventFilter(self.tb)

        QMetaObject.connectSlotsByName(self.mainwindow)

    def add_tabs(self):
        """
        adds new tabs
        """
        global logger
        if ('Inventory', True) in self.access:
            logger.info('initiating Inventory')
            icon = QIcon()
            icon.addPixmap(QPixmap(":/images/inventory.png"), QIcon.Normal,
                           QIcon.Off)
            from inventory.inventory import Inventory

            inventory = Inventory()
            # inventory.inventory_tab_1.setToolTip("Inventory Section")
            self.main_tabWidget.addTab(inventory.inventory_tab_1, icon, "")
            inventory.inventory_detail_tabWidget.setCurrentIndex(0)
        else:
            self.inventory_frame_1.setVisible(False)
        self.progress.setLabelText('Inventory Done....')
        self.progress.setValue(2)

        if ('Billing', True) in self.access:
            logger.info('initiating Billing')
            icon1 = QIcon()
            icon1.addPixmap(QPixmap(":/images/billing.png"), QIcon.Normal,
                            QIcon.Off)
            from billing.billing import Billing

            bill = Billing()
            # bill.billing_tab_2.setToolTip("Billing Section")
            self.main_tabWidget.addTab(bill.billing_tab_2, icon1, "")
            bill.billing_detail_tabWidget.setCurrentIndex(0)
        else:
            self.billing_frame_2.setVisible(False)
        self.progress.setLabelText('Billing Done...')
        self.progress.setValue(3)

        if ('Employee', True) in self.access:
            logger.info('initiating Employee')
            icon2 = QIcon()
            icon2.addPixmap(QPixmap(":/images/employee.png"), QIcon.Normal,
                            QIcon.Off)
            from employee.employee import Employee

            employee = Employee()
            # employee.employee_tab_3.setToolTip("Employee Section")
            self.main_tabWidget.addTab(employee.employee_tab_3, icon2, "")
            employee.employee_detail_tabWidget.setCurrentIndex(0)
        else:
            self.employee_frame_3.setVisible(False)
        self.progress.setLabelText('Employee Done...')
        self.progress.setValue(4)

        if ('Menu', True) in self.access:
            logger.info('initiating Menu')
            icon3 = QIcon()
            icon3.addPixmap(QPixmap(":/images/menu.png"), QIcon.Normal,
                            QIcon.Off)
            from menu.menu import Menu

            menu = Menu()
            # menu.menu_tab_4.setToolTip("Menu Section")
            self.main_tabWidget.addTab(menu.menu_tab_4, icon3, "")
            menu.menu_detail_tabWidget.setCurrentIndex(0)
        else:
            self.menu_frame_4.setVisible(False)
        self.progress.setLabelText('Menu Done....')
        self.progress.setValue(5)

        if ('Report', True) in self.access:
            logger.info('initiating Report')
            icon4 = QIcon()
            icon4.addPixmap(QPixmap(":/images/report.png"), QIcon.Normal,
                            QIcon.Off)
            from report.report import Report

            report = Report()
            # report.report_tab_5.setToolTip("Report Section")
            self.main_tabWidget.addTab(report.report_tab_5, icon4, "")
            report.report_detail_tabWidget.setCurrentIndex(0)
        else:
            self.report_frame_5.setVisible(False)
        self.progress.setLabelText('Report Done....')
        self.progress.setValue(6)

        if ('Waste', True) in self.access:
            logger.info('initiating Waste')
            icon5 = QIcon()
            icon5.addPixmap(QPixmap(":/images/waste.png"), QIcon.Normal,
                            QIcon.Off)
            from waste.waste import Waste

            waste = Waste()
            # waste.waste_tab_6.setToolTip("Waste Section")
            self.main_tabWidget.addTab(waste.waste_tab_6, icon5, "")
            waste.waste_detail_tabWidget.setCurrentIndex(0)
        else:
            self.waste_frame_6.setVisible(False)
        self.progress.setLabelText('Waste Done....')
        self.progress.setValue(7)

    def change_focus(self, event=None):
        """
        focus method to set focus to a tab to initialize the corresponding events of the tab
        """
        wid = self.main_tabWidget.currentWidget()
        if wid:
            if wid.isVisible():
                # print wid.objectName()
                # print '1y'
                wid.setFocus()

    def add_tool_tip(
        self, ob
    ):  # todo not working causing segmentation fault, avoided calling this function
        """
        method to add tool tip to the tabs
        :param ob: Tab bar
        """
        obj = ob
        count = obj.count()
        hardcode = {
            0: 'Inventory Section',
            1: "Billing Section",
            2: "Employee Section",
            3: "Menu Section",
            4: "Report Section",
            5: "Waste Section"
        }
        for i in range(count):
            obj.setTabToolTip(i, hardcode[i])
Ejemplo n.º 26
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(800, 480)
        self.setWindowTitle('PySide GUI')
        #self.setWindowFlags(PySide.QtCore.Qt.FramelessWindowHint)

         
        self.wgHome, self.dcHome = self.createHomePage()

        
        # serial page
        self.wgSerial = QWidget(self)
        gridLayout = QGridLayout(self.wgSerial)
        self.lb1 = QLabel('serial page')
        self.lb2 = QLabel('label 2')
        self.lb3 = QLabel('label 3')
        
        gridLayout.addWidget(self.lb1, 0, 0)
        gridLayout.addWidget(self.lb2, 1, 0)
        gridLayout.addWidget(self.lb3, 2, 0)
        

        self.sw = QStackedWidget(self)
        self.sw.addWidget(self.wgHome)
        self.sw.addWidget(self.wgSerial)
        self.setCentralWidget(self.sw)
        
        
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
        menu_File = QMenu(menubar)
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
        self.setStatusBar(statusbar)
        

        actionHome = QAction(self)
        actionHome.setIcon(QIcon("icon/Home-50.png"))
        actionHome.setStatusTip("Home content")
        actionHome.triggered.connect(
            lambda: self.sw.setCurrentWidget(self.wgHome))

        actionSerial = QAction(self)
        actionSerial.setIcon(QIcon("icon/Unicast-50.png"))
        actionSerial.setStatusTip("Serial polling task status")
        actionSerial.triggered.connect(
            lambda: self.sw.setCurrentWidget(self.wgSerial))

        actionLogging = QAction(self)
        actionLogging.setIcon(QIcon("icon/Database-50.png"))
        actionLogging.setStatusTip("Logging task status")
        actionLogging.triggered.connect(
            lambda: self.sw.setCurrentWidget(self.wgLogging))  

        actionUpload = QAction(self)
        actionUpload.setIcon(QIcon("icon/Upload to Cloud-50.png"))
        actionUpload.setStatusTip("Uploading task status")
        actionUpload.triggered.connect(
            lambda: self.sw.setCurrentWidget(self.wgLogging))  

        actionDebug = QAction(self)
        actionDebug.setIcon(QIcon("icon/Bug-50.png"))
        actionDebug.setStatusTip("debug")
        actionDebug.triggered.connect(self.debug)  


        actionAbout = QAction(self)
        actionAbout.triggered.connect(self.about)
        actionAbout.setIcon(QIcon("icon/Info-50.png"))
        actionAbout.setStatusTip("Pop up the About dialog.")

        actionSetting = QAction(self)
        actionSetting.setCheckable(False)
        actionSetting.setObjectName('action_clear')
        actionSetting.setIcon(QIcon("icon/Settings-50.png"))
        

        actionLeft = QAction(self)
        actionLeft.setIcon(QIcon("icon/Left-50.png"))
        actionLeft.setStatusTip("Left page")
        actionLeft.triggered.connect(self.switchLeftWidget)

        actionRight = QAction(self)
        actionRight.setIcon(QIcon("icon/Right-50.png"))
        actionRight.setStatusTip("Right page")
        actionRight.triggered.connect(self.switchRightWidget)
        

        actionClose = QAction(self)
        actionClose.setCheckable(False)
        actionClose.setObjectName("action_Close")        
        actionClose.setIcon(QIcon("icon/Delete-50.png"))
        actionClose.setStatusTip("Close the program.")
        actionClose.triggered.connect(self.close)        

#------------------------------------------------------
        menu_File.addAction(actionHome)
        menu_File.addAction(actionAbout)
        menu_File.addAction(actionClose)
        menu_File.addAction(actionSetting)
        menubar.addAction(menu_File.menuAction())


        iconToolBar = self.addToolBar("iconBar.png")
        iconToolBar.addAction(actionHome)
        
        iconToolBar.addAction(actionSerial)
        iconToolBar.addAction(actionLogging)
        iconToolBar.addAction(actionUpload)

        iconToolBar.addAction(actionDebug)
        
        iconToolBar.addAction(actionAbout)
        iconToolBar.addAction(actionSetting)
        iconToolBar.addAction(actionLeft)
        iconToolBar.addAction(actionRight)
        iconToolBar.addAction(actionClose)
Ejemplo n.º 27
0
class Editor(QMainWindow):  # TODO: kill this god shit
    """Note editor"""
    def __init__(self, note, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.app = QApplication.instance()
        self.note = note
        self.closed = False
        self.ui = Ui_Editor()
        self.ui.setupUi(self)
        self.setWindowIcon(get_icon())
        self.alternatives_template =\
            self.ui.alternativeVersions.text()
        self.init_controls()
        self.load_note(note)
        self.update_title()
        self.mark_untouched()
        geometry = self.app.settings.value("note-geometry-%d" % self.note.id)
        if not geometry:
            geometry = self.app.settings.value("note-geometry-default")
        if geometry:
            self.restoreGeometry(geometry)
        self.resource_edit.note = note

    def init_controls(self):
        self.ui.menubar.hide()
        self.ui.resourceArea.hide()
        self.note_edit = ContentEdit(
            self,
            self.ui.contentView,
            self.text_changed,
        )
        self.tag_edit = TagEdit(
            self,
            self.ui.tags,
            self.mark_touched,
        )
        self.notebook_edit = NotebookEdit(
            self,
            self.ui.notebook,
            self.mark_touched,
        )
        self.resource_edit = ResourceEdit(
            self,
            self.ui.resourceArea,
            self.ui.resourceLabel,
            self.mark_touched,
        )
        self.findbar = FindBar(self)
        self.init_toolbar()
        self.init_shortcuts()
        self.init_alternatives()
        self.app.data_changed.connect(self.init_alternatives)

    def init_alternatives(self):
        try:
            conflict_items = self.app.provider.get_note_alternatives(
                self.note.id)
            if conflict_items:
                conflicts = map(
                    lambda item: Note.from_tuple(
                        self.app.provider.get_note(item, )),
                    self.note.conflict_items,
                )
                text = self.alternatives_template % ', '.join(
                    map(
                        lambda note: u'<a href="%d">%s</a>' % (
                            note.id,
                            note.title,
                        ),
                        conflicts,
                    ))
                self.ui.alternativeVersions.setText(text)
                self.ui.alternativeVersions.linkActivated.connect(
                    lambda id: self.app.indicator.open(
                        Note.from_tuple(self.app.provider.get_note(int(id))),
                    ))
            else:
                self.ui.alternativeVersions.hide()
        except DBusException:
            self.ui.alternativeVersions.hide()

    def init_shortcuts(self):
        self.save_btn.setShortcut(QKeySequence('Ctrl+s'))
        self.close_btn.setShortcut(QKeySequence('Ctrl+q'))
        self.email_btn.setShortcut(QKeySequence('Ctrl+Shift+e'))
        self.print_btn.setShortcut(QKeySequence(self.tr('Ctrl+p')))
        QShortcut(QKeySequence(self.tr('Ctrl+w')), self, self.save_and_close)

    def init_toolbar(self):
        self.save_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('document-save'),
            self.tr('Save'),
            self.save,
        )
        self.close_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('window-close'),
            self.tr('Close without saving'),
            self.close,
        )
        self.ui.toolBar.addAction(
            QIcon.fromTheme('edit-delete'),
            self.tr('Remove note'),
            self.delete,
        )
        self.print_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('document-print'),
            self.tr('Print note'),
            self.note_edit.print_,
        )
        self.email_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('mail-unread'),
            self.tr('Email note'),
            self.note_edit.email_note,
        )
        self.email_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('emblem-shared'),
            self.tr('Share note'),
            self.share_note,
        )
        self.ui.toolBar.addSeparator()
        for action in self.note_edit.get_format_actions():
            self.ui.toolBar.addAction(action)
        self.ui.toolBar.addSeparator()
        self.find_action = QAction(QIcon.fromTheme('edit-find'),
                                   self.tr('Find'), self)
        self.find_action.setCheckable(True)
        self.find_action.triggered.connect(self.findbar.toggle_visible)
        self.ui.toolBar.addAction(self.find_action)
        self.ui.toolBar.addSeparator()
        self.pin = self.ui.toolBar.addAction(
            QIcon.fromTheme('edit-pin', QIcon.fromTheme('everpad-pin')),
            self.tr('Pin note'),
            self.mark_touched,
        )
        self.pin.setCheckable(True)
        self.pin.setChecked(self.note.pinnded)

    def load_note(self, note):
        self.resource_edit.resources = map(
            Resource.from_tuple,
            self.app.provider.get_note_resources(note.id),
        )
        self.notebook_edit.notebook = note.notebook
        self.note_edit.title = note.title
        self.note_edit.content = note.content
        self.tag_edit.tags = note.tags

    def update_note(self):
        self.note.notebook = self.notebook_edit.notebook
        self.note.title = self.note_edit.title
        self.note.content = self.note_edit.content
        self.note.tags = dbus.Array(self.tag_edit.tags, signature='s')
        self.note.pinnded = self.pin.isChecked()

    def closeEvent(self, event):
        event.ignore()
        self.save_and_close()

    def text_changed(self):
        self.update_title()
        self.mark_touched()

    def update_title(self):
        title = self.note_edit.title
        if self.note.conflict_parent:
            title += self.tr(' altrentive of: %s') % (Note.from_tuple(
                self.app.provider.get_note(
                    self.note.conflict_parent, )).title, )
        self.setWindowTitle(self.tr('Everpad / %s') % title)

    @Slot()
    def save(self):
        self.mark_untouched()
        self.update_note()
        self.app.provider.update_note(self.note.struct)
        self.app.provider.update_note_resources(
            self.note.struct,
            dbus.Array(map(
                lambda res: res.struct,
                self.resource_edit.resources,
            ),
                       signature=Resource.signature),
        )
        self.app.send_notify(self.tr('Note "%s" saved!') % self.note.title)

    @Slot()
    def save_and_close(self):
        if self.touched:
            self.save()
        self.close()

    @Slot()
    def delete(self):
        msgBox = QMessageBox(QMessageBox.Critical,
                             self.tr("You are trying to delete a note"),
                             self.tr("Are you sure want to delete this note?"),
                             QMessageBox.Yes | QMessageBox.No)
        ret = msgBox.exec_()
        if ret == QMessageBox.Yes:
            self.update_note()
            self.app.provider.delete_note(self.note.id)
            self.app.send_notify(
                self.tr('Note "%s" deleted!') % self.note.title)
            self.close()

    @Slot()
    def close(self):
        msg = QMessageBox(
            QMessageBox.Critical, self.tr("Close without Saving"),
            self.tr("Are you sure want to close this note without saving?"),
            QMessageBox.Yes | QMessageBox.No)
        if not self.touched or msg.exec_() == QMessageBox.Yes:
            self.hide()
            self.closed = True
            self.app.settings.setValue(
                "note-geometry-%d" % self.note.id,
                self.saveGeometry(),
            )
            self.app.settings.setValue(
                "note-geometry-default",
                self.saveGeometry(),
            )

    @Slot()
    def mark_touched(self):
        self.touched = True
        self.ui.actionSave.setEnabled(True)
        self.save_btn.setEnabled(True)

    def mark_untouched(self):
        self.touched = False
        self.ui.actionSave.setEnabled(False)
        self.save_btn.setEnabled(False)

    def share_note(self):
        dialog = ShareNoteDialog(self.note, parent=self)
        dialog.exec_()
Ejemplo n.º 28
0
    class PlotMainWindow(QWidget):
        """Base class for plot main windows."""
        def __init__(self, U, plot, length=1, title=None):
            super().__init__()

            layout = QVBoxLayout()

            if title:
                title = QLabel('<b>' + title + '</b>')
                title.setAlignment(Qt.AlignHCenter)
                layout.addWidget(title)
            layout.addWidget(plot)

            plot.set(U, 0)

            if length > 1:
                hlayout = QHBoxLayout()

                self.slider = QSlider(Qt.Horizontal)
                self.slider.setMinimum(0)
                self.slider.setMaximum(length - 1)
                self.slider.setTickPosition(QSlider.TicksBelow)
                hlayout.addWidget(self.slider)

                lcd = QLCDNumber(m.ceil(m.log10(length)))
                lcd.setDecMode()
                lcd.setSegmentStyle(QLCDNumber.Flat)
                hlayout.addWidget(lcd)

                layout.addLayout(hlayout)

                hlayout = QHBoxLayout()

                toolbar = QToolBar()
                self.a_play = QAction(
                    self.style().standardIcon(QStyle.SP_MediaPlay), 'Play',
                    self)
                self.a_play.setCheckable(True)
                self.a_rewind = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSeekBackward),
                    'Rewind', self)
                self.a_toend = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSeekForward),
                    'End', self)
                self.a_step_backward = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSkipBackward),
                    'Step Back', self)
                self.a_step_forward = QAction(
                    self.style().standardIcon(QStyle.SP_MediaSkipForward),
                    'Step', self)
                self.a_loop = QAction(
                    self.style().standardIcon(QStyle.SP_BrowserReload), 'Loop',
                    self)
                self.a_loop.setCheckable(True)
                toolbar.addAction(self.a_play)
                toolbar.addAction(self.a_rewind)
                toolbar.addAction(self.a_toend)
                toolbar.addAction(self.a_step_backward)
                toolbar.addAction(self.a_step_forward)
                toolbar.addAction(self.a_loop)
                if hasattr(self, 'save'):
                    self.a_save = QAction(
                        self.style().standardIcon(QStyle.SP_DialogSaveButton),
                        'Save', self)
                    toolbar.addAction(self.a_save)
                    self.a_save.triggered.connect(self.save)
                hlayout.addWidget(toolbar)

                self.speed = QSlider(Qt.Horizontal)
                self.speed.setMinimum(0)
                self.speed.setMaximum(100)
                hlayout.addWidget(QLabel('Speed:'))
                hlayout.addWidget(self.speed)

                layout.addLayout(hlayout)

                self.timer = QTimer()
                self.timer.timeout.connect(self.update_solution)

                self.slider.valueChanged.connect(self.slider_changed)
                self.slider.valueChanged.connect(lcd.display)
                self.speed.valueChanged.connect(self.speed_changed)
                self.a_play.toggled.connect(self.toggle_play)
                self.a_rewind.triggered.connect(self.rewind)
                self.a_toend.triggered.connect(self.to_end)
                self.a_step_forward.triggered.connect(self.step_forward)
                self.a_step_backward.triggered.connect(self.step_backward)

                self.speed.setValue(50)

            elif hasattr(self, 'save'):
                hlayout = QHBoxLayout()
                toolbar = QToolBar()
                self.a_save = QAction(
                    self.style().standardIcon(QStyle.SP_DialogSaveButton),
                    'Save', self)
                toolbar.addAction(self.a_save)
                hlayout.addWidget(toolbar)
                layout.addLayout(hlayout)
                self.a_save.triggered.connect(self.save)

            self.setLayout(layout)
            self.plot = plot
            self.U = U
            self.length = length

        def slider_changed(self, ind):
            self.plot.set(self.U, ind)

        def speed_changed(self, val):
            self.timer.setInterval(val * 20)

        def update_solution(self):
            ind = self.slider.value() + 1
            if ind >= self.length:
                if self.a_loop.isChecked():
                    ind = 0
                else:
                    self.a_play.setChecked(False)
                    return
            self.slider.setValue(ind)

        def toggle_play(self, checked):
            if checked:
                if self.slider.value() + 1 == self.length:
                    self.slider.setValue(0)
                self.timer.start()
            else:
                self.timer.stop()

        def rewind(self):
            self.slider.setValue(0)

        def to_end(self):
            self.a_play.setChecked(False)
            self.slider.setValue(self.length - 1)

        def step_forward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() + 1
            if ind == self.length and self.a_loop.isChecked():
                ind = 0
            if ind < self.length:
                self.slider.setValue(ind)

        def step_backward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() - 1
            if ind == -1 and self.a_loop.isChecked():
                ind = self.length - 1
            if ind >= 0:
                self.slider.setValue(ind)
Ejemplo n.º 29
0
class Editor(QMainWindow):  # TODO: kill this god shit
    """Note editor"""

    def __init__(self, note, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        # Configure logger.
        self.logger = logging.getLogger("everpad-editor")
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(os.path.expanduser("~/.everpad/logs/everpad.log"))
        fh.setLevel(logging.DEBUG)
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

        self.app = QApplication.instance()
        self.timer = QBasicTimer()
        self.note = note
        self.closed = False
        self.ui = Ui_Editor()
        self.ui.setupUi(self)
        self.setWindowIcon(get_icon())
        self.alternatives_template = self.ui.alternativeVersions.text()
        self.init_controls()
        self.load_note(note)
        self.update_title()
        self.mark_untouched()
        geometry = self.app.settings.value("note-geometry-%d" % self.note.id)
        if not geometry:
            geometry = self.app.settings.value("note-geometry-default")
        if geometry:
            self.restoreGeometry(geometry)
        self.resource_edit.note = note
        self.timer.start(10000, self)

    def timerEvent(self, event):
        if self.touched:
            self.save(notify=False)

    def init_controls(self):
        self.ui.menubar.hide()
        self.ui.resourceArea.hide()
        self.note_edit = ContentEdit(self, self.ui.contentView, self.text_changed)
        self.tag_edit = TagEdit(self, self.ui.tags, self.mark_touched)
        self.notebook_edit = NotebookEdit(self, self.ui.notebook, self.mark_touched)
        self.resource_edit = ResourceEdit(self, self.ui.resourceArea, self.ui.resourceLabel, self.mark_touched)
        self.findbar = FindBar(self)
        self.init_toolbar()
        self.init_shortcuts()
        self.init_alternatives()
        self.app.data_changed.connect(self.init_alternatives)

    def init_alternatives(self):
        try:
            conflict_items = self.app.provider.get_note_alternatives(self.note.id)
            if conflict_items:
                conflicts = map(
                    lambda item: Note.from_tuple(self.app.provider.get_note(item)), self.note.conflict_items
                )
                text = self.alternatives_template % ", ".join(
                    map(lambda note: u'<a href="%d">%s</a>' % (note.id, note.title), conflicts)
                )
                self.ui.alternativeVersions.setText(text)
                self.ui.alternativeVersions.linkActivated.connect(
                    lambda id: self.app.indicator.open(Note.from_tuple(self.app.provider.get_note(int(id))))
                )
            else:
                self.ui.alternativeVersions.hide()
        except DBusException:
            self.ui.alternativeVersions.hide()

    def init_shortcuts(self):
        self.save_btn.setShortcut(QKeySequence("Ctrl+s"))
        self.close_btn.setShortcut(QKeySequence("Ctrl+q"))
        self.email_btn.setShortcut(QKeySequence("Ctrl+Shift+e"))
        self.print_btn.setShortcut(QKeySequence(self.tr("Ctrl+p")))
        QShortcut(QKeySequence(self.tr("Ctrl+w")), self, self.save_and_close)

    def init_toolbar(self):
        self.save_btn = self.ui.toolBar.addAction(QIcon.fromTheme("document-save"), self.tr("Save"), self.save)
        self.close_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme("window-close"), self.tr("Close without saving"), self.close
        )
        self.ui.toolBar.addAction(QIcon.fromTheme("edit-delete"), self.tr("Remove note"), self.delete)
        self.print_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme("document-print"), self.tr("Print note"), self.note_edit.print_
        )
        self.email_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme("mail-unread"), self.tr("Email note"), self.note_edit.email_note
        )
        self.email_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme("emblem-shared"), self.tr("Share note"), self.share_note
        )
        self.ui.toolBar.addSeparator()
        for action in self.note_edit.get_format_actions():
            self.ui.toolBar.addAction(action)
        self.ui.toolBar.addSeparator()
        self.find_action = QAction(QIcon.fromTheme("edit-find"), self.tr("Find"), self)
        self.find_action.setCheckable(True)
        self.find_action.triggered.connect(self.findbar.toggle_visible)
        self.ui.toolBar.addAction(self.find_action)
        self.ui.toolBar.addSeparator()
        self.pin = self.ui.toolBar.addAction(
            QIcon.fromTheme("edit-pin", QIcon.fromTheme("everpad-pin")), self.tr("Pin note"), self.mark_touched
        )
        self.pin.setCheckable(True)
        self.pin.setChecked(self.note.pinnded)

    def load_note(self, note):
        self.logger.debug('Loading note: "%s"' % note.title)
        self.resource_edit.resources = map(Resource.from_tuple, self.app.provider.get_note_resources(note.id))
        self.notebook_edit.notebook = note.notebook
        self.note_edit.title = note.title
        self.logger.debug('Note content: "%s"' % note.content)
        self.note_edit.content = note.content
        self.tag_edit.tags = note.tags

    def update_note(self):
        self.logger.debug('Updating note: "%s"' % self.note_edit.title)
        self.note.notebook = self.notebook_edit.notebook
        self.note.title = self.note_edit.title
        self.note.content = self.note_edit.content
        self.note.tags = dbus.Array(self.tag_edit.tags, signature="s")
        self.note.pinnded = self.pin.isChecked()

    def closeEvent(self, event):
        event.ignore()
        self.save_and_close()

    def text_changed(self):
        self.update_title()
        self.mark_touched()

    def update_title(self):
        title = self.note_edit.title
        if self.note.conflict_parent:
            title += self.tr(" alternative of: %s") % (
                Note.from_tuple(self.app.provider.get_note(self.note.conflict_parent)).title,
            )
        self.setWindowTitle(self.tr("Everpad / %s") % title)

    @Slot()
    def save(self, notify=True):
        self.logger.debug('Saving note: "%s"' % self.note.title)
        self.mark_untouched()
        self.update_note()
        self.app.provider.update_note(self.note.struct)
        self.app.provider.update_note_resources(
            self.note.id,
            dbus.Array(map(lambda res: res.struct, self.resource_edit.resources), signature=Resource.signature),
        )
        if notify:
            self.app.send_notify(self.tr('Note "%s" saved!') % self.note.title)

    @Slot()
    def save_and_close(self):
        if self.touched:
            self.save()
        self.close()

    @Slot()
    def delete(self):
        msgBox = QMessageBox(
            QMessageBox.Critical,
            self.tr("You are trying to delete a note"),
            self.tr("Are you sure want to delete this note?"),
            QMessageBox.Yes | QMessageBox.No,
        )
        ret = msgBox.exec_()
        if ret == QMessageBox.Yes:
            self.update_note()
            self.app.provider.delete_note(self.note.id)
            self.app.send_notify(self.tr('Note "%s" deleted!') % self.note.title)
            self.close()

    @Slot()
    def close(self):
        msg = QMessageBox(
            QMessageBox.Critical,
            self.tr("Close without Saving"),
            self.tr("Are you sure want to close this note without saving?"),
            QMessageBox.Yes | QMessageBox.No,
        )
        if not self.touched or msg.exec_() == QMessageBox.Yes:
            self.hide()
            self.closed = True
            self.app.settings.setValue("note-geometry-%d" % self.note.id, self.saveGeometry())
            self.app.settings.setValue("note-geometry-default", self.saveGeometry())

    @Slot()
    def mark_touched(self):
        self.touched = True
        self.ui.actionSave.setEnabled(True)
        self.save_btn.setEnabled(True)

    def mark_untouched(self):
        self.touched = False
        self.ui.actionSave.setEnabled(False)
        self.save_btn.setEnabled(False)

    def share_note(self):
        dialog = ShareNoteDialog(self.note, parent=self)
        dialog.exec_()
Ejemplo n.º 30
0
class SymbolWort(QWidget):
	def __init__(self):
		QWidget.__init__(self)
		self.setWindowTitle("Symbol-Worte")
		
		self.thread=MyWorker(self)
		self.thread.start()
		self.thread.calculator.calculationDone.connect(self.calculationDone)
		
		self.initUI()
	
	def about(self):
		QMessageBox.information(self,u"Über Symbol-Worte",u"Symbol-Worte ist ein kleines, zum Spaß entwickeltes, Programm. Es nutzt die Open-Source Entwicklungsumgebung Python (www.python.org) und PySide (Qt-Schnittstelle). Es ist unter GPL v.3 veröffentlicht. Entwickelt von Peter Waldert.")
	
	def update(self):
		text=self.lineEdit.text()
		if text.lower() != self.responseLabel.text().lower():
			self.thread.startCalculation(text)
	
	def calculationDone(self,ok):
		if ok:
			self.responseLabel.setText(self.thread.calculator.result)
		else:
			self.responseLabel.setText(u"Keine Treffer")
		self.updateTable(self.thread.calculator.resultElements)
	
	def updateAuto(self,checked):
		if checked:
			self.lineEdit.textEdited.connect(self.update)
		else:
			self.lineEdit.textEdited.disconnect(self.update)
	
	def updateMaxLength(self,checked):
		if checked:
			self.lineEdit.setMaxLength(10)
		else:
			self.lineEdit.setMaxLength(100)
	
	def setupTable(self):
		self.tableWidget.setColumnCount(3)
		self.tableWidget.setHorizontalHeaderLabels(["OZ","Sym","Name"])
		self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
		self.tableWidget.setSelectionMode(QTableWidget.SingleSelection)
		self.tableWidget.setEditTriggers(QTableWidget.NoEditTriggers)
		self.tableWidget.setAlternatingRowColors(True)
	
	def updateTable(self,elements):
		self.tableWidget.clearContents()
		self.tableWidget.setRowCount(len(elements))
		row=0
		for element in elements:
			self.tableWidget.setItem(row,0,QTableWidgetItem(str(element.atomicNumber)))
			self.tableWidget.setItem(row,1,QTableWidgetItem(elements[row].symbol))
			self.tableWidget.setItem(row,2,QTableWidgetItem(elements[row].name))
			row+=1
		self.tableWidget.resizeColumnsToContents()
	
	def initUI(self):
		wordLabel=QLabel("&Wort:")
		responseLabel=QLabel("Symbol-Wort:")
		progressLabel=QLabel("Rechen-Fortschritt:")
		
		self.lineEdit=QLineEdit()
		self.updateButton=QPushButton("&Berechnen")
		self.autoUpdate=QCheckBox("&Auto-Berechnung")
		self.responseLabel=QLabel()
		wordLabel.setBuddy(self.lineEdit)
		self.tableWidget=QTableWidget()
		self.progressView=ProgressView()
		
		self.disableMaxLengthAction=QAction("Zeichenmaximum (Achtung!)",self)
		self.disableMaxLengthAction.setCheckable(True)
		self.disableMaxLengthAction.toggled.connect(self.updateMaxLength)
		self.disableMaxLengthAction.setChecked(True)
		
		self.setupTable()
		self.progressView.setProgress(self.thread.calculator.progress)
		self.progressView.abortButton.setIcon(QIcon.fromTheme("process-stopp",QIcon("Abort.png")))
		self.progressView.abortButton.setToolTip("Stoppe die Berechnung")
		self.lineEdit.setValidator(QRegExpValidator(QRegExp("[A-Za-z]+")))
		self.lineEdit.setToolTip("Nur Zeichen von A-Z")
		self.lineEdit.setContextMenuPolicy(Qt.ActionsContextMenu)
		self.lineEdit.addAction(self.disableMaxLengthAction)
		self.responseLabel.setSizePolicy(QSizePolicy.Preferred,QSizePolicy.Fixed)
		self.responseLabel.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
		self.aboutButton=QPushButton(u"Über")
		f=self.responseLabel.font()
		f.setPointSize(24)
		self.responseLabel.setFont(f)
		
		self.lineEdit.returnPressed.connect(self.update)
		self.updateButton.clicked.connect(self.update)
		self.autoUpdate.stateChanged.connect(self.updateAuto)
		self.aboutButton.clicked.connect(self.about)
		
		layout=QGridLayout()
		layout.addWidget(wordLabel,0,0)
		layout.addWidget(self.lineEdit,0,1)
		layout.addWidget(self.updateButton,0,2)
		layout.addWidget(self.autoUpdate,1,1,1,2)
		layout.addWidget(responseLabel,2,0)
		layout.addWidget(self.responseLabel,2,1,1,2)
		layout.addWidget(self.tableWidget,3,0,1,3)
		layout.addWidget(progressLabel,4,0)
		layout.addWidget(self.progressView,5,0,1,3)
		layout.addWidget(self.aboutButton,6,2)
		self.setLayout(layout)
	
	def closeEvent(self,event):
		self.thread.quit()
		self.thread.wait()
		event.accept()
	
	def keyPressEvent(self,event):
		if event.key() == Qt.Key_Escape:
			self.thread.calculator.progress.abort()
			event.accept()
		else:
			event.ignore()
Ejemplo n.º 31
0
class MainWindow(QMainWindow):
    start_acq = Signal(str)
    start_rec = Signal(str)
    collect_frame = Signal(object)
    collect_threshed = Signal(object)

    def __init__(self, parent=None):
        ''' sets up the whole main window '''

        #standard init
        super(MainWindow, self).__init__(parent)

        #set the window title
        self.setWindowTitle('Open Ephys Control GUI')

        self.window_height = 700
        self.window_width = 1100

        self.screen2 = QDesktopWidget().screenGeometry(0)
        self.move(
            self.screen2.left() +
            (self.screen2.width() - self.window_width) / 2.,
            self.screen2.top() +
            (self.screen2.height() - self.window_height) / 2.)

        self.get_info()
        self.noinfo = True

        while self.noinfo:
            loop = QEventLoop()
            QTimer.singleShot(500., loop.quit)
            loop.exec_()

        subprocess.Popen('start %s' % open_ephys_path, shell=True)

        self.collect_frame.connect(self.update_frame)
        self.collect_threshed.connect(self.update_threshed)
        self.acquiring = False
        self.recording = False

        self.video_height = self.window_height * .52
        self.video_width = self.window_width * .48

        self.resize(self.window_width, self.window_height)

        #create QTextEdit window 'terminal' for receiving stdout and stderr
        self.terminal = QTextEdit(self)
        #set the geometry
        self.terminal.setGeometry(
            QRect(self.window_width * .02,
                  self.window_height * .15 + self.video_height,
                  self.video_width * .96, 150))

        #make widgets
        self.setup_video_frames()
        self.setup_thresh_buttons()

        self.overlay = True

        #create thread and worker for video processing
        self.videoThread = QThread(self)
        self.videoThread.start()
        self.videoproc_worker = VideoWorker(self)
        self.videoproc_worker.moveToThread(self.videoThread)

        self.vt_file = None
        """""" """""" """""" """""" """""" """""" """""" """
        set up menus
        """ """""" """""" """""" """""" """""" """""" """"""

        #create a QMenuBar and set geometry
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(
            QRect(0, 0, self.window_width * .5, self.window_height * .03))
        #set the QMenuBar as menu bar for main window
        self.setMenuBar(self.menubar)

        #create a QStatusBar
        statusbar = QStatusBar(self)
        #set it as status bar for main window
        self.setStatusBar(statusbar)

        #create icon toolbar with default image
        iconToolBar = self.addToolBar("iconBar.png")

        #create a QAction for the acquire button
        self.action_Acq = QAction(self)
        #make it checkable
        self.action_Acq.setCheckable(True)
        #grab an icon for the button
        acq_icon = self.style().standardIcon(QStyle.SP_MediaPlay)
        #set the icon for the action
        self.action_Acq.setIcon(acq_icon)
        #when the button is pressed, call the Acquire function
        self.action_Acq.triggered.connect(self.Acquire)

        #create a QAction for the record button
        self.action_Record = QAction(self)
        #make it checkable
        self.action_Record.setCheckable(True)
        #grab an icon for the button
        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)
        #when the button is pressed, call advanced_settings function
        self.action_Record.triggered.connect(self.Record)

        #create QAction for stop button
        action_Stop = QAction(self)
        #grab close icon
        stop_icon = self.style().standardIcon(QStyle.SP_MediaStop)
        #set icon for action
        action_Stop.setIcon(stop_icon)
        #when button pressed, close window
        action_Stop.triggered.connect(self.Stop)

        #show tips for each action in the status bar
        self.action_Acq.setStatusTip("Start acquiring")
        self.action_Record.setStatusTip("Start recording")
        action_Stop.setStatusTip("Stop acquiring/recording")

        #add actions to icon toolbar
        iconToolBar.addAction(self.action_Acq)
        iconToolBar.addAction(self.action_Record)
        iconToolBar.addAction(action_Stop)

        #        self.sort_button = QPushButton('Sort Now',self)
        #        self.sort_button.setGeometry(QRect(self.window_width*.85,0,self.window_width*.15,self.window_height*.05))
        #        self.sort_button.clicked.connect(self.sort_now)

        #show the window if minimized by windows
        self.showMinimized()
        self.showNormal()
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""

    #this function acts as a slot to accept 'message' signal
    @Slot(str)
    def print_message(self, message):
        ''' print stdout and stderr to terminal window '''

        #move terminal cursor to end
        self.terminal.moveCursor(QTextCursor.End)
        #write message to terminal
        self.terminal.insertPlainText(message)

    def setup_thresh_buttons(self):
        ''' set up buttons for overlay/clearing thresh view '''

        self.button_frame = QFrame(self)
        self.button_frame.setGeometry(
            QRect(self.window_width * .52,
                  self.window_height * .13 + self.video_height,
                  self.video_width * .98, 50))
        button_layout = QHBoxLayout()
        self.button_frame.setLayout(button_layout)
        self.clear_button = QPushButton('Clear')
        self.overlay_button = QPushButton('Overlay')
        button_layout.addWidget(self.clear_button)
        button_layout.addWidget(self.overlay_button)

        self.clear_button.setEnabled(False)
        self.clear_button.clicked.connect(self.clear_threshed)
        self.overlay_button.setEnabled(False)
        self.overlay_button.clicked.connect(self.overlay_threshed)

    def setup_video_frames(self):
        ''' set up spots for playing video frames '''

        filler_frame = np.zeros((360, 540, 3))
        filler_frame = qimage2ndarray.array2qimage(filler_frame)

        self.raw_frame = QFrame(self)
        self.raw_label = QLabel()
        self.raw_label.setText('raw')
        self.raw_frame.setGeometry(
            QRect(self.window_width * .01, self.window_height * .15,
                  self.video_width, self.video_height))
        self.raw_frame
        raw_layout = QVBoxLayout()
        self.raw_frame.setLayout(raw_layout)
        raw_layout.addWidget(self.raw_label)

        self.threshed_frame = QFrame(self)
        self.threshed_label = QLabel()
        self.threshed_label.setText('Threshed')
        self.threshed_frame.setGeometry(
            QRect(self.window_width * .51, self.window_height * .15,
                  self.video_width, self.video_height))
        threshed_layout = QVBoxLayout()
        self.threshed_frame.setLayout(threshed_layout)
        threshed_layout.addWidget(self.threshed_label)

        self.label_frame = QFrame(self)
        self.label_frame.setGeometry(
            QRect(self.window_width * .01, self.window_height * .11,
                  self.video_width * 2, 50))
        self.label_rawlabel = QLabel()
        self.label_rawlabel.setText('Raw Video')
        self.label_threshedlabel = QLabel()
        self.label_threshedlabel.setText('Threshold View')
        label_layout = QHBoxLayout()
        self.label_frame.setLayout(label_layout)
        label_layout.addWidget(self.label_rawlabel)
        label_layout.addWidget(self.label_threshedlabel)

        self.raw_label.setPixmap(QPixmap.fromImage(filler_frame))
        self.threshed_label.setPixmap(QPixmap.fromImage(filler_frame))

    def Acquire(self):

        if self.action_Acq.isChecked():

            self.vidbuffer = []

            if self.recording:

                while 1:
                    try:
                        self.sock.send('StopRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.recording = False

            else:
                #create and start a thread to transport a worker to later
                self.workerThread = QThread(self)
                self.workerThread.start()
                #create a worker object based on Worker class and move it to our
                #worker thread
                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_acq.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.acquiring = True
                self.start_acq.connect(self.worker.acquire)
                self.start_acq.emit('start!')

            self.action_Acq.setEnabled(False)
            self.action_Record.setChecked(False)
            self.action_Record.setEnabled(True)

            record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)

    def Record(self):

        if self.action_Record.isChecked():

            if not self.acquiring:
                self.workerThread = QThread(self)
                self.workerThread.start()

                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_rec.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.start_rec.connect(self.worker.acquire)
                self.recording = True
                self.start_rec.emit('start!')

            else:

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.recording = True

            record_icon = self.style().standardIcon(QStyle.SP_DialogNoButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)
            self.action_Record.setEnabled(False)

            self.action_Acq.setChecked(False)
            self.action_Acq.setEnabled(True)

    def Stop(self):

        self.acquiring = False
        self.recording = False

        while 1:
            try:
                self.sock.send('isRecording')
                rec = self.sock.recv()
            except:
                continue
            break

        if rec == '1':
            while 1:
                try:
                    self.sock.send('StopRecord')
                    self.sock.recv()
                except:
                    continue
                break

            self.action_Record.setEnabled(True)
            self.action_Record.setChecked(False)

        while 1:
            try:
                self.sock.send('isAcquiring')
                acq = self.sock.recv_string()
            except:
                continue
            break

        if acq == '1':
            while 1:
                try:
                    self.sock.send('StopAcquisition')
                    self.sock.recv()
                except:
                    continue
                break

        self.action_Acq.setEnabled(True)
        self.action_Acq.setChecked(False)

        try:
            #open a csv file for saving tracking data
            with open(self.vt_file, 'a') as csvfile:
                #create a writer
                vidwriter = csv.writer(csvfile, dialect='excel-tab')
                #check if it's an empty file
                for row in self.vidbuffer:
                    vidwriter.writerow(row)

        except:
            pass

        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)

    def update_frame(self, image):
        self.raw_label.setPixmap(QPixmap.fromImage(image))

    def update_threshed(self, threshed_image):
        self.threshed_label.setPixmap(QPixmap.fromImage(threshed_image))

    def clear_threshed(self):
        self.green_frame = np.zeros_like(self.green_frame)
        self.red_frame = np.zeros_like(self.red_frame)

    def overlay_threshed(self):
        if self.overlay:
            self.overlay = False
        elif not self.overlay:
            self.overlay = True


#    def sort_now(self):
#
#        if self.recdir is not None:
#            os.chdir('./kilosort_control')
#            #create and show the main window
#            self.sort_frame = kilosort_control.sort_gui.MainWindow()
#            self.sort_frame.show()
#
#            #set up stream for stdout and stderr based on outputStream class
#            self.outputStream = kilosort_control.sort_gui.outputStream()
#            #when outputStream sends messages, connect to appropriate function for
#            #writing to terminal window
#            self.outputStream.message.connect(self.sort_frame.print_message)
#
#            #connect stdout and stderr to outputStream
#            sys.stdout = self.outputStream
#            sys.stderr = self.outputStream
#
#            self.sort_frame.run_now(self.recdir)
#
#            self.close()

    def get_info(self):

        self.info_window = QWidget()
        self.info_window.resize(400, 350)
        #set title
        self.info_window.setWindowTitle('Session Info')
        #give layout
        info_layout = QVBoxLayout(self.info_window)

        with open('info_fields.pickle', 'rb') as f:
            default_fields = pickle.load(f)
            f.close()

        #set label for pic_resolution setting
        experimenter_label = QLabel('Experimenter:')
        #make a QLineEdit box for displaying/editing settings
        experimenter = QComboBox(self.info_window)
        experimenter.setEditable(True)
        experimenter.addItems(default_fields['experimenter'])
        #add label and box to current window
        info_layout.addWidget(experimenter_label)
        info_layout.addWidget(experimenter)

        #set label for pic_resolution setting
        whose_animal_label = QLabel('Whose animal?')
        #make a QLineEdit box for displaying/editing settings
        whose_animal = QComboBox(self.info_window)
        whose_animal.setEditable(True)
        whose_animal.addItems(default_fields['whose_animal'])
        #add label and box to current window
        info_layout.addWidget(whose_animal_label)
        info_layout.addWidget(whose_animal)

        animal_number_label = QLabel('Animal number:')
        animal_number = QComboBox(self.info_window)
        animal_number.setEditable(True)
        animal_number.addItems(default_fields['animal_number'])
        info_layout.addWidget(animal_number_label)
        info_layout.addWidget(animal_number)

        session_number_label = QLabel('Session number:')
        session_number = QTextEdit(self.info_window)
        session_number.setText('1')
        info_layout.addWidget(session_number_label)
        info_layout.addWidget(session_number)

        session_type_label = QLabel('Session type:')
        session_type = QComboBox(self.info_window)
        session_type.setEditable(True)
        session_type.addItems(default_fields['session_type'])
        info_layout.addWidget(session_type_label)
        info_layout.addWidget(session_type)

        def save_info(self):

            info_fields = {}
            info_fields['experimenter'] = [
                experimenter.itemText(i) for i in range(experimenter.count())
            ]
            info_fields['whose_animal'] = [
                whose_animal.itemText(i) for i in range(whose_animal.count())
            ]
            info_fields['animal_number'] = [
                animal_number.itemText(i) for i in range(animal_number.count())
            ]
            info_fields['session_type'] = [
                session_type.itemText(i) for i in range(session_type.count())
            ]

            with open('info_fields.pickle', 'wb') as f:
                pickle.dump(info_fields, f, protocol=2)
                f.close()

            current_experimenter = str(experimenter.currentText())
            current_whose_animal = str(whose_animal.currentText())
            current_animal_number = str(animal_number.currentText())
            current_session_number = str(session_number.toPlainText())
            current_session_type = str(session_type.currentText())

            recdir = data_save_dir + current_whose_animal + '/' + current_animal_number

            if not os.path.exists(recdir):
                os.makedirs(recdir)

            self.experiment_info = '###### Experiment Info ######\r\n'
            self.experiment_info += 'Experimenter: %s\r\n' % current_experimenter
            self.experiment_info += 'Whose animal? %s\r\n' % current_whose_animal
            self.experiment_info += 'Animal number: %s\r\n' % current_animal_number
            self.experiment_info += 'Session number: %s\r\n' % current_session_number
            self.experiment_info += 'Session type: %s\r\n' % current_session_type

            self.experiment_info = self.experiment_info.encode()

            config_file = config_path + '/' + current_animal_number + '.xml'

            if not os.path.exists(config_file):
                shutil.copy(default_config, config_file)

            tree = et.parse(config_file)
            root = tree.getroot()
            for child in root:
                if child.tag == 'CONTROLPANEL':
                    child.attrib['recordPath'] = recdir.replace('/', '\\')
            tree.write(config_file)
            tree.write(default_config)

            self.info_window.close()
            self.noinfo = False

        ready_button = QPushButton('Ready!')
        ready_button.clicked.connect(lambda: save_info(self))
        info_layout.addWidget(ready_button)

        self.info_window.show()
Ejemplo n.º 32
0
def createAction(self, icon, toolTip, statusTip, scripted=False):
    """
    TOWRITE

    :param `icon`: TOWRITE
    :type `icon`: QString
    :param `toolTip`: TOWRITE
    :type `toolTip`: QString
    :param `statusTip`: TOWRITE
    :type `statusTip`: QString
    :param `scripted`: TOWRITE
    :type `scripted`: bool
    :rtype: `QAction`_

    .. TODO:: send the global Icon, Image, Commands Dirs in to be used.

    """
    connect = self.connect  # NOT local optimization, but for ease of the code looking similar to the C++ whash
    mdiArea = self.mdiArea  # ditto

    ACTION = QAction(
        QIcon(self.gIconDir + os.sep + self.getSettingsGeneralIconTheme() +
              "/" + icon + ".png"), toolTip, self
    )  # QAction *  # TODO: Qt4.7 wont load icons without an extension...
    ACTION.setStatusTip(statusTip)
    ACTION.setObjectName(icon)
    # TODO: Set What's This Context Help to statusTip for now so there is some infos there.
    # Make custom whats this context help popup with more descriptive help than just
    # the status bar/tip one liner(short but not real long) with a hyperlink in the custom popup
    # at the bottom to open full help file description. Ex: like wxPython AGW's SuperToolTip.
    ACTION.setWhatsThis(statusTip)
    # TODO: Finish All Commands ... <.<

    if icon == "donothing":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("doNothing()"))
    elif icon == "new":
        ACTION.setShortcut(QKeySequence.New)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("newFile()"))
    elif icon == "open":
        ACTION.setShortcut(QKeySequence.Open)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("openFile()"))
    elif icon == "save":
        ACTION.setShortcut(QKeySequence.Save)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("savefile()"))
    elif icon == "saveas":
        ACTION.setShortcut(QKeySequence.SaveAs)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("saveasfile()"))
    elif icon == "print":
        ACTION.setShortcut(QKeySequence.Print)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("print_()"))
    elif icon == "designdetails":
        ACTION.setShortcut(QKeySequence("Ctrl+D"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("designDetails()"))
    elif icon == "exit":
        ACTION.setShortcut(QKeySequence("Ctrl+Q"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("exit()"))

    elif icon == "cut":
        ACTION.setShortcut(QKeySequence.Cut)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("cut()"))
    elif icon == "copy":
        ACTION.setShortcut(QKeySequence.Copy)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("copy()"))
    elif icon == "paste":
        ACTION.setShortcut(QKeySequence.Paste)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("paste()"))

    elif icon == "windowcascade":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("cascade()"))
    elif icon == "windowtile":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("tile()"))
    elif icon == "windowclose":
        ACTION.setShortcut(QKeySequence.Close)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("onCloseWindow()"))
    elif icon == "windowcloseall":
        connect(ACTION, SIGNAL("triggered()"), mdiArea,
                SLOT("closeAllSubWindows()"))
    elif icon == "windownext":
        ACTION.setShortcut(QKeySequence.NextChild)
        connect(ACTION, SIGNAL("triggered()"), mdiArea,
                SLOT("activateNextSubWindow()"))
    elif icon == "windowprevious":
        ACTION.setShortcut(QKeySequence.PreviousChild)
        connect(ACTION, SIGNAL("triggered()"), mdiArea,
                SLOT("activatePreviousSubWindow()"))

    elif icon == "help":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("help()"))
    elif icon == "changelog":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("changelog()"))
    elif icon == "tipoftheday":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("tipOfTheDay()"))
    elif icon == "about":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("about()"))
    elif icon == "whatsthis":
        connect(ACTION, SIGNAL("triggered()"), self,
                SLOT("whatsThisContextHelp()"))

    elif icon == "icon16":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon16()"))
    elif icon == "icon24":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon24()"))
    elif icon == "icon32":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon32()"))
    elif icon == "icon48":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon48()"))
    elif icon == "icon64":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon64()"))
    elif icon == "icon128":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon128()"))

    elif icon == "settingsdialog":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("settingsDialog()"))

    elif icon == "undo":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("undo()"))
    elif icon == "redo":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("redo()"))

    elif icon == "makelayercurrent":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("makeLayerActive()"))
    elif icon == "layers":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerManager()"))
    elif icon == "layerprevious":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerPrevious()"))

    elif icon == "textbold":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextBold(bool)"))
    elif icon == "textitalic":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextItalic(bool)"))
    elif icon == "textunderline":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextUnderline(bool)"))
    elif icon == "textstrikeout":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextStrikeOut(bool)"))
    elif icon == "textoverline":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self,
                SLOT("setTextOverline(bool)"))

    elif icon == "zoomrealtime":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomRealtime()"))
    elif icon == "zoomprevious":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomPrevious()"))
    elif icon == "zoomwindow":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomWindow()"))
    elif icon == "zoomdynamic":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomDynamic()"))
    elif icon == "zoomscale":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomScale()"))
    elif icon == "zoomcenter":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomCenter()"))
    elif icon == "zoomin":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomIn()"))
    elif icon == "zoomout":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomOut()"))
    elif icon == "zoomselected":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomSelected()"))
    elif icon == "zoomall":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomAll()"))
    elif icon == "zoomextents":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomExtents()"))

    elif icon == "panrealtime":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panrealtime()"))
    elif icon == "panpoint":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panpoint()"))
    elif icon == "panleft":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panLeft()"))
    elif icon == "panright":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panRight()"))
    elif icon == "panup":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panUp()"))
    elif icon == "pandown":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panDown()"))

    elif icon == "day":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("dayVision()"))
    elif icon == "night":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("nightVision()"))

    elif scripted:
        ACTION.setIcon(
            QIcon(self.gAppDir + os.sep + "commands/" + icon + "/" + icon +
                  ".png"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("runCommand()"))

    else:
        ACTION.setEnabled(False)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("stub_implement()"))

    return ACTION
Ejemplo n.º 33
0
    class MainWindow(QWidget):
        def __init__(self, grid, U):
            assert isinstance(U, Communicable)
            super(MainWindow, self).__init__()

            U = U.data

            layout = QVBoxLayout()

            plotBox = QHBoxLayout()
            plot = GlumpyPatchWidget(self, grid, vmin=np.min(U), vmax=np.max(U), bounding_box=bounding_box, codim=codim)
            bar = ColorBarWidget(self, vmin=np.min(U), vmax=np.max(U))
            plotBox.addWidget(plot)
            plotBox.addWidget(bar)
            layout.addLayout(plotBox)

            if len(U) == 1:
                plot.set(U.ravel())
            else:
                plot.set(U[0])

                hlayout = QHBoxLayout()

                self.slider = QSlider(Qt.Horizontal)
                self.slider.setMinimum(0)
                self.slider.setMaximum(len(U) - 1)
                self.slider.setTickPosition(QSlider.TicksBelow)
                hlayout.addWidget(self.slider)

                lcd = QLCDNumber(m.ceil(m.log10(len(U))))
                lcd.setDecMode()
                lcd.setSegmentStyle(QLCDNumber.Flat)
                hlayout.addWidget(lcd)

                layout.addLayout(hlayout)

                hlayout = QHBoxLayout()

                toolbar = QToolBar()
                self.a_play = QAction(self.style().standardIcon(QStyle.SP_MediaPlay), 'Play', self)
                self.a_play.setCheckable(True)
                self.a_rewind = QAction(self.style().standardIcon(QStyle.SP_MediaSeekBackward), 'Rewind', self)
                self.a_toend = QAction(self.style().standardIcon(QStyle.SP_MediaSeekForward), 'End', self)
                self.a_step_backward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipBackward), 'Step Back', self)
                self.a_step_forward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipForward), 'Step', self)
                self.a_loop = QAction(self.style().standardIcon(QStyle.SP_BrowserReload), 'Loop', self)
                self.a_loop.setCheckable(True)
                toolbar.addAction(self.a_play)
                toolbar.addAction(self.a_rewind)
                toolbar.addAction(self.a_toend)
                toolbar.addAction(self.a_step_backward)
                toolbar.addAction(self.a_step_forward)
                toolbar.addAction(self.a_loop)
                hlayout.addWidget(toolbar)

                self.speed = QSlider(Qt.Horizontal)
                self.speed.setMinimum(0)
                self.speed.setMaximum(100)
                hlayout.addWidget(QLabel('Speed:'))
                hlayout.addWidget(self.speed)

                layout.addLayout(hlayout)

                self.timer = QTimer()
                self.timer.timeout.connect(self.update_solution)

                self.slider.valueChanged.connect(self.slider_changed)
                self.slider.valueChanged.connect(lcd.display)
                self.speed.valueChanged.connect(self.speed_changed)
                self.a_play.toggled.connect(self.toggle_play)
                self.a_rewind.triggered.connect(self.rewind)
                self.a_toend.triggered.connect(self.to_end)
                self.a_step_forward.triggered.connect(self.step_forward)
                self.a_step_backward.triggered.connect(self.step_backward)

                self.speed.setValue(50)

            self.setLayout(layout)
            self.plot = plot
            self.U = U

        def slider_changed(self, ind):
            self.plot.set(self.U[ind])

        def speed_changed(self, val):
            self.timer.setInterval(val * 20)

        def update_solution(self):
            ind = self.slider.value() + 1
            if ind >= len(self.U):
                if self.a_loop.isChecked():
                    ind = 0
                else:
                    self.a_play.setChecked(False)
                    return
            self.slider.setValue(ind)

        def toggle_play(self, checked):
            if checked:
                if self.slider.value() + 1 == len(self.U):
                    self.slider.setValue(0)
                self.timer.start()
            else:
                self.timer.stop()

        def rewind(self):
            self.slider.setValue(0)

        def to_end(self):
            self.a_play.setChecked(False)
            self.slider.setValue(len(self.U) - 1)

        def step_forward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() + 1
            if ind == len(self.U) and self.a_loop.isChecked():
                ind = 0
            if ind < len(self.U):
                self.slider.setValue(ind)

        def step_backward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() - 1
            if ind == -1 and self.a_loop.isChecked():
                ind = len(self.U) - 1
            if ind >= 0:
                self.slider.setValue(ind)
Ejemplo n.º 34
0
class Editor(QMainWindow):  # TODO: kill this god shit
    """Note editor"""

    def __init__(self, note, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.app = QApplication.instance()
        self.note = note
        self.closed = False
        self.ui = Ui_Editor()
        self.ui.setupUi(self)
        self.setWindowIcon(get_icon())
        self.alternatives_template =\
            self.ui.alternativeVersions.text()
        self.init_controls()
        self.load_note(note)
        self.update_title()
        self.mark_untouched()
        geometry = self.app.settings.value("note-geometry-%d" % self.note.id)
        if not geometry:
            geometry = self.app.settings.value("note-geometry-default")
        if geometry:
            self.restoreGeometry(geometry)
        self.resource_edit.note = note

    def init_controls(self):
        self.ui.menubar.hide()
        self.ui.resourceArea.hide()
        self.note_edit = ContentEdit(
            self, self.ui.contentView, self.text_changed,
        )
        self.tag_edit = TagEdit(
            self, self.ui.tags, self.mark_touched,
        )
        self.notebook_edit = NotebookEdit(
            self, self.ui.notebook, self.mark_touched,
        )
        self.resource_edit = ResourceEdit(
            self, self.ui.resourceArea,
            self.ui.resourceLabel, self.mark_touched,
        )
        self.findbar = FindBar(self)
        self.init_toolbar()
        self.init_shortcuts()
        self.init_alternatives()
        self.app.data_changed.connect(self.init_alternatives)

    def init_alternatives(self):
        try:
            conflict_items = self.app.provider.get_note_alternatives(self.note.id)
            if conflict_items:
                conflicts = map(
                    lambda item: Note.from_tuple(self.app.provider.get_note(
                        item,
                    )), self.note.conflict_items,
                )
                text = self.alternatives_template % ', '.join(map(
                    lambda note: u'<a href="%d">%s</a>' % (
                        note.id, note.title,
                    ), conflicts,
                ))
                self.ui.alternativeVersions.setText(text)
                self.ui.alternativeVersions.linkActivated.connect(
                    lambda id: self.app.indicator.open(
                        Note.from_tuple(self.app.provider.get_note(int(id))),
                    )
                )
            else:
                self.ui.alternativeVersions.hide()
        except DBusException:
            self.ui.alternativeVersions.hide()

    def init_shortcuts(self):
        self.save_btn.setShortcut(QKeySequence('Ctrl+s'))
        self.close_btn.setShortcut(QKeySequence('Ctrl+q'))
        self.email_btn.setShortcut(QKeySequence('Ctrl+Shift+e'))
        self.print_btn.setShortcut(QKeySequence(self.tr('Ctrl+p')))
        QShortcut(QKeySequence(self.tr('Ctrl+w')), self, self.save_and_close)

    def init_toolbar(self):
        self.save_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('document-save'),
            self.tr('Save'), self.save,
        )
        self.close_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('window-close'),
            self.tr('Close without saving'),
            self.close,
        )
        self.ui.toolBar.addAction(
            QIcon.fromTheme('edit-delete'),
            self.tr('Remove note'),
            self.delete,
        )
        self.print_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('document-print'),
            self.tr('Print note'),
            self.note_edit.print_,
        )
        self.email_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('mail-unread'),
            self.tr('Email note'),
            self.note_edit.email_note,
        )
        self.email_btn = self.ui.toolBar.addAction(
            QIcon.fromTheme('emblem-shared'),
            self.tr('Share note'),
            self.share_note,
        )
        self.ui.toolBar.addSeparator()
        for action in self.note_edit.get_format_actions():
            self.ui.toolBar.addAction(action)
        self.ui.toolBar.addSeparator()
        self.find_action = QAction(QIcon.fromTheme('edit-find'),
                                   self.tr('Find'), self)
        self.find_action.setCheckable(True)
        self.find_action.triggered.connect(self.findbar.toggle_visible)
        self.ui.toolBar.addAction(self.find_action)
        self.ui.toolBar.addSeparator()
        self.pin = self.ui.toolBar.addAction(
            QIcon.fromTheme('edit-pin', QIcon.fromTheme('everpad-pin')),
            self.tr('Pin note'), self.mark_touched,
        )
        self.pin.setCheckable(True)
        self.pin.setChecked(self.note.pinnded)

    def load_note(self, note):
        self.resource_edit.resources = map(Resource.from_tuple,
            self.app.provider.get_note_resources(note.id),
        )
        self.notebook_edit.notebook = note.notebook
        self.note_edit.title = note.title
        self.note_edit.content = note.content
        self.tag_edit.tags = note.tags

    def update_note(self):
        self.note.notebook = self.notebook_edit.notebook
        self.note.title = self.note_edit.title
        self.note.content = self.note_edit.content
        self.note.tags = dbus.Array(self.tag_edit.tags, signature='s')
        self.note.pinnded = self.pin.isChecked()

    def closeEvent(self, event):
        event.ignore()
        self.save_and_close()

    def text_changed(self):
        self.update_title()
        self.mark_touched()

    def update_title(self):
        title = self.note_edit.title
        if self.note.conflict_parent:
            title += self.tr(' altrentive of: %s') % (
                Note.from_tuple(self.app.provider.get_note(
                    self.note.conflict_parent,
                )).title,
            )
        self.setWindowTitle(self.tr('Everpad / %s') % title)

    @Slot()
    def save(self):
        self.mark_untouched()
        self.update_note()
        self.app.provider.update_note(self.note.struct)
        self.app.provider.update_note_resources(
            self.note.struct, dbus.Array(map(lambda res:
                res.struct, self.resource_edit.resources,
            ), signature=Resource.signature),
        )
        self.app.send_notify(self.tr('Note "%s" saved!') % self.note.title)

    @Slot()
    def save_and_close(self):
        if self.touched:
            self.save()
        self.close()

    @Slot()
    def delete(self):
        msgBox = QMessageBox(
            QMessageBox.Critical,
            self.tr("You are trying to delete a note"),
            self.tr("Are you sure want to delete this note?"),
            QMessageBox.Yes | QMessageBox.No
        )
        ret = msgBox.exec_()
        if ret == QMessageBox.Yes:
            self.update_note()
            self.app.provider.delete_note(self.note.id)
            self.app.send_notify(self.tr('Note "%s" deleted!') % self.note.title)
            self.close()

    @Slot()
    def close(self):
        msg = QMessageBox(
            QMessageBox.Critical,
            self.tr("Close without Saving"),
            self.tr("Are you sure want to close this note without saving?"),
            QMessageBox.Yes | QMessageBox.No
        )
        if not self.touched or msg.exec_() == QMessageBox.Yes:
            self.hide()
            self.closed = True
            self.app.settings.setValue(
                "note-geometry-%d" % self.note.id,
                self.saveGeometry(),
            )
            self.app.settings.setValue(
                "note-geometry-default", self.saveGeometry(),
            )

    @Slot()
    def mark_touched(self):
        self.touched = True
        self.ui.actionSave.setEnabled(True)
        self.save_btn.setEnabled(True)

    def mark_untouched(self):
        self.touched = False
        self.ui.actionSave.setEnabled(False)
        self.save_btn.setEnabled(False)

    def share_note(self):
        dialog = ShareNoteDialog(self.note, parent=self)
        dialog.exec_()
Ejemplo n.º 35
0
    class PlotMainWindow(QWidget):
        """Base class for plot main windows."""

        def __init__(self, U, plot, length=1, title=None):
            super(PlotMainWindow, self).__init__()

            layout = QVBoxLayout()

            if title:
                title = QLabel('<b>' + title + '</b>')
                title.setAlignment(Qt.AlignHCenter)
                layout.addWidget(title)
            layout.addWidget(plot)

            plot.set(U, 0)

            if length > 1:
                hlayout = QHBoxLayout()

                self.slider = QSlider(Qt.Horizontal)
                self.slider.setMinimum(0)
                self.slider.setMaximum(length - 1)
                self.slider.setTickPosition(QSlider.TicksBelow)
                hlayout.addWidget(self.slider)

                lcd = QLCDNumber(m.ceil(m.log10(length)))
                lcd.setDecMode()
                lcd.setSegmentStyle(QLCDNumber.Flat)
                hlayout.addWidget(lcd)

                layout.addLayout(hlayout)

                hlayout = QHBoxLayout()

                toolbar = QToolBar()
                self.a_play = QAction(self.style().standardIcon(QStyle.SP_MediaPlay), 'Play', self)
                self.a_play.setCheckable(True)
                self.a_rewind = QAction(self.style().standardIcon(QStyle.SP_MediaSeekBackward), 'Rewind', self)
                self.a_toend = QAction(self.style().standardIcon(QStyle.SP_MediaSeekForward), 'End', self)
                self.a_step_backward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipBackward),
                                               'Step Back', self)
                self.a_step_forward = QAction(self.style().standardIcon(QStyle.SP_MediaSkipForward), 'Step', self)
                self.a_loop = QAction(self.style().standardIcon(QStyle.SP_BrowserReload), 'Loop', self)
                self.a_loop.setCheckable(True)
                toolbar.addAction(self.a_play)
                toolbar.addAction(self.a_rewind)
                toolbar.addAction(self.a_toend)
                toolbar.addAction(self.a_step_backward)
                toolbar.addAction(self.a_step_forward)
                toolbar.addAction(self.a_loop)
                if hasattr(self, 'save'):
                    self.a_save = QAction(self.style().standardIcon(QStyle.SP_DialogSaveButton), 'Save', self)
                    toolbar.addAction(self.a_save)
                    self.a_save.triggered.connect(self.save)
                hlayout.addWidget(toolbar)

                self.speed = QSlider(Qt.Horizontal)
                self.speed.setMinimum(0)
                self.speed.setMaximum(100)
                hlayout.addWidget(QLabel('Speed:'))
                hlayout.addWidget(self.speed)

                layout.addLayout(hlayout)

                self.timer = QTimer()
                self.timer.timeout.connect(self.update_solution)

                self.slider.valueChanged.connect(self.slider_changed)
                self.slider.valueChanged.connect(lcd.display)
                self.speed.valueChanged.connect(self.speed_changed)
                self.a_play.toggled.connect(self.toggle_play)
                self.a_rewind.triggered.connect(self.rewind)
                self.a_toend.triggered.connect(self.to_end)
                self.a_step_forward.triggered.connect(self.step_forward)
                self.a_step_backward.triggered.connect(self.step_backward)

                self.speed.setValue(50)

            elif hasattr(self, 'save'):
                hlayout = QHBoxLayout()
                toolbar = QToolBar()
                self.a_save = QAction(self.style().standardIcon(QStyle.SP_DialogSaveButton), 'Save', self)
                toolbar.addAction(self.a_save)
                hlayout.addWidget(toolbar)
                layout.addLayout(hlayout)
                self.a_save.triggered.connect(self.save)

            self.setLayout(layout)
            self.plot = plot
            self.U = U
            self.length = length

        def slider_changed(self, ind):
            self.plot.set(self.U, ind)

        def speed_changed(self, val):
            self.timer.setInterval(val * 20)

        def update_solution(self):
            ind = self.slider.value() + 1
            if ind >= self.length:
                if self.a_loop.isChecked():
                    ind = 0
                else:
                    self.a_play.setChecked(False)
                    return
            self.slider.setValue(ind)

        def toggle_play(self, checked):
            if checked:
                if self.slider.value() + 1 == self.length:
                    self.slider.setValue(0)
                self.timer.start()
            else:
                self.timer.stop()

        def rewind(self):
            self.slider.setValue(0)

        def to_end(self):
            self.a_play.setChecked(False)
            self.slider.setValue(self.length - 1)

        def step_forward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() + 1
            if ind == self.length and self.a_loop.isChecked():
                ind = 0
            if ind < self.length:
                self.slider.setValue(ind)

        def step_backward(self):
            self.a_play.setChecked(False)
            ind = self.slider.value() - 1
            if ind == -1 and self.a_loop.isChecked():
                ind = self.length - 1
            if ind >= 0:
                self.slider.setValue(ind)
Ejemplo n.º 36
0
def createAction(self, icon, toolTip, statusTip, scripted=False):
    """
    TOWRITE

    :param `icon`: TOWRITE
    :type `icon`: QString
    :param `toolTip`: TOWRITE
    :type `toolTip`: QString
    :param `statusTip`: TOWRITE
    :type `statusTip`: QString
    :param `scripted`: TOWRITE
    :type `scripted`: bool
    :rtype: `QAction`_

    .. TODO:: send the global Icon, Image, Commands Dirs in to be used.

    """
    connect = self.connect  # NOT local optimization, but for ease of the code looking similar to the C++ whash
    mdiArea = self.mdiArea  # ditto

    ACTION = QAction(
        QIcon(self.gIconDir + os.sep + self.getSettingsGeneralIconTheme() + "/" + icon + ".png"), toolTip, self
    )  # QAction *  # TODO: Qt4.7 wont load icons without an extension...
    ACTION.setStatusTip(statusTip)
    ACTION.setObjectName(icon)
    # TODO: Set What's This Context Help to statusTip for now so there is some infos there.
    # Make custom whats this context help popup with more descriptive help than just
    # the status bar/tip one liner(short but not real long) with a hyperlink in the custom popup
    # at the bottom to open full help file description. Ex: like wxPython AGW's SuperToolTip.
    ACTION.setWhatsThis(statusTip)
    # TODO: Finish All Commands ... <.<

    if icon == "donothing":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("doNothing()"))
    elif icon == "new":
        ACTION.setShortcut(QKeySequence.New)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("newFile()"))
    elif icon == "open":
        ACTION.setShortcut(QKeySequence.Open)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("openFile()"))
    elif icon == "save":
        ACTION.setShortcut(QKeySequence.Save)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("savefile()"))
    elif icon == "saveas":
        ACTION.setShortcut(QKeySequence.SaveAs)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("saveasfile()"))
    elif icon == "print":
        ACTION.setShortcut(QKeySequence.Print)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("print_()"))
    elif icon == "designdetails":
        ACTION.setShortcut(QKeySequence("Ctrl+D"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("designDetails()"))
    elif icon == "exit":
        ACTION.setShortcut(QKeySequence("Ctrl+Q"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("exit()"))

    elif icon == "cut":
        ACTION.setShortcut(QKeySequence.Cut)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("cut()"))
    elif icon == "copy":
        ACTION.setShortcut(QKeySequence.Copy)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("copy()"))
    elif icon == "paste":
        ACTION.setShortcut(QKeySequence.Paste)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("paste()"))

    elif icon == "windowcascade":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("cascade()"))
    elif icon == "windowtile":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("tile()"))
    elif icon == "windowclose":
        ACTION.setShortcut(QKeySequence.Close)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("onCloseWindow()"))
    elif icon == "windowcloseall":
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("closeAllSubWindows()"))
    elif icon == "windownext":
        ACTION.setShortcut(QKeySequence.NextChild)
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("activateNextSubWindow()"))
    elif icon == "windowprevious":
        ACTION.setShortcut(QKeySequence.PreviousChild)
        connect(ACTION, SIGNAL("triggered()"), mdiArea, SLOT("activatePreviousSubWindow()"))

    elif icon == "help":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("help()"))
    elif icon == "changelog":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("changelog()"))
    elif icon == "tipoftheday":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("tipOfTheDay()"))
    elif icon == "about":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("about()"))
    elif icon == "whatsthis":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("whatsThisContextHelp()"))

    elif icon == "icon16":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon16()"))
    elif icon == "icon24":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon24()"))
    elif icon == "icon32":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon32()"))
    elif icon == "icon48":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon48()"))
    elif icon == "icon64":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon64()"))
    elif icon == "icon128":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("icon128()"))

    elif icon == "settingsdialog":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("settingsDialog()"))

    elif icon == "undo":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("undo()"))
    elif icon == "redo":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("redo()"))

    elif icon == "makelayercurrent":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("makeLayerActive()"))
    elif icon == "layers":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerManager()"))
    elif icon == "layerprevious":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("layerPrevious()"))

    elif icon == "textbold":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextBold(bool)"))
    elif icon == "textitalic":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextItalic(bool)"))
    elif icon == "textunderline":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextUnderline(bool)"))
    elif icon == "textstrikeout":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextStrikeOut(bool)"))
    elif icon == "textoverline":
        ACTION.setCheckable(True)
        connect(ACTION, SIGNAL("toggled(bool)"), self, SLOT("setTextOverline(bool)"))

    elif icon == "zoomrealtime":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomRealtime()"))
    elif icon == "zoomprevious":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomPrevious()"))
    elif icon == "zoomwindow":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomWindow()"))
    elif icon == "zoomdynamic":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomDynamic()"))
    elif icon == "zoomscale":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomScale()"))
    elif icon == "zoomcenter":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomCenter()"))
    elif icon == "zoomin":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomIn()"))
    elif icon == "zoomout":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomOut()"))
    elif icon == "zoomselected":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomSelected()"))
    elif icon == "zoomall":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomAll()"))
    elif icon == "zoomextents":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("zoomExtents()"))

    elif icon == "panrealtime":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panrealtime()"))
    elif icon == "panpoint":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panpoint()"))
    elif icon == "panleft":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panLeft()"))
    elif icon == "panright":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panRight()"))
    elif icon == "panup":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panUp()"))
    elif icon == "pandown":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("panDown()"))

    elif icon == "day":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("dayVision()"))
    elif icon == "night":
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("nightVision()"))

    elif scripted:
        ACTION.setIcon(QIcon(self.gAppDir + os.sep + "commands/" + icon + "/" + icon + ".png"))
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("runCommand()"))

    else:
        ACTION.setEnabled(False)
        connect(ACTION, SIGNAL("triggered()"), self, SLOT("stub_implement()"))

    return ACTION