Exemplo n.º 1
0
 def initializeTray(self):
     self.tray = Tray(self, self.iface)
     self.cw.operation.finished.connect(self.trayAction)
     self.cw.operation.finished.connect(self.tray.stop)
     self.cw.operation.operationCancelled.connect(self.tray.stop)
     self.cw.operation.started.connect(self.tray.animate)
     self.tray.showUpdatesSelected.connect(self.trayShowUpdates)
Exemplo n.º 2
0
 def initializeTray(self):
     self.tray = Tray(self, self.iface)
     self.connect(self.cw.operation, SIGNAL("finished(QString)"),
                  self.trayAction)
     self.connect(self.cw.operation, SIGNAL("finished(QString)"),
                  self.tray.stop)
     self.connect(self.cw.operation, SIGNAL("operationCancelled()"),
                  self.tray.stop)
     self.connect(self.cw.operation, SIGNAL("started(QString)"),
                  self.tray.animate)
     self.connect(self.tray, SIGNAL("showUpdatesSelected()"),
                  self.trayShowUpdates)
Exemplo n.º 3
0
    def init(self):
        self.load_data('data')
        self.load_data('config')
        # 初始化分辨率
        if self.config['resolving'] == [0, 0]:
            self.config['resolving'] = self.resolving
            self.dump_data('config')
        else:
            self.resolving = self.config['resolving']
        for api in self.all_api[1:]:
            exec('self.%s = %s(self)' % (api, api))

        self.tray = Tray(self)
        self.switch_frame = SwitchFrame(self)
        self.right_frame = Right(self)
        self.set = Set(self)
        # 检查权限
        if not try_author():
            self.set.auto_start.setEnabled(False)

        self.choose_random = ChooseRandom(self.set, self)
        self.local_api = LocalWallpaper(self)
        self.verify = Verify(self)
        self.local_api.init_check()

        # qss
        with open('style.qss', 'r') as fp:
            self.setStyleSheet(fp.read())

        self.initializing = False
        if self.config['show_windmill'] == 0:
            self.hide()
        else:
            self.show()
Exemplo n.º 4
0
 def initializeTray(self):
     self.tray = Tray(self, self.iface)
     self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.trayAction)
     self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.tray.stop)
     self.connect(self.cw.operation, SIGNAL("operationCancelled()"), self.tray.stop)
     self.connect(self.cw.operation, SIGNAL("started(QString)"), self.tray.animate)
     self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)
Exemplo n.º 5
0
 def initializeTray(self):
     self.tray = Tray(self, self.iface)
     self.cw.operation.finished[str].connect(self.trayAction)
     self.cw.operation.finished[str].connect(self.tray.stop)
     self.cw.operation.operationCancelled.connect(self.tray.stop)
     self.cw.operation.started[str].connect(self.tray.animate)
     self.tray.showUpdatesSelected.connect(self.trayShowUpdates)         # buraya dikkat
Exemplo n.º 6
0
 def init(self):
     self.tray = Tray(self)
     self.head = Head(self)
     self.agenda = Agenda(self)
     self.set = Set(self)
     # qss
     with open('style.QSS', 'r') as fp:
         self.setStyleSheet(fp.read())
         fp.close()
Exemplo n.º 7
0
    def __init__(self):
        WindowBaseClass.__init__(self)
        self.setupUi(self)
        self._explicitQuit = False

        # Tunnels
        self._tunnels = []

        # Setup tray
        self.tray = Tray(self, "IOSSHy", QIcon(":/icons/network-server.png"))
        self.tray.activated.connect(self.activated)

        action = QAction("&Configure", self.tray.menu)
        action.setIcon(QIcon(":/icons/configure.png"))
        action.triggered.connect(self.show)
        self.tray.menu.addAction(action)
        self.tray.menu.setDefaultAction(action)

        self.tray.menu.addSeparator()
        self.actionNoTun = QAction("No tunnels configured", self.tray.menu)
        self.actionNoTun.setEnabled(False)
        self.tray.menu.addAction(self.actionNoTun)
        self.actionLastSep = self.tray.menu.addSeparator()

        if kde:
            action = QAction("&About", self.tray.menu)
            action.triggered.connect(self.about)
            self.tray.menu.addAction(action)

        action = QAction("&Quit", self.tray.menu)
        action.setIcon(QIcon(":/icons/application-exit.png"))
        action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q))
        action.triggered.connect(self.quit)
        self.tray.menu.addAction(action)

        # Load settings
        self.readSettings()
        self.hide()
Exemplo n.º 8
0
    def __init__(self):
        QDialog.__init__(self)
        self.setupUi(self)
        self._explicitQuit = False

        # Tunnels
        self._tunnels = []

        # Setup tray
        self.tray = Tray(self, "IOSSHy", Icon("network-server"))
        self.tray.activated.connect(self.activated)

        action = QAction("&Configure", self.tray.menu)
        action.setIcon(Icon("configure"))
        action.setIconVisibleInMenu(True)
        action.triggered.connect(self.show)
        self.tray.menu.addAction(action)
        self.tray.menu.setDefaultAction(action)

        self.tray.menu.addSeparator()
        self.actionNoTun = QAction("No tunnels configured", self.tray.menu)
        self.actionNoTun.setEnabled(False)
        self.tray.menu.addAction(self.actionNoTun)
        self.actionLastSep = self.tray.menu.addSeparator()

        if kde:
            action = QAction("&About", self.tray.menu)
            action.triggered.connect(self.about)
            self.tray.menu.addAction(action)

        action = QAction("&Quit", self.tray.menu)
        action.setIcon(Icon("application-exit"))
        action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q))
        action.triggered.connect(self.quit)
        self.tray.menu.addAction(action)

        # Load settings
        self.readSettings()
        self.hide()
Exemplo n.º 9
0
    def init(self):
        self.load_data('data')
        self.load_data('config')
        for api in self.all_api[1:]:
            exec('self.%s = %s(self)' % (api, api))
        self.tray = Tray(self)
        self.switch_frame = SwitchFrame(self)
        self.switch_frame.change_interval()
        self.right_frame = Right(self)
        self.set = Set(self)
        self.set.api_choose.addItems(self.all_api)
        self.set.api_choose.setCurrentText(self.config['api'])
        if self.config['api'] != '随机':
            self.api = eval('self.%s' % self.config['api'])
            self.set.category_choose.addItems(self.api.cate)
            self.set.category_choose.setCurrentText(self.config['category'])
            if self.config['play_like'] != 0:
                self.set.api_choose.setEnabled(False)
                self.set.category_choose.setEnabled(False)
        else:
            self.set.category_choose.addItem('随机')
            self.set.category_choose.setCurrentText('随机')
        # 检查权限
        if not try_author():
            self.set.auto_start.setEnabled(False)

        self.choose_random = ChooseRandom(self.set, self)
        # qss
        with open('style.qss', 'r') as fp:
            self.setStyleSheet(fp.read())

        self.initializing = False
        if self.config['show_windmill'] == 0:
            self.hide()
        else:
            self.show()
Exemplo n.º 10
0
class Gui(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        
        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()
        
        self.restore_wnd_geometry()

        self.downloads = Downloads(self)
        self.add_downloads = AddDownloads(self)
        self.log = Log(self)
        
        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM), _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM), _('Start Download'), self.on_start_download, False)
        self.accounts = (QToolButton(), media.get_icon(media.ACCOUNTS, media.MEDIUM), _('Accounts'), self.on_accounts, True)
        self.preferences = (QToolButton(), media.get_icon(media.PREFERENCES, media.MEDIUM), _('Preferences'), self.on_preferences, True)
        self.about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM), _('About'), self.on_about, True)
        
        self.menu = QMenu()
        self.preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        self.preferences[BTN].setMenu(self.menu)
        
        self.toolbar = Toolbar(self, [self.start, self.stop, None, self.accounts, self.preferences, None, self.about])

        self.addToolBar(self.toolbar)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget()
        #
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        self.show_or_hide_tray()

        #load session.
        self.load_session()

        #add core's event loop
        self.dispatcher = ThreadDispatcher(self)
        self.dispatcher.start()

        #quit event
        events.quit.connect(self.event_close)

        #custom qt signals
        signals.switch_tab.connect(self.switch_tab)
        signals.show_or_hide_tray.connect(self.show_or_hide_tray)

        self.show()

    def customEvent(self, event):
        #process idle_queue_dispacher events
        event.callback()

    def switch_tab(self, index):
        self.tab.setCurrentIndex(index)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    
    def restore_wnd_geometry(self):
        wx, wy, ww, wh = QDesktopWidget().availableGeometry().getRect()
        x, y, w, h = conf.get_window_settings()
        if ww <= w or wh <= h:
            self.showMaximized()
        elif ww > x >= 0 and wh > y >= 0: #resize and move
            self.setGeometry(x, y, w, h)
        else: #resize only
            self.resize(w, h)

    def on_stop_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                stopped = api.stop_download(id_item)
                if stopped:
                    if items[row][1] == self.downloads.icons_dict[cons.STATUS_QUEUE]:
                        items[row][1] = self.downloads.icons_dict[cons.STATUS_STOPPED]
                    self.stop[BTN].setEnabled(False)
                    self.start[BTN].setEnabled(True)

    def on_start_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                started = api.start_download(id_item)
                if started:
                    items[row][1] = self.downloads.icons_dict[cons.STATUS_QUEUE] #status
                    items[row][10] = None #status_msg
                    self.stop[BTN].setEnabled(True)
                    self.start[BTN].setEnabled(False)
            id_item_list = [row[0] for row in items]
            api.reorder_queue(id_item_list)
    
    def on_accounts(self):
        accounts = ConfigAccounts(self)
    
    def on_preferences(self):
        index_page = self.tab.indexOf(self.preferences) #get the page containig the widget
        if index_page >= 0: #if = -1 there is not such tab.
            self.tab.setCurrentIndex(index_page)
        else:
            index_page = self.tab.addTab(self.preferences, _('Preferences'))
            btn_close = QPushButton(self)
            #btn_close.setIcon(QIcon('stop.png'))
            #btn_close.setIconSize(QSize(10, 10))
            btn_close.setFixedHeight(12)
            btn_close.setFixedWidth(12)
            #btn_close.setFlat(True)
            btn_close.clicked.connect(self.on_close_preferences)
            self.tab.tabBar().setTabButton(index_page, QTabBar.RightSide, btn_close)
            #
            last_index = self.tab.count() - 1
            self.tab.setCurrentIndex(last_index)
    
    def on_close_preferences(self):
        index_page = self.tab.indexOf(self.preferences)
        if index_page >= 0:
            self.tab.removeTab(index_page)
        #self.tab.setCurrentIndex(0)
    
    def on_about(self):
        about = About(self)
    
    def on_tab_switch(self, index):
        current_widget = self.tab.currentWidget()
        if current_widget == self.tab_log:
            self.log.on_load()
        elif current_widget in self.addon_tab_widgets:
            tab = current_widget.layout()
            tab.on_load()

        if self.previous_tab == self.preferences:
            self.previous_tab.on_close()
        elif self.previous_tab in self.addon_tab_widgets:
            tab = self.previous_tab.layout()
            tab.on_close()
        self.previous_tab = current_widget

    def show_or_hide_tray(self):
        if self.tray.is_available() and conf.get_tray_available():
            self.tray.show()
        else:
            self.tray.hide()

    def load_addon_tabs(self):
        for tab, addon in [(addon.get_tab(), addon) for addon in self.addons_list]:
            if tab is not None:
                tab_widget = QWidget()
                tab_widget.setLayout(tab)
                self.tab.addTab(tab_widget, addon.name)
                self.addon_tab_widgets.append(tab_widget)

    def load_session(self):
        """"""
        download_items = api.load_session()
        for download_item in download_items:
            self.downloads.store_item(download_item)
    
    def save_session(self):
        """"""
        id_item_list = [row[0] for row in self.downloads.items]
        api.save_session(id_item_list)
    
    def idle_timeout(self, interval, func):
        timer = QTimer()
        timer.timeout.connect(func)
        timer.start(interval)
        return timer

    def event_close(self):
        self.tray.hide()
        self.close()

    def closeEvent(self, event):
        # overridden
        if not self.tray.isVisible():
            x, y, w, h = self.geometry().getRect()
            self.hide()
            self.save_session()
            self.preferences.on_close()
            self.dispatcher.stop()
            conf.set_window_settings(x, y, w, h)
            conf.save()
            accounts_manager.save()
            event.accept()
        else:  # hide only
            self.hide()
            event.ignore()
Exemplo n.º 11
0
class MainWindow(KXmlGuiWindow, Ui_MainWindow):
    def __init__(self, app=None):
        KXmlGuiWindow.__init__(self, None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(KIcon(":/data/package-manager.png"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)

    def connectMainSignals(self):
        self.cw.connectMainSignals()
        self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab), self),
                     SIGNAL("activated()"), lambda: self.moveTab('next'))
        self.connect(
            QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Tab), self),
            SIGNAL("activated()"), lambda: self.moveTab('prev'))
        self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F), self),
                     SIGNAL("activated()"), self.cw.searchLine.setFocus)
        self.connect(QShortcut(QKeySequence(Qt.Key_F3), self),
                     SIGNAL("activated()"), self.cw.searchLine.setFocus)

        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"),
                     self.cw.initialize)
        self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"),
                     self.cw.updateSettings)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"),
                     self.tray.settingsChanged)
        self.connect(self.cw.state, SIGNAL("repositoriesChanged()"),
                     self.tray.populateRepositoryMenu)
        self.connect(self.cw, SIGNAL("repositoriesUpdated()"),
                     self.tray.updateTrayUnread)
        self.connect(KApplication.kApplication(), SIGNAL("shutDown()"),
                     self.slotQuit)

    def moveTab(self, direction):
        new_index = self.cw.stateTab.currentIndex() - 1
        if direction == 'next':
            new_index = self.cw.stateTab.currentIndex() + 1
        if new_index not in range(self.cw.stateTab.count()):
            new_index = 0
        self.cw.stateTab.setCurrentIndex(new_index)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"),
                     self.trayAction)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"),
                     self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("operationCancelled()"),
                     self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("started(QString)"),
                     self.tray.animate)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"),
                     self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)

        self.cw.switchState(StateManager.UPGRADE)

        KApplication.kApplication().updateUserTimestamp()

        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in [
                "System.Manager.updateRepository",
                "System.Manager.updateAllRepositories"
        ]:
            self.tray.showPopup()
        if self.tray.isActive() and operation in [
                "System.Manager.updatePackage",
                "System.Manager.installPackage", "System.Manager.removePackage"
        ]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.cw.mainLayout.insertWidget(0, self.busy)
        self.statusBar().addPermanentWidget(self.cw.actions, 1)
        self.statusBar().show()

        self.updateStatusBar('')

        self.connect(self.cw, SIGNAL("selectionStatusChanged(QString)"),
                     self.updateStatusBar)
        self.connect(self.cw, SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.toolBar().setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        KStandardAction.quit(KApplication.kApplication().quit,
                             self.actionCollection())
        KStandardAction.preferences(self.settingsDialog.show,
                                    self.actionCollection())
        self.setupGUI(
            KXmlGuiWindow.Default,
            "/usr/share/kde4/apps/package-manager/data/packagemanagerui.rc")
        self.initializeOperationActions()

    def initializeOperationActions(self):
        actionGroup = QtGui.QActionGroup(self)

        self.showAllAction = KToggleAction(KIcon("applications-other"),
                                           i18n("All Packages"), self)
        self.actionCollection().addAction("showAllAction", self.showAllAction)
        self.connect(self.showAllAction, SIGNAL("triggered()"),
                     lambda: self.cw.switchState(StateManager.ALL))
        self.cw.stateTab.addTab(QWidget(), KIcon("applications-other"),
                                i18n("All Packages"))
        actionGroup.addAction(self.showAllAction)

        self.showInstallAction = KToggleAction(KIcon("list-add"),
                                               i18n("Installable Packages"),
                                               self)
        self.actionCollection().addAction("showInstallAction",
                                          self.showInstallAction)
        self.connect(self.showInstallAction, SIGNAL("triggered()"),
                     lambda: self.cw.switchState(StateManager.INSTALL))
        self.cw.stateTab.addTab(QWidget(), KIcon("list-add"),
                                i18n("Installable Packages"))
        actionGroup.addAction(self.showInstallAction)

        self.showRemoveAction = KToggleAction(KIcon("list-remove"),
                                              i18n("Installed Packages"), self)
        self.actionCollection().addAction("showRemoveAction",
                                          self.showRemoveAction)
        self.connect(self.showRemoveAction, SIGNAL("triggered()"),
                     lambda: self.cw.switchState(StateManager.REMOVE))
        self.cw.stateTab.addTab(QWidget(), KIcon("list-remove"),
                                i18n("Installed Packages"))
        actionGroup.addAction(self.showRemoveAction)

        self.showUpgradeAction = KToggleAction(KIcon("system-software-update"),
                                               i18n("Updates"), self)
        self.actionCollection().addAction("showUpgradeAction",
                                          self.showUpgradeAction)
        self.connect(self.showUpgradeAction, SIGNAL("triggered()"),
                     lambda: self.cw.switchState(StateManager.UPGRADE))
        self.cw.stateTab.addTab(QWidget(), KIcon("system-software-update"),
                                i18n("Updates"))
        actionGroup.addAction(self.showUpgradeAction)

        # self.showHistoryAction = KToggleAction(KIcon("view-refresh"), i18n("History"), self)
        # self.actionCollection().addAction("showHistoryAction", self.showHistoryAction)
        # self.connect(self.showHistoryAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.HISTORY))
        # self.cw.stateTab.addTab(QWidget(), KIcon("view-refresh"), i18n("History"))
        # actionGroup.addAction(self.showHistoryAction)

        self.cw.menuButton.setMenu(QMenu('MainMenu', self.cw.menuButton))
        self.cw.menuButton.setIcon(KIcon('preferences-other'))
        self.cw.menuButton.menu().clear()

        self.cw.contentHistory.hide()

        # self.cw.menuButton.menu().addAction(self.showAllAction)
        # self.cw.menuButton.menu().addAction(self.showInstallAction)
        # self.cw.menuButton.menu().addAction(self.showRemoveAction)
        # self.cw.menuButton.menu().addAction(self.showUpgradeAction)
        # self.cw.menuButton.menu().addSeparator()

        self.cw.menuButton.menu().addAction(self.actionCollection().action(
            KStandardAction.name(KStandardAction.Preferences)))
        self.cw.menuButton.menu().addAction(self.actionCollection().action(
            KStandardAction.name(KStandardAction.Help)))
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionCollection().action(
            KStandardAction.name(KStandardAction.AboutApp)))
        self.cw.menuButton.menu().addAction(self.actionCollection().action(
            KStandardAction.name(KStandardAction.AboutKDE)))
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionCollection().action(
            KStandardAction.name(KStandardAction.Quit)))

        self.cw._states = {
            self.cw.state.ALL: (0, self.showAllAction),
            self.cw.state.INSTALL: (1, self.showInstallAction),
            self.cw.state.REMOVE: (2, self.showRemoveAction),
            self.cw.state.UPGRADE: (3, self.showUpgradeAction)
        }
        #                  self.cw.state.HISTORY:(4, self.showHistoryAction)}

        self.showAllAction.setChecked(True)
        self.cw.checkUpdatesButton.hide()
        self.cw.checkUpdatesButton.setIcon(KIcon('view-refresh'))
        self.cw.showBasketButton.clicked.connect(self.cw.showBasket)

        # Little time left for the new ui
        self.menuBar().setVisible(False)
        self.cw.switchState(self.cw.state.ALL)

    def statusWaiting(self):
        self.updateStatusBar(i18n('Calculating dependencies...'), busy=True)

    def updateStatusBar(self, text, busy=False):
        if text == '':
            text = i18n("Currently your basket is empty.")
            self.busy.hide()
            self.cw.showBasketButton.hide()
        else:
            self.cw.showBasketButton.show()

        if busy:
            self.busy.busy()
            self.cw.showBasketButton.hide()
        else:
            self.busy.hide()

        self.cw.statusLabel.setText(text)

    def queryClose(self):
        if config.PMConfig().systemTray(
        ) and not KApplication.kApplication().sessionSaving():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray:
                del self.tray.notification
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
Exemplo n.º 12
0
class TunnelDialog(WindowBaseClass, Ui_TunnelDialog):
    def __init__(self):
        WindowBaseClass.__init__(self)
        self.setupUi(self)
        self._explicitQuit = False

        # Tunnels
        self._tunnels = []

        # Setup tray
        self.tray = Tray(self, "IOSSHy", QIcon(":/icons/network-server.png"))
        self.tray.activated.connect(self.activated)

        action = QAction("&Configure", self.tray.menu)
        action.setIcon(QIcon(":/icons/configure.png"))
        action.triggered.connect(self.show)
        self.tray.menu.addAction(action)
        self.tray.menu.setDefaultAction(action)

        self.tray.menu.addSeparator()
        self.actionNoTun = QAction("No tunnels configured", self.tray.menu)
        self.actionNoTun.setEnabled(False)
        self.tray.menu.addAction(self.actionNoTun)
        self.actionLastSep = self.tray.menu.addSeparator()

        if kde:
            action = QAction("&About", self.tray.menu)
            action.triggered.connect(self.about)
            self.tray.menu.addAction(action)

        action = QAction("&Quit", self.tray.menu)
        action.setIcon(QIcon(":/icons/application-exit.png"))
        action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q))
        action.triggered.connect(self.quit)
        self.tray.menu.addAction(action)

        # Load settings
        self.readSettings()
        self.hide()

    def show(self):
        self.visible = True
        WindowBaseClass.show(self)
        desktop = QDesktopWidget()
        rect = desktop.availableGeometry(desktop.primaryScreen()) 
        center = rect.center();
        center.setX(center.x() - (self.width()/2));
        center.setY(center.y() - (self.height()/2));
        self.move(center);

    def hide(self):
        self.visible = False
        self.writeSettings()
        WindowBaseClass.hide(self)

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

    def on_listTunnels_currentItemChanged(self, current, previous):
        self.grpTunnelProperties.setEnabled(current is not None)
        self.grpSshProperties.setEnabled(current is not None)
        if current is not None:
            tunnel = self._tunnels[self.listTunnels.row(current)]

            self.txtName.setText( tunnel.name )
            self.txtHost.setText( "localhost" if tunnel.host == "" else tunnel.host )
            self.txtLocalPort.setText( "0" if tunnel.localPort is None else str(tunnel.localPort) )
            self.txtPort.setText( str(tunnel.port) )
            self.txtSshPort.setText( str(tunnel.sshPort) )
            self.txtUsername.setText( "root" if tunnel.username == "" else tunnel.username )
            self.txtCommand.setText( "" if tunnel.command is None else tunnel.command )
            self.chkCloseOnTerm.setChecked( Qt.Checked if tunnel.autoClose else Qt.Unchecked )

            self.txtName.setFocus()
            self.txtName.selectAll()
        else:
            self.txtName.setText("")
            self.txtHost.setText("localhost")
            self.txtLocalPort.setText("0")
            self.txtPort.setText("")
            self.txtSshPort.setText("22")
            self.txtUsername.setText("root")
            self.txtCommand.setText("")
            self.chkCloseOnTerm.setChecked(Qt.Unchecked)

    def currentTunnel(self):
        try:
            ti = self.listTunnels.currentRow()
            return None if ti < 0 else self._tunnels[ti]
        except IndexError:
            return None

    def on_txtName_textEdited(self, text):
        self.currentTunnel().name = text

    def on_txtHost_textEdited(self, text):
        self.currentTunnel().host = text

    def on_txtLocalPort_textEdited(self, text):
        self.currentTunnel().localPort = text

    def on_txtPort_textEdited(self, text):
        self.currentTunnel().port = text

    def on_txtSshPort_textEdited(self, text):
        self.currentTunnel().sshPort = text

    def on_txtUsername_textEdited(self, text):
        self.currentTunnel().username = text

    def on_txtCommand_textEdited(self, text):
        self.currentTunnel().command = text

    def on_chkCloseOnTerm_stateChanged(self, state):
        if self.currentTunnel() is not None:
            self.currentTunnel().autoClose = state == Qt.Checked

    @pyqtSignature("")
    def on_btnAddTunnel_clicked(self):
        tunnel = Tunnel(self)
        self._tunnels.append(tunnel)
        self.listTunnels.setCurrentItem(tunnel.item)
        self.tray.menu.insertAction(self.actionLastSep, tunnel.action)
        self.tray.menu.removeAction(self.actionNoTun)

    @pyqtSignature("")
    def on_btnDuplicateTunnel_clicked(self):
        cur = self.currentTunnel()
        if cur is not None:
            tunnel = Tunnel(self)
            tunnel.name = cur.name+" (copy)"
            tunnel.host = cur.host
            tunnel.localPort = cur.localPort
            tunnel.port = cur.port
            tunnel.username = cur.username
            tunnel.command = cur.command
            tunnel.autoClose = cur.autoClose
            self._tunnels.append(tunnel)
            self.listTunnels.setCurrentItem(tunnel.item)
            self.tray.menu.insertAction(self.actionLastSep, tunnel.action)

    @pyqtSignature("")
    def on_btnRemoveTunnel_clicked(self):
        tunnel = self.currentTunnel()
        if tunnel is not None:
            ti = self.listTunnels.currentRow()
            del self._tunnels[ti]
            self.listTunnels.setCurrentRow(0 if ti != 0 else 1)
            self.listTunnels.takeItem(ti)
            self.listTunnels.setCurrentItem(None, QItemSelectionModel.Clear)
            self.tray.menu.removeAction(tunnel.action)
            del tunnel

            if len(self._tunnels) == 0:
                self.tray.menu.insertAction(self.actionLastSep, self.actionNoTun)

    def updateTooltip(self):
        tuninfo = []
        for tunnel in self._tunnels:
            if tunnel.isOpen():
                tuninfo.append( "<div>{name}: {host}:{port} => {local}</div>".format(name=tunnel.name, host=tunnel.host, port=tunnel.port, local=tunnel.tunnelPort) )
        if tuninfo:
            tuninfo.insert(0, "<b>Active tunnels:</b>")
            self.tray.setActive()
        else:
            self.tray.setActive(False)
        self.tray.setToolTipSubTitle( "\n".join(tuninfo) )

    def activated(self):
        if self.visible:
            self.hide()
        else:
            self.show()

    def readSettings(self):
        if os.name == 'nt':
            settings = QSettings()
        else:
            settings = QSettings(os.path.expanduser("~/.iosshy.ini"), QSettings.IniFormat)
        for name in settings.childGroups():
            tunnel = Tunnel(self)
            tunnel.name = name
            tunnel.readSettings(settings)
            self._tunnels.append(tunnel)
            self.tray.menu.insertAction(self.actionLastSep, tunnel.action)
            self.tray.menu.removeAction(self.actionNoTun)

    def writeSettings(self):
        if os.name == 'nt':
            settings = QSettings()
        else:
            settings = QSettings(os.path.expanduser("~/.iosshy.ini"), QSettings.IniFormat)
        settings.clear()
        for tunnel in self._tunnels:
            tunnel.writeSettings(settings)

    def about(self):
        KAboutApplicationDialog(application.aboutData, self).exec_()
        if self.isHidden():
            self.show()
            self.hide()

    def quit(self):
        self.writeSettings()
        self._explicitQuit = True
        self.close()
Exemplo n.º 13
0
 def initializeTray(self):
     self.tray = Tray(self)
     self.connect(self.centralWidget().operation, SIGNAL("finished(QString)"), self.trayShow)
     self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)
Exemplo n.º 14
0
 def initializeTray(self):
     self.tray = Tray(self)
Exemplo n.º 15
0
class MainView:
    def __init__(self, master):
        self.master = master
        self.ID = "main"
        #============ Menu ======================

        self.menubar = Menu(master)
        self.filemenu = Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="Save")
        self.filemenu.add_command(label="Open")
        self.filemenu.add_command(label="New")
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Audio Settings",
                                  command=self.openConfigSettings)
        self.menubar.add_cascade(label="File", menu=self.filemenu)

        self.master.config(menu=self.menubar)

        # True/False is Editable or Not.
        self.mainSettingsList = [["consFolder", False], ["vowelFolder", False],
                                 ["outFolder", False], ["fred", True],
                                 ["initial frequency", True],
                                 ["xFade Length", True], ["Vowel Pad", True],
                                 ["Splice Point", True],
                                 ["Tuning Bounds", True], ["Pad First", True],
                                 ["Pad Last", True], ["Crossfade First", True],
                                 ["Crossfade Last", True]]

        self.indivSettingsList = [["consFile", True], ["vowelFile", True],
                                  ["initial frequency", True],
                                  ["xFade Length", True], ["InitPad", True],
                                  ["EndPad", True], ["Vowel Pad", True],
                                  ["Splice Point", True],
                                  ["Tuning Bounds", True], ["outFile", True]]
        self.readSettings()
        #============ vars ==================

        #self.toneFolderPath = StringVar()
        #self.attackFolderPath = StringVar()

        #============ frames ================

        self.mainFrame = ttk.Frame(self.master)
        self.mainFrame.grid()

        self.leftWrapper = ttk.Frame(self.mainFrame)
        self.leftWrapper.grid(row=0, column=0, sticky=N)

        self.inFrame = ttk.LabelFrame(self.leftWrapper, text="File Setup")
        self.inFrame.grid(row=0, column=0, sticky=N)

        self.settingsFrame = ttk.LabelFrame(self.mainFrame,
                                            text="Main Settings")
        self.settingsFrame.grid(row=0, column=1)

        self.trayFrame = ttk.LabelFrame(self.leftWrapper, text="Tray")
        self.trayFrame.grid(row=2, column=0, sticky=N + W)

        self.goFrame = ttk.Frame(self.leftWrapper)
        self.goFrame.grid(row=1, column=0, sticky=E + W)

        self.graphicsFrame = ttk.LabelFrame(self.mainFrame, text="Editing")
        self.graphicsFrame.grid(row=0, column=2, sticky=N)

        #============ inFrame ==========================

        self.chooseAttackButton = ttk.Button(
            self.inFrame,
            text="Choose Attack Folder",
            command=lambda: self.chooseFolder("consFolder"))
        self.chooseAttackButton.grid(row=0, column=0)

        self.chooseToneButton = ttk.Button(
            self.inFrame,
            text="Choose Tone Folder",
            command=lambda: self.chooseFolder("vowelFolder"))
        self.chooseToneButton.grid(row=0, column=1)

        self.chooseFred = ttk.Button(self.inFrame,
                                     text="Choose fred",
                                     command=lambda: self.chooseFolder("fred"))
        self.chooseFred.grid(row=0, column=2)

        self.chooseDestinationButton = ttk.Button(
            self.inFrame,
            text="Choose Destination Folder",
            command=lambda: self.chooseFolder("outFolder"))
        self.chooseDestinationButton.grid(row=1,
                                          column=0,
                                          columnspan=2,
                                          sticky=W)

        #============ goFrame =============================

        self.goButton = ttk.Button(self.goFrame,
                                   text="Process Batch",
                                   command=self.spliceByBatch)
        self.goButton.grid(row=0, column=0)

        self.statusLabel = ttk.Label(self.goFrame, text="IDLE")
        self.statusLabel.grid(row=0, column=1)

        #============ settingsFrame =======================

        self.mainSettings = MainSettings(self.settingsFrame,
                                         settings=self.mainSettingsList)
        self.mainSettings.grid(row=0, column=0, sticky=E)

        print "  "
        print "============ SETTINGS IMPORTED FROM json ============="
        self.mainSettings.setValues(self.settings)
        print "============ END OF json IMPORT ============="

        self.applySettingsButton = ttk.Button(self.settingsFrame,
                                              text="Apply",
                                              command=self.applyMainSettings)
        self.applySettingsButton.grid(row=1)

        #============ trayFrame ============================

        self.tray = Tray(
            self.trayFrame,
            settings=self.indivSettingsList)  #,initialSettings=self.settings)
        self.tray.grid()
        #for i in range(11):
        #	self.tray.addItem(json.loads(open('settings.json').read()))

        # self.placeHolder = ttk.Button(self.trayFrame, text="Placeholder",
        # 							  command=self.placeholderButton)
        # self.placeHolder.grid()

        #============ graphicsFrame ============================
        self.graphs = {}

        self.padGraph = Graphic(self.graphicsFrame, self.numFiles, 100,
                                "Padding")
        self.padGraph.grid(row=0, column=0)
        self.graphs["pads"] = self.padGraph

        self.padGraph = Graphic(self.graphicsFrame,
                                self.numFiles,
                                100,
                                "Cross Fade Length",
                                maxRange=800)
        self.padGraph.grid(row=0, column=1)
        self.graphs["cfls"] = self.padGraph

    def graphGet(self, category):
        self.setupOut[category] = self.graphs[category].get()
        print category, self.setupOut[category]
        #print self.setupOut

    def readSettings(self):
        if not os.path.exists('settings.json'):
            with open('default_settings.json') as r:
                with open('settings.json', 'w') as w:
                    w.write(r.read())
        self.settings = json.loads(open('settings.json').read())
        self.setupOut = setup(self.settings)
        self.numFiles = len(self.setupOut["outFiles"])

    #def readIndivSettings(self):
    #	pass

    def chooseFolder(self, var):
        f = tkFileDialog.askdirectory(initialdir=".")
        #print(os.getcwd())
        #print(f)
        the_dir = f.split(os.getcwd())[-1][1:]
        self.settings[var] = the_dir
        self.mainSettings.setValues(self.settings)
        #print var.get()

    def loadProject(self):
        directory = tkFileDialog.askdirectory()
        if checkFileSystem(directory):
            os.chdir(directory)
            self.readSettings()

    def applyMainSettings(self):
        self.settings = self.mainSettings.get()
        print "================ APPLY MAIN SETTINGS ====================="
        print self.settings

        with open('settings.json', 'w') as w:
            w.write(json.dumps(self.settings))

        self.readSettings()

    def spliceByBatch(self):
        #names = batch(self.settings)
        #setupOut = setup(self.settings)
        #for n in names:
        #self.tray.clear()
        #self.tray.update_idletasks()
        print "  "
        print "===================================================================="
        print "========================= BEGIN spiceByBatch ======================="
        print "===================================================================="
        self.statusLabel.config(text="WORKING")
        self.master.update_idletasks()
        self.applyMainSettings()
        print "============ graphicKnobs ============="
        for g in self.graphs:
            self.graphGet(g)
        print "============ Frequencies ============="
        print "setupOut[freqs] = ", self.setupOut["freqs"]
        print "Length ::: len(self.setupOut[freqs]) = ", len(
            self.setupOut["freqs"])
        print "  "
        print "============================================"
        print "============= NOW BEGIN LOOP ==============="
        for i in range(len(self.setupOut["freqs"])):
            splice(i, self.setupOut, self.settings)
            print "  "
            print "NOW WE'RE IN self.tray.addItem TERRITORY"
            self.tray.addItem(
                json.loads(open('settings.json').read()),
                buttonText=self.setupOut["outFiles"][i].split("/")[-1],
                consFile=self.setupOut["consFiles"][i])
            self.tray.update_idletasks()
            print "  "
            print "  "
        print "======================================================================="
        print "============================ PROCESS DONE ============================="
        print "======================================================================="
        print "  "
        print "  "
        print "  "
        self.statusLabel.config(text="IDLE")

    def placeholderButton(self):
        t = Toplevel(self.master)
        i = IndividualSettings(t)
        i.grid()

    def openConfigSettings(self):
        t = Toplevel(self.master)
        s = ConfigSettings(t)
        s.grid()
Exemplo n.º 16
0
class MainWindow(KXmlGuiWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        KXmlGuiWindow.__init__(self, parent)
        self.setupUi(self)
        self.setWindowIcon(KIcon(":/data/package-manager.png"))
        self.setCentralWidget(MainWidget(self))
        self.settingsDialog = SettingsDialog(self)
        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()
        
        self.offlinemanager = OfflineManager()
        self.connectOfflineSignals()

    def connectMainSignals(self):
        self.connect(self, SIGNAL("packagesChanged()"), self.centralWidget().initialize)
        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.centralWidget().initialize)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged)
        self.connect(self.centralWidget().state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu)
        self.connect(KApplication.kApplication(), SIGNAL("shutDown()"), self.slotQuit)

    def connectOfflineSignals(self):
        self.connect(self, SIGNAL("importIndex(str)"), self.offlinemanager.importIndex)
        self.connect(self, SIGNAL("exportIndex(str)"), self.offlinemanager.exportIndex)
        self.connect(self, SIGNAL("openSession(str)"), self.offlinemanager.openSession)
        self.connect(self, SIGNAL("saveSession(str)"), self.offlinemanager.saveSession)

    def initializeTray(self):
        self.tray = Tray(self)
        self.connect(self.centralWidget().operation, SIGNAL("finished(QString)"), self.trayShow)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)
        self.centralWidget().switchState(StateManager.UPGRADE, action=False)
        self.centralWidget().initialize()
        KApplication.kApplication().updateUserTimestamp()
        self.show()
        self.raise_()

    def trayShow(self, operation):
        if not self.isVisible() and operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            self.tray.showPopup()

    def initializeStatusBar(self):
        self.statusLabel = QtGui.QLabel(i18n("Currently your basket is empty."), self.statusBar())
        self.statusLabel.setAlignment(Qt.AlignCenter)
        self.statusBar().addWidget(self.statusLabel)
        self.statusBar().setSizeGripEnabled(True)
        self.wheelMovie = QtGui.QMovie(self)
        self.statusLabel.setText(i18n("Currently your basket is empty."))
        self.wheelMovie.setFileName(":/data/wheel.mng")
        self.connect(self.centralWidget(), SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar)
        self.connect(self.centralWidget(), SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.toolBar().setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        KStandardAction.quit(KApplication.kApplication().quit, self.actionCollection())
        KStandardAction.preferences(self.settingsDialog.show, self.actionCollection())

        self.initializeOperationActions()
        self.setupGUI(KXmlGuiWindow.Default, "data/packagemanagerui.rc")

    def initializeOperationActions(self):
        actionGroup = QtGui.QActionGroup(self)

        self.showInstallAction = KToggleAction(KIcon("list-add"), i18n("Show Installable Packages"), self)
        self.showInstallAction.setChecked(True)
        self.actionCollection().addAction("showInstallAction", self.showInstallAction)
        self.connect(self.showInstallAction, SIGNAL("triggered()"), lambda:self.centralWidget().switchState(StateManager.INSTALL))
        self.connect(self.showInstallAction, SIGNAL("triggered()"), self.centralWidget().initialize)
        actionGroup.addAction(self.showInstallAction)

        self.showRemoveAction = KToggleAction(KIcon("list-remove"), i18n("Show Installed Packages"), self)
        self.actionCollection().addAction("showRemoveAction", self.showRemoveAction)
        self.connect(self.showRemoveAction, SIGNAL("triggered()"), lambda:self.centralWidget().switchState(StateManager.REMOVE))
        self.connect(self.showRemoveAction, SIGNAL("triggered()"), self.centralWidget().initialize)
        actionGroup.addAction(self.showRemoveAction)

        self.showUpgradeAction = KToggleAction(KIcon("view-refresh"), i18n("Show Upgradable Packages"), self)
        self.actionCollection().addAction("showUpgradeAction", self.showUpgradeAction)
        self.connect(self.showUpgradeAction, SIGNAL("triggered()"), lambda:self.centralWidget().switchState(StateManager.UPGRADE))
        actionGroup.addAction(self.showUpgradeAction)

        self.importIndexAction = KToggleAction(KIcon("list-add"), i18n("Import Index"), self)
        self.actionCollection().addAction("importIndexAction", self.importIndexAction)
        self.connect(self.importIndexAction, SIGNAL("triggered()"), self.importIndex)

        self.exportIndexAction = KToggleAction(KIcon("list-remove"), i18n("Export Index"), self)
        self.actionCollection().addAction("exportIndexAction", self.exportIndexAction)
        self.connect(self.exportIndexAction, SIGNAL("triggered()"), self.exportIndex)

        self.openSessionAction = KToggleAction(KIcon("list-add"), i18n("Open Session"), self)
        self.actionCollection().addAction("openSessionAction", self.openSessionAction)
        self.connect(self.openSessionAction, SIGNAL("triggered()"), self.openSession)

        self.saveSessionAction = KToggleAction(KIcon("list-remove"), i18n("Save Session"), self)
        self.actionCollection().addAction("saveSessionAction", self.saveSessionAction)
        self.connect(self.saveSessionAction, SIGNAL("triggered()"), self.saveSession)

    def statusWaiting(self):
        self.statusLabel.setMovie(self.wheelMovie)
        self.wheelMovie.start()

    def updateStatusBar(self, text):
        self.wheelMovie.stop()
        self.statusLabel.setText(text)

    def queryClose(self):
        if config.PMConfig().systemTray() and not KApplication.kApplication().sessionSaving():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not backend.pm.Iface().operationInProgress():
            if self.tray.notification:
                self.tray.notification.close()
            return True
        return False

    def slotQuit(self):
        if backend.pm.Iface().operationInProgress():
            return

    def switchSession(self, session):
        self.centralWidget().switchSession(session)
        self.showInstallAction.setChecked(True)

    def importIndex(self):
        filename = str(KFileDialog.getOpenFileName(KUrl("pisi-installed"), "*.xml", self, i18n("Import index file")))

        if filename:
            self.switchSession(SessionManager.OFFLINE)
            self.emit(SIGNAL("importIndex(str)"), filename)
            self.emit(SIGNAL("packagesChanged()"))

    def exportIndex(self):
        filename = str(KFileDialog.getSaveFileName(KUrl("pisi-installed"), "*.xml", self, i18n("Export index file")))

        if filename:
            self.emit(SIGNAL("exportIndex(str)"), filename)

    def openSession(self):
        filename = str(KFileDialog.getOpenFileName(KUrl("pisi-archive"), "*.offline", self, i18n("Open offline session")))

        if filename:
            self.emit(SIGNAL("openSession(str)"), filename)

    def saveSession(self):
        filename = str(KFileDialog.getSaveFileName(KUrl("pisi-archive"), "*.offline", self, i18n("Save offline session")))

        if filename:
            self.emit(SIGNAL("saveSession(str)"), filename)
            self.switchSession(SessionManager.NORMAL)
Exemplo n.º 17
0
def start():
    #First, we get the basic information:
    info = config.getBasicInfo()
    MODE = info[0]
    lastTrigger = config.getLastTrigger()

    # Goal : Get basic config, load config, load tray and determine the TIMER
    if MODE == 0:
        EXERCISES_MODE, EXERCISES_SELECTED, NUMBER_TO_PICK_PER_SESSION, TIMER = info[
            1:]
        # Get List EXERCISES Config:
        ListEXERCISES = getListOfEXERCISES(EXERCISES_SELECTED)
        # Start STRAY as THREAD
        tray = Tray(MODE, TIMER, EXERCISES_MODE, EXERCISES_SELECTED)

    elif MODE == 1:
        EXERCISES_MODE, EXERCISES_SELECTED, NUMBER_TO_PICK_PER_SESSION, HOURS, MAXIMUM_NUMBER_OF_SESSIONS_PER_INTERVAL, RECUPERATION_TIME_SECONDS = info[
            1:]
        # Get List EXERCISES Config:
        ListEXERCISES = getListOfEXERCISES(EXERCISES_SELECTED)
        # Start STRAY as THREAD
        tray = Tray(MODE, [
            HOURS, MAXIMUM_NUMBER_OF_SESSIONS_PER_INTERVAL,
            RECUPERATION_TIME_SECONDS
        ], EXERCISES_MODE, EXERCISES_SELECTED)

        # Get current time and hour : determine TIMER

        HOURS.sort()
        expandedIntervals = [[j for j in range(*HOURS[i:i + 2])]
                             for i in range(0, len(HOURS), 2)]
        currentDT = datetime.datetime.now()
        n = 0
        if lastTrigger == None:
            lastTrigger = [0, -1]
            notify(
                "Workout Starter Pack",
                "Error: Couldn't get the last trigger from config. Switching to [0, -1] by default.",
                5)

        for i in range(len(expandedIntervals)):
            expandedInterval = expandedIntervals[i]
            if currentDT.hour in expandedInterval:

                if lastTrigger[
                        0] < MAXIMUM_NUMBER_OF_SESSIONS_PER_INTERVAL and lastTrigger[
                            1] == i:
                    TIMER = RECUPERATION_TIME_SECONDS
                    lastTrigger = [lastTrigger[0] + 1, i]

                elif lastTrigger[1] != i:
                    lastTrigger = [1, i]
                    TIMER = 5

                else:
                    nextHour = HOURS[0]
                    nextDay = datetime.datetime(currentDT.year,
                                                currentDT.month,
                                                currentDT.day + 1).day

                    for i in HOURS[::2]:
                        if i > currentDT.hour:
                            nextHour = i
                            nextDay = currentDT.day

                    nextDateTime = datetime.datetime(currentDT.year,
                                                     currentDT.month, nextDay,
                                                     nextHour, 0)
                    TIMER = (nextDateTime - currentDT).total_seconds()
                    print(
                        "Skipping to next interval because finished this one")
                    # config.updateLastTrigger(0, -1)
            else:
                n += 1

        # Update current interval and interation in config if currentDT not in any interval
        if n == len(expandedIntervals):
            print("Not in any intverval")
            lastTrigger = [0, -1]
            nextHour = HOURS[0]
            nextDay = datetime.datetime(currentDT.year, currentDT.month,
                                        currentDT.day + 1).day

            for i in HOURS[::2]:
                if i >= currentDT.hour:
                    nextHour = i
                    nextDay = currentDT.day

            nextDateTime = datetime.datetime(currentDT.year, currentDT.month,
                                             nextDay, nextHour, 0)
            TIMER = (nextDateTime - currentDT).total_seconds()

    # Notify for the user of what was done
    if len(ListEXERCISES) == 0:
        notify(
            "Workout Starter Pack",
            "Error: no exercises loaded. Please look at the configuration file. Quitting.",
            5)
        sys.exit(0)

    # EXERCISES_MODE :
    if EXERCISES_MODE == 1:
        shuffle(ListEXERCISES)
    ListEXERCISES = ListEXERCISES[:NUMBER_TO_PICK_PER_SESSION]

    # Notify of the next session's content
    names = [i[0] for i in ListEXERCISES]
    notify(
        "Workout Starter Pack",
        str(len(ListEXERCISES)) + " exercise(s) loaded!\nWaiting " +
        str(int(TIMER)) + " seconds. \nNext Session : " + " ".join(names), 5)

    # Starting the tray
    tray.init_icon_tray()

    # Sleep TIMER seconds
    time.sleep(TIMER)

    # Redirect the keys and mouse events
    print("Redirecting keys events...")
    inputs = config.getInputsConfig()
    keyboard = Thread(target=lambda: init_keyboard(*inputs))
    keyboard.start()

    # Run the server
    PORT = config.getServerConfig()
    if (has_internet()):
        notify("Workout Starter Pack",
               ((EXERCISES_MODE == 0) and "Ordered" or "Randomized") +
               " sequence :\n  - " + "\n  - ".join(names), 5)
        run(lastTrigger, ListEXERCISES, PORT, tray)
    else:
        notify(
            "Workout Starter Pack",
            "No internet connection (needed for the webserver)! Stopping...",
            5,
            threaded=False)
Exemplo n.º 18
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, app = None):
        #QMainWindow.__init__(self, None)
        super(MainWindow, self).__init__(None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(QIcon("/usr/share/package-manager/data/tray-zero.svg"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)
        

    def connectMainSignals(self):
        self.cw.connectMainSignals()
        
        move_shortcut=QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab),self)
        move_shortcut.activated.connect(lambda: self.moveTab('next'))
        QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Tab),self).activated.connect(lambda: self.moveTab('prev'))
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F),self).activated.connect(self.cw.searchLine.setFocus)
        QShortcut(QKeySequence(Qt.Key_F3),self).activated.connect(self.cw.searchLine.setFocus)

        self.settingsDialog.generalSettings.packagesChanged.connect(self.cw.initialize)
        self.settingsDialog.generalSettings.packageViewChanged.connect(self.cw.updateSettings)
        self.settingsDialog.generalSettings.traySettingChanged.connect(self.tray.settingsChanged)
        self.cw.state.repositoriesChanged.connect(self.tray.populateRepositoryMenu)
        self.cw.repositoriesUpdated.connect(self.tray.updateTrayUnread)
        

    def moveTab(self, direction):
        new_index = self.cw.stateTab.currentIndex() - 1
        if direction == 'next':
            new_index = self.cw.stateTab.currentIndex() + 1
        if new_index not in range(self.cw.stateTab.count()):
            new_index = 0
        self.cw.stateTab.setCurrentIndex(new_index)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.cw.operation.finished[str].connect(self.trayAction)
        self.cw.operation.finished[str].connect(self.tray.stop)
        self.cw.operation.operationCancelled.connect(self.tray.stop)
        self.cw.operation.started[str].connect(self.tray.animate)
        self.tray.showUpdatesSelected.connect(self.trayShowUpdates)         # buraya dikkat

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)

        self.cw.switchState(StateManager.UPGRADE)

        KApplication.kApplication().updateUserTimestamp()
       
        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            self.tray.showPopup()
        if self.tray.isVisible() and operation in ["System.Manager.updatePackage",
                                                   "System.Manager.installPackage",
                                                   "System.Manager.removePackage"]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.cw.mainLayout.insertWidget(0, self.busy)
        self.statusBar().addPermanentWidget(self.cw.actions, 1)
        self.statusBar().show()

        self.updateStatusBar('')

        self.cw.selectionStatusChanged[str].connect(self.updateStatusBar)
        self.cw.updatingStatus.connect(self.statusWaiting)

    def initializeActions(self):
        self.initializeOperationActions()

    def initializeOperationActions(self):

        self.showAllAction = QAction(QIcon.fromTheme("media-optical"), _translate("Packaga Manager","All Packages"), self)
        self.showAllAction.triggered.connect(lambda:self.cw.switchState(StateManager.ALL))
        self.cw.stateTab.addTab(QWidget(), QIcon.fromTheme("media-optical"), _translate("Packaga Manager","All Packages"))

        self.showInstallAction = QAction(QIcon.fromTheme("list-remove"), _translate("Packaga Manager","Installable Packages"), self)
        self.showInstallAction.triggered.connect(lambda:self.cw.switchState(StateManager.INSTALL))
        self.cw.stateTab.addTab(QWidget(), QIcon.fromTheme("list-add"), _translate("Packaga Manager","Installable Packages"))

        self.showRemoveAction = QAction(QIcon.fromTheme("list-add"), _translate("Packaga Manager","Installed Packages"), self)
        self.showRemoveAction.triggered.connect(lambda:self.cw.switchState(StateManager.REMOVE))
        self.cw.stateTab.addTab(QWidget(), QIcon.fromTheme("list-remove"), _translate("Packaga Manager","Installed Packages"))

        self.showUpgradeAction = QAction(QIcon.fromTheme("system-software-update"), _translate("Packaga Manager","Updates"), self)
        self.showUpgradeAction.triggered.connect(lambda:self.cw.switchState(StateManager.UPGRADE))
        self.cw.stateTab.addTab(QWidget(), QIcon("/usr/share/package-manager/data/star_1.svg"), _translate("Packaga Manager","Updates"))

        self.showPreferences = QAction(QIcon.fromTheme("preferences-system"), _translate("Packaga Manager","Settings"), self)
        self.showPreferences.triggered.connect(self.settingsDialog.show_)

        self.actionHelp = QAction(QIcon.fromTheme("help-about"), _translate("Packaga Manager","Help"), self)
        self.actionHelp.setShortcuts(QKeySequence.HelpContents)
        self.actionHelp.triggered.connect(self.showHelp)

        self.actionQuit = QAction(QIcon.fromTheme("media-eject"), _translate("Packaga Manager","Quit"), self)
        self.actionQuit.setShortcuts(QKeySequence.Quit)
        self.actionQuit.triggered.connect(qApp.exit)

        self.cw.menuButton.setMenu(QMenu('MainMenu', self.cw.menuButton))
        self.cw.menuButton.setIcon(QIcon.fromTheme("preferences-system"))
        self.cw.menuButton.menu().clear()

        self.cw.contentHistory.hide()

        self.cw.menuButton.menu().addAction(self.showPreferences)
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionHelp)
        self.cw.menuButton.menu().addAction(self.actionQuit)

        self.cw._states = {self.cw.state.ALL    :(0, self.showAllAction),
                           self.cw.state.INSTALL:(1, self.showInstallAction),
                           self.cw.state.REMOVE :(2, self.showRemoveAction),
                           self.cw.state.UPGRADE:(3, self.showUpgradeAction)}

        self.showAllAction.setChecked(True)
        self.cw.checkUpdatesButton.hide()
        self.cw.checkUpdatesButton.setIcon(QIcon.fromTheme("system-reboot"))
        self.cw.showBasketButton.clicked.connect(self.cw.showBasket)

        # Little time left for the new ui
        self.menuBar().setVisible(False)
        self.cw.switchState(self.cw.state.ALL)

    def statusWaiting(self):
        self.updateStatusBar(_translate("Packaga Manager",'Calculating dependencies...'), busy = True)

    def showHelp(self):
        self.Pds = pds.Pds()
        self.lang = localedata.setSystemLocale(justGet = True)
        
        if self.lang in os.listdir("/usr/share/package-manager/help"):
            pass
        else:
            self.lang = "en"

        
        if self.Pds.session == pds.Kde3 :
            os.popen("khelpcenter /usr/share/package-manager/help/%s/main_help.html" %(self.lang))
        else:
            helpdialog.HelpDialog(self,helpdialog.MAINAPP)


    def updateStatusBar(self, text, busy = False):
        if text == '':
            text = _translate("Packaga Manager","Currently your basket is empty.")
            self.busy.hide()
            self.cw.showBasketButton.hide()
        else:
            self.cw.showBasketButton.show()

        if busy:
            self.busy.busy()
            self.cw.showBasketButton.hide()
        else:
            self.busy.hide()

        self.cw.statusLabel.setText(text)
        self.cw.statusLabel.setToolTip(text)

    def queryClose(self):
        if config.PMConfig().systemTray():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray:
                del self.tray.notification
            return True
        return False

    def CloseEvent(self,event):
        if self.iface.operationInProgress():
            return
Exemplo n.º 19
0
    def __init__(self):
        QMainWindow.__init__(self)
        
        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()
        
        self.restore_wnd_geometry()

        self.downloads = Downloads(self)
        self.add_downloads = AddDownloads(self)
        self.log = Log(self)
        
        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM), _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM), _('Start Download'), self.on_start_download, False)
        self.accounts = (QToolButton(), media.get_icon(media.ACCOUNTS, media.MEDIUM), _('Accounts'), self.on_accounts, True)
        self.preferences = (QToolButton(), media.get_icon(media.PREFERENCES, media.MEDIUM), _('Preferences'), self.on_preferences, True)
        self.about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM), _('About'), self.on_about, True)
        
        self.menu = QMenu()
        self.preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        self.preferences[BTN].setMenu(self.menu)
        
        self.toolbar = Toolbar(self, [self.start, self.stop, None, self.accounts, self.preferences, None, self.about])

        self.addToolBar(self.toolbar)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget()
        #
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        self.show_or_hide_tray()

        #load session.
        self.load_session()

        #add core's event loop
        self.dispatcher = ThreadDispatcher(self)
        self.dispatcher.start()

        #quit event
        events.quit.connect(self.event_close)

        #custom qt signals
        signals.switch_tab.connect(self.switch_tab)
        signals.show_or_hide_tray.connect(self.show_or_hide_tray)

        self.show()
Exemplo n.º 20
0
    def __init__(self, master):
        self.master = master
        self.ID = "main"
        #============ Menu ======================

        self.menubar = Menu(master)
        self.filemenu = Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="Save")
        self.filemenu.add_command(label="Open")
        self.filemenu.add_command(label="New")
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Audio Settings",
                                  command=self.openConfigSettings)
        self.menubar.add_cascade(label="File", menu=self.filemenu)

        self.master.config(menu=self.menubar)

        # True/False is Editable or Not.
        self.mainSettingsList = [["consFolder", False], ["vowelFolder", False],
                                 ["outFolder", False], ["fred", True],
                                 ["initial frequency", True],
                                 ["xFade Length", True], ["Vowel Pad", True],
                                 ["Splice Point", True],
                                 ["Tuning Bounds", True], ["Pad First", True],
                                 ["Pad Last", True], ["Crossfade First", True],
                                 ["Crossfade Last", True]]

        self.indivSettingsList = [["consFile", True], ["vowelFile", True],
                                  ["initial frequency", True],
                                  ["xFade Length", True], ["InitPad", True],
                                  ["EndPad", True], ["Vowel Pad", True],
                                  ["Splice Point", True],
                                  ["Tuning Bounds", True], ["outFile", True]]
        self.readSettings()
        #============ vars ==================

        #self.toneFolderPath = StringVar()
        #self.attackFolderPath = StringVar()

        #============ frames ================

        self.mainFrame = ttk.Frame(self.master)
        self.mainFrame.grid()

        self.leftWrapper = ttk.Frame(self.mainFrame)
        self.leftWrapper.grid(row=0, column=0, sticky=N)

        self.inFrame = ttk.LabelFrame(self.leftWrapper, text="File Setup")
        self.inFrame.grid(row=0, column=0, sticky=N)

        self.settingsFrame = ttk.LabelFrame(self.mainFrame,
                                            text="Main Settings")
        self.settingsFrame.grid(row=0, column=1)

        self.trayFrame = ttk.LabelFrame(self.leftWrapper, text="Tray")
        self.trayFrame.grid(row=2, column=0, sticky=N + W)

        self.goFrame = ttk.Frame(self.leftWrapper)
        self.goFrame.grid(row=1, column=0, sticky=E + W)

        self.graphicsFrame = ttk.LabelFrame(self.mainFrame, text="Editing")
        self.graphicsFrame.grid(row=0, column=2, sticky=N)

        #============ inFrame ==========================

        self.chooseAttackButton = ttk.Button(
            self.inFrame,
            text="Choose Attack Folder",
            command=lambda: self.chooseFolder("consFolder"))
        self.chooseAttackButton.grid(row=0, column=0)

        self.chooseToneButton = ttk.Button(
            self.inFrame,
            text="Choose Tone Folder",
            command=lambda: self.chooseFolder("vowelFolder"))
        self.chooseToneButton.grid(row=0, column=1)

        self.chooseFred = ttk.Button(self.inFrame,
                                     text="Choose fred",
                                     command=lambda: self.chooseFolder("fred"))
        self.chooseFred.grid(row=0, column=2)

        self.chooseDestinationButton = ttk.Button(
            self.inFrame,
            text="Choose Destination Folder",
            command=lambda: self.chooseFolder("outFolder"))
        self.chooseDestinationButton.grid(row=1,
                                          column=0,
                                          columnspan=2,
                                          sticky=W)

        #============ goFrame =============================

        self.goButton = ttk.Button(self.goFrame,
                                   text="Process Batch",
                                   command=self.spliceByBatch)
        self.goButton.grid(row=0, column=0)

        self.statusLabel = ttk.Label(self.goFrame, text="IDLE")
        self.statusLabel.grid(row=0, column=1)

        #============ settingsFrame =======================

        self.mainSettings = MainSettings(self.settingsFrame,
                                         settings=self.mainSettingsList)
        self.mainSettings.grid(row=0, column=0, sticky=E)

        print "  "
        print "============ SETTINGS IMPORTED FROM json ============="
        self.mainSettings.setValues(self.settings)
        print "============ END OF json IMPORT ============="

        self.applySettingsButton = ttk.Button(self.settingsFrame,
                                              text="Apply",
                                              command=self.applyMainSettings)
        self.applySettingsButton.grid(row=1)

        #============ trayFrame ============================

        self.tray = Tray(
            self.trayFrame,
            settings=self.indivSettingsList)  #,initialSettings=self.settings)
        self.tray.grid()
        #for i in range(11):
        #	self.tray.addItem(json.loads(open('settings.json').read()))

        # self.placeHolder = ttk.Button(self.trayFrame, text="Placeholder",
        # 							  command=self.placeholderButton)
        # self.placeHolder.grid()

        #============ graphicsFrame ============================
        self.graphs = {}

        self.padGraph = Graphic(self.graphicsFrame, self.numFiles, 100,
                                "Padding")
        self.padGraph.grid(row=0, column=0)
        self.graphs["pads"] = self.padGraph

        self.padGraph = Graphic(self.graphicsFrame,
                                self.numFiles,
                                100,
                                "Cross Fade Length",
                                maxRange=800)
        self.padGraph.grid(row=0, column=1)
        self.graphs["cfls"] = self.padGraph
Exemplo n.º 21
0
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, app = None, silence = False):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        self.iface = backend.pm.Iface()
        self.setWindowIcon(QtGui.QIcon(":/data/package-manager.png"))
        self.connect(app, SIGNAL("aboutToQuit()"), self.slotQuit)
        self.setCentralWidget(MainWidget(self, silence))
        self.initializeActions()

        if not silence:
            self.settingsDialog = SettingsDialog(self)
            self.initializeStatusBar()
            self.initializeTray()
            self.connectMainSignals()

    def connectMainSignals(self):
        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.centralWidget().initialize)
        self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"), self.centralWidget().updateSettings)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged)
        self.connect(self.centralWidget().state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.connect(self.centralWidget().operation, SIGNAL("finished(QString)"), self.trayAction)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)
        self.centralWidget().switchState(StateManager.UPGRADE, action=False)
        self.centralWidget().initialize()
        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            self.tray.showPopup()
        if self.tray.isVisible() and operation in ["System.Manager.updatePackage",
                                                   "System.Manager.installPackage",
                                                   "System.Manager.removePackage"]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.statusLabel = QtGui.QLabel(i18n("Currently your basket is empty."), self.statusBar())
        self.statusLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.statusBar().addWidget(self.statusLabel)
        self.statusBar().setSizeGripEnabled(True)
        self.wheelMovie = QtGui.QMovie(self)
        self.statusLabel.setText(i18n("Currently your basket is empty."))
        self.wheelMovie.setFileName(":/data/wheel.mng")
        self.connect(self.centralWidget(), SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar)
        self.connect(self.centralWidget(), SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.toolBar = QtGui.QToolBar(self)
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)

        self.initializeOperationActions()

    def initializeOperationActions(self):
        actionGroup = QtGui.QActionGroup(self)

        self.menubar = QtGui.QMenuBar(self)

        self.menuFile = QtGui.QMenu(i18n('File'), self.menubar)
        self.menuOptions = QtGui.QMenu(i18n('Settings'), self.menubar)
        self.menuHelp = QtGui.QMenu(i18n('Help'), self.menubar)

        self.quitAppAction = QtGui.QAction(KIcon(('exit', 'application-exit')), i18n("Quit"), self)
        self.quitAppAction.setShortcut(QtGui.QKeySequence('Ctrl+q'))
        self.quitAppAction.triggered.connect(self.slotQuit)

        self.helpAppAction = QtGui.QAction(KIcon(('help', 'help-contents')), i18n("Help"), self)
        self.helpAppAction.setShortcut(QtGui.QKeySequence('F1'))
        self.helpAppAction.triggered.connect(self.showHelp)
        self.menuHelp.addAction(self.helpAppAction)

        self.setMenuBar(self.menubar)

        # Action Show Installable Packages
        self.showInstallAction = QtGui.QAction(KIcon("list-add"),
                          i18n("Show Installable Packages"), self)
        self.showInstallAction.setCheckable(True)
        self.showInstallAction.setChecked(True)
        self.showInstallAction.triggered.connect(lambda:self.centralWidget().switchState(StateManager.INSTALL))
        actionGroup.addAction(self.showInstallAction)
        self.toolBar.addAction(self.showInstallAction)
        self.menuFile.addAction(self.showInstallAction)

        # Action Show Installed Packages
        self.showRemoveAction = QtGui.QAction(KIcon("list-remove"),
                          i18n("Show Installed Packages"), self)
        self.showRemoveAction.setCheckable(True)
        self.showRemoveAction.triggered.connect(lambda:self.centralWidget().switchState(StateManager.REMOVE))
        actionGroup.addAction(self.showRemoveAction)
        self.toolBar.addAction(self.showRemoveAction)
        self.menuFile.addAction(self.showRemoveAction)

        # Action Show Upgradable Packages
        self.showUpgradeAction = QtGui.QAction(KIcon("view-refresh"),
                          i18n("Show Upgradable Packages"), self)
        self.showUpgradeAction.setCheckable(True)
        self.showUpgradeAction.triggered.connect(lambda:self.centralWidget().switchState(StateManager.UPGRADE))
        actionGroup.addAction(self.showUpgradeAction)
        self.toolBar.addAction(self.showUpgradeAction)
        self.menuFile.addAction(self.showUpgradeAction)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.quitAppAction)

        self.showSettingsAction = QtGui.QAction(KIcon("preferences-system"),
                          i18n("Package Manager Settings"), self)
        self.showSettingsAction.triggered.connect(self.showSettingsDialog)
        self.menuOptions.addAction(self.showSettingsAction)

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuOptions.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

    def showSettingsDialog(self):
        self.settingsDialog.show()

    def statusWaiting(self):
        self.statusLabel.setMovie(self.wheelMovie)
        self.wheelMovie.start()

    def updateStatusBar(self, text):
        self.wheelMovie.stop()
        self.statusLabel.setText(text)

    def queryClose(self):
        if config.PMConfig().systemTray():
            self.hide()
            return False
        return True

    def showHelp(self):
        helpDialog = helpdialog.HelpDialog(self, helpdialog.MAINAPP)
        helpDialog.show()

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray.notification:
                self.tray.notification.close()
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
        QtCore.QCoreApplication.quit()
Exemplo n.º 22
0
class MainWindow(KXmlGuiWindow, Ui_MainWindow):
    def __init__(self, app = None):
        KXmlGuiWindow.__init__(self, None)
        self.setupUi(self)
        self.app = app
        self.iface = backend.pm.Iface()
        _time()
        self.setWindowIcon(KIcon(":/data/package-manager.png"))
        self.setCentralWidget(MainWidget(self))
        self.settingsDialog = SettingsDialog(self)
        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()
        _time()

    def resizeEvent(self, event):
        # info label should be resized automatically,
        # if the mainwindow resized.
        width = self.width()
        height = self.statusBar().height() + 4
        self.statusLabel.resize(QSize(width, height))
        self.statusLabel.move(0, self.height() - height + 2)#self.width() / 2 - 170, self.height() / 2 - 40)

    def connectMainSignals(self):
        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.centralWidget().initialize)
        self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"), self.centralWidget().updateSettings)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged)
        self.connect(self.centralWidget().state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu)
        self.connect(self.centralWidget(), SIGNAL("repositoriesUpdated()"), self.tray.updateTrayUnread)
        self.connect(KApplication.kApplication(), SIGNAL("shutDown()"), self.slotQuit)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.connect(self.centralWidget().operation, SIGNAL("finished(QString)"), self.trayAction)
        self.connect(self.centralWidget().operation, SIGNAL("finished(QString)"), self.tray.stop)
        self.connect(self.centralWidget().operation, SIGNAL("operationCancelled()"), self.tray.stop)
        self.connect(self.centralWidget().operation, SIGNAL("started(QString)"), self.tray.animate)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)
        self.centralWidget().switchState(StateManager.UPGRADE, action=False)
        self.centralWidget().initialize()
        KApplication.kApplication().updateUserTimestamp()
        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            self.tray.showPopup()
        if self.tray.isVisible() and operation in ["System.Manager.updatePackage",
                                                   "System.Manager.installPackage",
                                                   "System.Manager.removePackage"]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):

        # An info label to show a proper information,
        # if there is no updates available.
        self.statusLabel = QLabel(i18n("Currently your basket is empty."), self)
        self.statusLabel.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        self.statusLabel.setStyleSheet("background-color:rgba(0,0,0,220); \
                                 color:white; \
                                 border: 1px solid white;")
        # self.info.hide()
        self.statusLabel.show()
        self.wheelMovie = QtGui.QMovie(self)
        self.statusLabel.setText(i18n("Currently your basket is empty."))
        self.wheelMovie.setFileName(":/data/wheel.mng")
        self.connect(self.centralWidget(), SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar)
        self.connect(self.centralWidget(), SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.toolBar().setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        KStandardAction.quit(KApplication.kApplication().quit, self.actionCollection())
        KStandardAction.preferences(self.settingsDialog.show, self.actionCollection())

        self.initializeOperationActions()
        self.setupGUI(KXmlGuiWindow.Default, "/usr/share/package-manager/data/packagemanagerui.rc")

    def initializeOperationActions(self):
        actionGroup = QtGui.QActionGroup(self)

        self.showInstallAction = KToggleAction(KIcon("list-add"), i18n("Show Installable Packages"), self)
        self.showInstallAction.setChecked(True)
        self.actionCollection().addAction("showInstallAction", self.showInstallAction)
        self.connect(self.showInstallAction, SIGNAL("triggered()"), lambda:self.centralWidget().switchState(StateManager.INSTALL))
        actionGroup.addAction(self.showInstallAction)

        self.showRemoveAction = KToggleAction(KIcon("list-remove"), i18n("Show Installed Packages"), self)
        self.actionCollection().addAction("showRemoveAction", self.showRemoveAction)
        self.connect(self.showRemoveAction, SIGNAL("triggered()"), lambda:self.centralWidget().switchState(StateManager.REMOVE))
        actionGroup.addAction(self.showRemoveAction)

        self.showUpgradeAction = KToggleAction(KIcon("view-refresh"), i18n("Show Upgradable Packages"), self)
        self.actionCollection().addAction("showUpgradeAction", self.showUpgradeAction)
        self.connect(self.showUpgradeAction, SIGNAL("triggered()"), lambda:self.centralWidget().switchState(StateManager.UPGRADE))
        actionGroup.addAction(self.showUpgradeAction)

    def statusWaiting(self):
        self.statusLabel.setMovie(self.wheelMovie)
        self.wheelMovie.start()

    def updateStatusBar(self, text):
        self.wheelMovie.stop()
        self.statusLabel.setText(text)

    def queryClose(self):
        if config.PMConfig().systemTray() and not KApplication.kApplication().sessionSaving():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray:
                del self.tray.notification
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
Exemplo n.º 23
0
    def __init__(self,
                 n_trays,
                 feed_tray,
                 feed_stream_liq,
                 reflux,
                 vapor_reboil,
                 condensate,
                 bottoms,
                 pressure,
                 tray_efficiency=1.0,
                 name=None):
        '''
        feed_tray must be an integer between 1 and n_trays-2 (feed cannot be to the top or bottom trays for now)
        the bottom tray is tray number zero
        the top tray is tray number n_trays-1
        
        the default efficiency is 1 for all trays.
        if tray_efficiency is a scalar, it is used for all trays.
        if tray_efficiency is a dict (tray:efficiency), it is used for the specified trays. the remaining are
        assigned an efficiency of 1.
        '''
        self.column_num = SimpleColumn.n_columns
        super().__init__(name, self.column_num)
        SimpleColumn.n_columns += 1

        assert n_trays > 0, '{}: Number of tray must be greater than zero (specified {})'.format(
            self.name, n_trays)
        self.n_trays = n_trays

        assert (feed_tray >= 1) and (feed_tray <= self.n_trays-2), \
            '{}: Feed tray number must be from 1 to {} inclusive (specified {}). No feed to the top or bottom trays for now' \
            .format(self.name, self.n_trays-2, feed_tray)
        self.feed_tray = feed_tray

        self.feed_stream_liq = feed_stream_liq
        self.reflux = reflux
        self.vapor_reboil = vapor_reboil
        self.condensate = condensate
        self.bottoms = bottoms
        self.pressure = pressure
        self.n_vars = 0
        self.n_eqns = 0
        self.xvar = None
        self.eqns = None

        # figure out number of streams to be created as part of this column
        # for each tray, there are two streams leaving (one liquid, one vapor)
        # one liquid feed stream (comes from outside the column)
        # one stream that is a combination of the liquid feed stream and the liquid from the tray above the feed tray

        # create the streams associated with the column
        # tray liquid and vapor streams
        self.tray_liq_stream = []
        for i_tray in range(self.n_trays):
            name = self.name + 'Tray' + str(i_tray) + 'Liquid'
            #            self.tray_liq_stream.append(Stream(n_comps=N_COMPS, name=name))
            self.tray_liq_stream.append(
                Stream(n_comps=self.feed_stream_liq.n_comps, name=name))

        self.tray_vap_stream = []
        for i_tray in range(self.n_trays):
            name = self.name + 'Tray' + str(i_tray) + 'Vapor'
            #            self.tray_vap_stream.append(Stream(n_comps=N_COMPS, name=name))
            self.tray_vap_stream.append(
                Stream(n_comps=self.feed_stream_liq.n_comps, name=name))

        # create the mixed stream consisting of the feed stream and the liquid from the tray above the feed tray
        name = self.name + 'MixedLiquidFeed'
        #        self.mixed_liq_feed = Stream(n_comps=N_COMPS, name=name)
        self.mixed_liq_feed = Stream(n_comps=self.feed_stream_liq.n_comps,
                                     name=name)
        self.unit_dict[name] = self.mixed_liq_feed

        # create the mixer needed to mix the liquid feed and the liquid from the tray above the feed tray
        name = self.name + 'FeedMixer'
        self.feed_mixer = Mixer(streams_in=[
            self.feed_stream_liq, self.tray_liq_stream[feed_tray + 1]
        ],
                                streams_out=[self.mixed_liq_feed],
                                name=name)
        self.unit_dict[name] = self.feed_mixer

        # create trays
        self.trays = []
        for i_tray in range(self.n_trays):
            name = self.name + 'Tray' + str(i_tray)
            if i_tray == self.feed_tray:
                self.trays.append(
                    Tray(
                        liq_stream_in=self.mixed_liq_feed,
                        liq_stream_out=self.tray_liq_stream[i_tray],
                        vap_stream_in=self.tray_vap_stream[i_tray - 1],
                        vap_stream_out=self.tray_vap_stream[i_tray],
                        tray_efficiency=1,  # will be updated later
                        pressure=self.pressure,
                        name=name))
            elif i_tray == 0:
                self.trays.append(
                    Tray(
                        liq_stream_in=self.tray_liq_stream[i_tray + 1],
                        liq_stream_out=self.tray_liq_stream[i_tray],
                        vap_stream_in=self.vapor_reboil,
                        vap_stream_out=self.tray_vap_stream[i_tray],
                        tray_efficiency=1,  # will be updated later
                        pressure=self.pressure,
                        name=name))
            elif i_tray == self.n_trays - 1:
                self.trays.append(
                    Tray(
                        liq_stream_in=self.reflux,
                        liq_stream_out=self.tray_liq_stream[i_tray],
                        vap_stream_in=self.tray_vap_stream[i_tray - 1],
                        vap_stream_out=self.tray_vap_stream[i_tray],
                        tray_efficiency=1,  # will be updated later
                        pressure=self.pressure,
                        name=name))
            else:
                self.trays.append(
                    Tray(
                        liq_stream_in=self.tray_liq_stream[i_tray + 1],
                        liq_stream_out=self.tray_liq_stream[i_tray],
                        vap_stream_in=self.tray_vap_stream[i_tray - 1],
                        vap_stream_out=self.tray_vap_stream[i_tray],
                        tray_efficiency=1,  # will be updated later
                        pressure=self.pressure,
                        name=name))

        self.update_tray_efficiency(tray_efficiency)

        for s in self.tray_liq_stream:
            self.unit_dict[s.name] = s

        for s in self.tray_vap_stream:
            self.unit_dict[s.name] = s

        for s in self.trays:
            self.unit_dict[s.name] = s

        name = self.name + 'CondensateConnector'
        self.condensate_connector = Connector(self.condensate,
                                              self.tray_vap_stream[n_trays -
                                                                   1],
                                              name=name)
        self.unit_dict[name] = self.condensate_connector

        name = self.name + 'BottomsConnector'
        self.bottoms_connector = Connector(self.bottoms,
                                           self.tray_liq_stream[0],
                                           name=name)
        self.unit_dict[name] = self.bottoms_connector
Exemplo n.º 24
0
class MainWindow(KXmlGuiWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        KXmlGuiWindow.__init__(self, parent)
        self.setupUi(self)
        self.setWindowIcon(KIcon(":/data/package-manager.png"))
        self.setCentralWidget(MainWidget(self))
        self.settingsDialog = SettingsDialog(self)
        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.offlinemanager = OfflineManager()
        self.connectOfflineSignals()

    def connectMainSignals(self):
        self.connect(self, SIGNAL("packagesChanged()"), self.centralWidget().initialize)
        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.centralWidget().initialize)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged)
        self.connect(self.centralWidget().state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu)
        self.connect(KApplication.kApplication(), SIGNAL("shutDown()"), self.slotQuit)

    def connectOfflineSignals(self):
        self.connect(self, SIGNAL("importIndex(str)"), self.offlinemanager.importIndex)
        self.connect(self, SIGNAL("exportIndex(str)"), self.offlinemanager.exportIndex)
        self.connect(self, SIGNAL("openSession(str)"), self.offlinemanager.openSession)
        self.connect(self, SIGNAL("saveSession(str)"), self.offlinemanager.saveSession)

    def initializeTray(self):
        self.tray = Tray(self)
        self.connect(self.centralWidget().operation, SIGNAL("finished(QString)"), self.trayShow)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)
        self.centralWidget().switchState(StateManager.UPGRADE, action=False)
        self.centralWidget().initialize()
        KApplication.kApplication().updateUserTimestamp()
        self.show()
        self.raise_()

    def trayShow(self, operation):
        if not self.isVisible() and operation in [
            "System.Manager.updateRepository",
            "System.Manager.updateAllRepositories",
        ]:
            self.tray.showPopup()

    def initializeStatusBar(self):
        self.statusLabel = QtGui.QLabel(i18n("Currently your basket is empty."), self.statusBar())
        self.statusLabel.setAlignment(Qt.AlignCenter)
        self.statusBar().addWidget(self.statusLabel)
        self.statusBar().setSizeGripEnabled(True)
        self.wheelMovie = QtGui.QMovie(self)
        self.statusLabel.setText(i18n("Currently your basket is empty."))
        self.wheelMovie.setFileName(":/data/wheel.mng")
        self.connect(self.centralWidget(), SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar)
        self.connect(self.centralWidget(), SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.toolBar().setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        KStandardAction.quit(KApplication.kApplication().quit, self.actionCollection())
        KStandardAction.preferences(self.settingsDialog.show, self.actionCollection())

        self.initializeOperationActions()
        self.setupGUI(KXmlGuiWindow.Default, "data/packagemanagerui.rc")

    def initializeOperationActions(self):
        actionGroup = QtGui.QActionGroup(self)

        self.showInstallAction = KToggleAction(KIcon("list-add"), i18n("Show Installable Packages"), self)
        self.showInstallAction.setChecked(True)
        self.actionCollection().addAction("showInstallAction", self.showInstallAction)
        self.connect(
            self.showInstallAction,
            SIGNAL("triggered()"),
            lambda: self.centralWidget().switchState(StateManager.INSTALL),
        )
        self.connect(self.showInstallAction, SIGNAL("triggered()"), self.centralWidget().initialize)
        actionGroup.addAction(self.showInstallAction)

        self.showRemoveAction = KToggleAction(KIcon("list-remove"), i18n("Show Installed Packages"), self)
        self.actionCollection().addAction("showRemoveAction", self.showRemoveAction)
        self.connect(
            self.showRemoveAction, SIGNAL("triggered()"), lambda: self.centralWidget().switchState(StateManager.REMOVE)
        )
        self.connect(self.showRemoveAction, SIGNAL("triggered()"), self.centralWidget().initialize)
        actionGroup.addAction(self.showRemoveAction)

        self.showUpgradeAction = KToggleAction(KIcon("view-refresh"), i18n("Show Upgradable Packages"), self)
        self.actionCollection().addAction("showUpgradeAction", self.showUpgradeAction)
        self.connect(
            self.showUpgradeAction,
            SIGNAL("triggered()"),
            lambda: self.centralWidget().switchState(StateManager.UPGRADE),
        )
        actionGroup.addAction(self.showUpgradeAction)

        self.importIndexAction = KToggleAction(KIcon("list-add"), i18n("Import Index"), self)
        self.actionCollection().addAction("importIndexAction", self.importIndexAction)
        self.connect(self.importIndexAction, SIGNAL("triggered()"), self.importIndex)

        self.exportIndexAction = KToggleAction(KIcon("list-remove"), i18n("Export Index"), self)
        self.actionCollection().addAction("exportIndexAction", self.exportIndexAction)
        self.connect(self.exportIndexAction, SIGNAL("triggered()"), self.exportIndex)

        self.openSessionAction = KToggleAction(KIcon("list-add"), i18n("Open Session"), self)
        self.actionCollection().addAction("openSessionAction", self.openSessionAction)
        self.connect(self.openSessionAction, SIGNAL("triggered()"), self.openSession)

        self.saveSessionAction = KToggleAction(KIcon("list-remove"), i18n("Save Session"), self)
        self.actionCollection().addAction("saveSessionAction", self.saveSessionAction)
        self.connect(self.saveSessionAction, SIGNAL("triggered()"), self.saveSession)

    def statusWaiting(self):
        self.statusLabel.setMovie(self.wheelMovie)
        self.wheelMovie.start()

    def updateStatusBar(self, text):
        self.wheelMovie.stop()
        self.statusLabel.setText(text)

    def queryClose(self):
        if config.PMConfig().systemTray() and not KApplication.kApplication().sessionSaving():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not backend.pm.Iface().operationInProgress():
            if self.tray.notification:
                self.tray.notification.close()
            return True
        return False

    def slotQuit(self):
        if backend.pm.Iface().operationInProgress():
            return

    def switchSession(self, session):
        self.centralWidget().switchSession(session)
        self.showInstallAction.setChecked(True)

    def importIndex(self):
        filename = str(KFileDialog.getOpenFileName(KUrl("pisi-installed"), "*.xml", self, i18n("Import index file")))

        if filename:
            self.switchSession(SessionManager.OFFLINE)
            self.emit(SIGNAL("importIndex(str)"), filename)
            self.emit(SIGNAL("packagesChanged()"))

    def exportIndex(self):
        filename = str(KFileDialog.getSaveFileName(KUrl("pisi-installed"), "*.xml", self, i18n("Export index file")))

        if filename:
            self.emit(SIGNAL("exportIndex(str)"), filename)

    def openSession(self):
        filename = str(
            KFileDialog.getOpenFileName(KUrl("pisi-archive"), "*.offline", self, i18n("Open offline session"))
        )

        if filename:
            self.emit(SIGNAL("openSession(str)"), filename)

    def saveSession(self):
        filename = str(
            KFileDialog.getSaveFileName(KUrl("pisi-archive"), "*.offline", self, i18n("Save offline session"))
        )

        if filename:
            self.emit(SIGNAL("saveSession(str)"), filename)
            self.switchSession(SessionManager.NORMAL)
Exemplo n.º 25
0
class TunnelDialog(QDialog, Ui_TunnelDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setupUi(self)
        self._explicitQuit = False

        # Tunnels
        self._tunnels = []

        # Setup tray
        self.tray = Tray(self, "IOSSHy", Icon("network-server"))
        self.tray.activated.connect(self.activated)

        action = QAction("&Configure", self.tray.menu)
        action.setIcon(Icon("configure"))
        action.setIconVisibleInMenu(True)
        action.triggered.connect(self.show)
        self.tray.menu.addAction(action)
        self.tray.menu.setDefaultAction(action)

        self.tray.menu.addSeparator()
        self.actionNoTun = QAction("No tunnels configured", self.tray.menu)
        self.actionNoTun.setEnabled(False)
        self.tray.menu.addAction(self.actionNoTun)
        self.actionLastSep = self.tray.menu.addSeparator()

        if kde:
            action = QAction("&About", self.tray.menu)
            action.triggered.connect(self.about)
            self.tray.menu.addAction(action)

        action = QAction("&Quit", self.tray.menu)
        action.setIcon(Icon("application-exit"))
        action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q))
        action.triggered.connect(self.quit)
        self.tray.menu.addAction(action)

        # Load settings
        self.readSettings()
        self.hide()

    def show(self):
        self.visible = True
        QDialog.show(self)

    def hide(self):
        self.visible = False
        self.writeSettings()
        QDialog.hide(self)

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

    def on_listTunnels_currentItemChanged(self, current, previous):
        self.grpTunnelProperties.setEnabled(current is not None)
        self.grpSshProperties.setEnabled(current is not None)
        if current is not None:
            tunnel = self._tunnels[self.listTunnels.row(current)]

            self.txtName.setText( tunnel.name )
            self.txtHost.setText( "localhost" if tunnel.host == "" else tunnel.host )
            self.txtRemoteHost.setText( "localhost" if tunnel.remoteHost == "" else tunnel.remoteHost )
            self.txtLocalPort.setText( "0" if tunnel.localPort is None else str(tunnel.localPort) )
            self.txtPort.setText( str(tunnel.port) )
            self.txtSshPort.setText( str(tunnel.sshPort) )
            self.txtUsername.setText( "root" if tunnel.username == "" else tunnel.username )
            self.txtCommand.setText( "" if tunnel.command is None else tunnel.command )
            self.chkCloseOnTerm.setChecked( Qt.Checked if tunnel.autoClose else Qt.Unchecked )

            self.txtName.setFocus()
            self.txtName.selectAll()
        else:
            self.txtName.setText("")
            self.txtHost.setText("localhost")
            self.txtRemoteHost.setText("localhost")
            self.txtLocalPort.setText("0")
            self.txtPort.setText("")
            self.txtSshPort.setText("22")
            self.txtUsername.setText("root")
            self.txtCommand.setText("")
            self.chkCloseOnTerm.setChecked(Qt.Unchecked)

    def currentTunnel(self):
        try:
            ti = self.listTunnels.currentRow()
            return None if ti < 0 else self._tunnels[ti]
        except IndexError:
            return None

    def on_txtName_textEdited(self, text):
        self.currentTunnel().name = text

    def on_txtHost_textEdited(self, text):
        self.currentTunnel().host = text

    def on_txtRemoteHost_textEdited(self, text):
        self.currentTunnel().remoteHost = text

    def on_txtLocalPort_textEdited(self, text):
        self.currentTunnel().localPort = text

    def on_txtPort_textEdited(self, text):
        self.currentTunnel().port = text

    def on_txtSshPort_textEdited(self, text):
        self.currentTunnel().sshPort = text

    def on_txtUsername_textEdited(self, text):
        self.currentTunnel().username = text

    def on_txtCommand_textEdited(self, text):
        self.currentTunnel().command = text

    def on_chkCloseOnTerm_stateChanged(self, state):
        if self.currentTunnel() is not None:
            self.currentTunnel().autoClose = state == Qt.Checked

    @pyqtSignature("")
    def on_btnAddTunnel_clicked(self):
        tunnel = Tunnel(self)
        self._tunnels.append(tunnel)
        self.listTunnels.setCurrentItem(tunnel.item)
        self.tray.menu.insertAction(self.actionLastSep, tunnel.action)
        self.tray.menu.removeAction(self.actionNoTun)

    @pyqtSignature("")
    def on_btnDuplicateTunnel_clicked(self):
        cur = self.currentTunnel()
        if cur is not None:
            tunnel = Tunnel(self)
            tunnel.name = cur.name+" (copy)"
            tunnel.host = cur.host
            tunnel.localPort = cur.localPort
            tunnel.port = cur.port
            tunnel.username = cur.username
            tunnel.command = cur.command
            tunnel.autoClose = cur.autoClose
            self._tunnels.append(tunnel)
            self.listTunnels.setCurrentItem(tunnel.item)
            self.tray.menu.insertAction(self.actionLastSep, tunnel.action)

    @pyqtSignature("")
    def on_btnRemoveTunnel_clicked(self):
        tunnel = self.currentTunnel()
        if tunnel is not None:
            ti = self.listTunnels.currentRow()
            del self._tunnels[ti]
            self.listTunnels.setCurrentRow(0 if ti != 0 else 1)
            self.listTunnels.takeItem(ti)
            self.listTunnels.setCurrentItem(None, QItemSelectionModel.Clear)
            self.tray.menu.removeAction(tunnel.action)
            del tunnel

            if len(self._tunnels) == 0:
                self.tray.menu.insertAction(self.actionLastSep, self.actionNoTun)

    def updateTooltip(self):
        tuninfo = []
        for tunnel in self._tunnels:
            if tunnel.isOpen():
                tuninfo.append( "<div>{name}: {host}:{port} => {local}</div>".format(name=tunnel.name, host=tunnel.host, port=tunnel.port, local=tunnel.tunnelPort) )
        if tuninfo:
            tuninfo.insert(0, "<b>Active tunnels:</b>")
            self.tray.setActive()
        else:
            self.tray.setActive(False)
        self.tray.setToolTipSubTitle( "\n".join(tuninfo) )

    def activated(self):
        if self.visible:
            self.hide()
        else:
            self.show()

    def readSettings(self):
        if os.name == 'nt':
            settings = QSettings()
        else:
            settings = QSettings(os.path.expanduser("~/.iosshy.ini"), QSettings.IniFormat)
        for name in settings.childGroups():
            tunnel = Tunnel(self)
            tunnel.name = name
            tunnel.readSettings(settings)
            self._tunnels.append(tunnel)
            self.tray.menu.insertAction(self.actionLastSep, tunnel.action)
            self.tray.menu.removeAction(self.actionNoTun)

    def writeSettings(self):
        if os.name == 'nt':
            settings = QSettings()
        else:
            settings = QSettings(os.path.expanduser("~/.iosshy.ini"), QSettings.IniFormat)
        settings.clear()
        for tunnel in self._tunnels:
            tunnel.writeSettings(settings)

    def about(self):
        KAboutApplicationDialog(application.aboutData, self).exec_()
        if self.isHidden():
            self.show()
            self.hide()

    def quit(self):
        self.writeSettings()
        self._explicitQuit = True
        self.close()
Exemplo n.º 26
0
class Gui(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(
            QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()

        self.restore_wnd_geometry()

        self.downloads = Downloads(self)
        self.add_downloads = AddDownloads(self)
        self.log = Log(self)

        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM),
                     _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM),
                      _('Start Download'), self.on_start_download, False)
        self.accounts = (QToolButton(),
                         media.get_icon(media.ACCOUNTS, media.MEDIUM),
                         _('Accounts'), self.on_accounts, True)
        self.preferences = (QToolButton(),
                            media.get_icon(media.PREFERENCES, media.MEDIUM),
                            _('Preferences'), self.on_preferences, True)
        self.about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM),
                      _('About'), self.on_about, True)

        self.menu = QMenu()
        self.preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        self.preferences[BTN].setMenu(self.menu)

        self.toolbar = Toolbar(self, [
            self.start, self.stop, None, self.accounts, self.preferences, None,
            self.about
        ])

        self.addToolBar(self.toolbar)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget()
        #
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        self.show_or_hide_tray()

        #load session.
        self.load_session()

        #add core's event loop
        self.dispatcher = ThreadDispatcher(self)
        self.dispatcher.start()

        #quit event
        events.quit.connect(self.event_close)

        #custom qt signals
        signals.switch_tab.connect(self.switch_tab)
        signals.show_or_hide_tray.connect(self.show_or_hide_tray)

        self.show()

    def customEvent(self, event):
        #process idle_queue_dispacher events
        event.callback()

    def switch_tab(self, index):
        self.tab.setCurrentIndex(index)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def restore_wnd_geometry(self):
        wx, wy, ww, wh = QDesktopWidget().availableGeometry().getRect()
        x, y, w, h = conf.get_window_settings()
        if ww <= w or wh <= h:
            self.showMaximized()
        elif ww > x >= 0 and wh > y >= 0:  #resize and move
            self.setGeometry(x, y, w, h)
        else:  #resize only
            self.resize(w, h)

    def on_stop_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                stopped = api.stop_download(id_item)
                if stopped:
                    if items[row][1] == self.downloads.icons_dict[
                            cons.STATUS_QUEUE]:
                        items[row][1] = self.downloads.icons_dict[
                            cons.STATUS_STOPPED]
                    self.stop[BTN].setEnabled(False)
                    self.start[BTN].setEnabled(True)

    def on_start_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                started = api.start_download(id_item)
                if started:
                    items[row][1] = self.downloads.icons_dict[
                        cons.STATUS_QUEUE]  #status
                    items[row][10] = None  #status_msg
                    self.stop[BTN].setEnabled(True)
                    self.start[BTN].setEnabled(False)
            id_item_list = [row[0] for row in items]
            api.reorder_queue(id_item_list)

    def on_accounts(self):
        accounts = ConfigAccounts(self)

    def on_preferences(self):
        index_page = self.tab.indexOf(
            self.preferences)  #get the page containig the widget
        if index_page >= 0:  #if = -1 there is not such tab.
            self.tab.setCurrentIndex(index_page)
        else:
            index_page = self.tab.addTab(self.preferences, _('Preferences'))
            btn_close = QPushButton(self)
            #btn_close.setIcon(QIcon('stop.png'))
            #btn_close.setIconSize(QSize(10, 10))
            btn_close.setFixedHeight(12)
            btn_close.setFixedWidth(12)
            #btn_close.setFlat(True)
            btn_close.clicked.connect(self.on_close_preferences)
            self.tab.tabBar().setTabButton(index_page, QTabBar.RightSide,
                                           btn_close)
            #
            last_index = self.tab.count() - 1
            self.tab.setCurrentIndex(last_index)

    def on_close_preferences(self):
        index_page = self.tab.indexOf(self.preferences)
        if index_page >= 0:
            self.tab.removeTab(index_page)
        #self.tab.setCurrentIndex(0)

    def on_about(self):
        about = About(self)

    def on_tab_switch(self, index):
        current_widget = self.tab.currentWidget()
        if current_widget == self.tab_log:
            self.log.on_load()
        elif current_widget in self.addon_tab_widgets:
            tab = current_widget.layout()
            tab.on_load()

        if self.previous_tab == self.preferences:
            self.previous_tab.on_close()
        elif self.previous_tab in self.addon_tab_widgets:
            tab = self.previous_tab.layout()
            tab.on_close()
        self.previous_tab = current_widget

    def show_or_hide_tray(self):
        if self.tray.is_available() and conf.get_tray_available():
            self.tray.show()
        else:
            self.tray.hide()

    def load_addon_tabs(self):
        for tab, addon in [(addon.get_tab(), addon)
                           for addon in self.addons_list]:
            if tab is not None:
                tab_widget = QWidget()
                tab_widget.setLayout(tab)
                self.tab.addTab(tab_widget, addon.name)
                self.addon_tab_widgets.append(tab_widget)

    def load_session(self):
        """"""
        download_items = api.load_session()
        for download_item in download_items:
            self.downloads.store_item(download_item)

    def save_session(self):
        """"""
        id_item_list = [row[0] for row in self.downloads.items]
        api.save_session(id_item_list)

    def idle_timeout(self, interval, func):
        timer = QTimer()
        timer.timeout.connect(func)
        timer.start(interval)
        return timer

    def event_close(self):
        self.tray.hide()
        self.close()

    def closeEvent(self, event):
        # overridden
        if not self.tray.isVisible():
            x, y, w, h = self.geometry().getRect()
            self.hide()
            self.save_session()
            self.preferences.on_close()
            self.dispatcher.stop()
            conf.set_window_settings(x, y, w, h)
            conf.save()
            accounts_manager.save()
            event.accept()
        else:  # hide only
            self.hide()
            event.ignore()
Exemplo n.º 27
0
class MainWindow(KXmlGuiWindow, Ui_MainWindow):
    def __init__(self, app = None):
        KXmlGuiWindow.__init__(self, None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(KIcon(":/data/package-manager.png"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)

    def connectMainSignals(self):
        self.cw.connectMainSignals()
        self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab),self),
                SIGNAL("activated()"), lambda: self.moveTab('next'))
        self.connect(QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Tab),self),
                SIGNAL("activated()"), lambda: self.moveTab('prev'))
        self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F),self),
                SIGNAL("activated()"), self.cw.searchLine.setFocus)
        self.connect(QShortcut(QKeySequence(Qt.Key_F3),self),
                SIGNAL("activated()"), self.cw.searchLine.setFocus)

        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.cw.initialize)
        self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"), self.cw.updateSettings)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged)
        self.connect(self.cw.state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu)
        self.connect(self.cw, SIGNAL("repositoriesUpdated()"), self.tray.updateTrayUnread)
        self.connect(KApplication.kApplication(), SIGNAL("shutDown()"), self.slotQuit)

    def moveTab(self, direction):
        new_index = self.cw.stateTab.currentIndex() - 1
        if direction == 'next':
            new_index = self.cw.stateTab.currentIndex() + 1
        if new_index not in range(self.cw.stateTab.count()):
            new_index = 0
        self.cw.stateTab.setCurrentIndex(new_index)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.trayAction)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("operationCancelled()"), self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("started(QString)"), self.tray.animate)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)

        self.cw.switchState(StateManager.UPGRADE)

        KApplication.kApplication().updateUserTimestamp()

        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            self.tray.showPopup()
        if self.tray.isActive() and operation in ["System.Manager.updatePackage",
                                                  "System.Manager.installPackage",
                                                  "System.Manager.removePackage"]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.cw.mainLayout.insertWidget(0, self.busy)
        self.statusBar().addPermanentWidget(self.cw.actions, 1)
        self.statusBar().show()

        self.updateStatusBar('')

        self.connect(self.cw, SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar)
        self.connect(self.cw, SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.toolBar().setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        KStandardAction.quit(KApplication.kApplication().quit, self.actionCollection())
        KStandardAction.preferences(self.settingsDialog.show, self.actionCollection())
        self.setupGUI(KXmlGuiWindow.Default, "/usr/share/kde4/apps/package-manager/data/packagemanagerui.rc")
        self.initializeOperationActions()

    def initializeOperationActions(self):
        actionGroup = QtGui.QActionGroup(self)

        self.showAllAction = KToggleAction(KIcon("applications-other"), i18n("All Packages"), self)
        self.actionCollection().addAction("showAllAction", self.showAllAction)
        self.connect(self.showAllAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.ALL))
        self.cw.stateTab.addTab(QWidget(), KIcon("applications-other"), i18n("All Packages"))
        actionGroup.addAction(self.showAllAction)

        self.showInstallAction = KToggleAction(KIcon("list-add"), i18n("Installable Packages"), self)
        self.actionCollection().addAction("showInstallAction", self.showInstallAction)
        self.connect(self.showInstallAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.INSTALL))
        self.cw.stateTab.addTab(QWidget(), KIcon("list-add"), i18n("Installable Packages"))
        actionGroup.addAction(self.showInstallAction)

        self.showRemoveAction = KToggleAction(KIcon("list-remove"), i18n("Installed Packages"), self)
        self.actionCollection().addAction("showRemoveAction", self.showRemoveAction)
        self.connect(self.showRemoveAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.REMOVE))
        self.cw.stateTab.addTab(QWidget(), KIcon("list-remove"), i18n("Installed Packages"))
        actionGroup.addAction(self.showRemoveAction)

        self.showUpgradeAction = KToggleAction(KIcon("system-software-update"), i18n("Updates"), self)
        self.actionCollection().addAction("showUpgradeAction", self.showUpgradeAction)
        self.connect(self.showUpgradeAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.UPGRADE))
        self.cw.stateTab.addTab(QWidget(), KIcon("system-software-update"), i18n("Updates"))
        actionGroup.addAction(self.showUpgradeAction)

        # self.showHistoryAction = KToggleAction(KIcon("view-refresh"), i18n("History"), self)
        # self.actionCollection().addAction("showHistoryAction", self.showHistoryAction)
        # self.connect(self.showHistoryAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.HISTORY))
        # self.cw.stateTab.addTab(QWidget(), KIcon("view-refresh"), i18n("History"))
        # actionGroup.addAction(self.showHistoryAction)

        self.cw.menuButton.setMenu(QMenu('MainMenu', self.cw.menuButton))
        self.cw.menuButton.setIcon(KIcon('preferences-other'))
        self.cw.menuButton.menu().clear()

        self.cw.contentHistory.hide()

        # self.cw.menuButton.menu().addAction(self.showAllAction)
        # self.cw.menuButton.menu().addAction(self.showInstallAction)
        # self.cw.menuButton.menu().addAction(self.showRemoveAction)
        # self.cw.menuButton.menu().addAction(self.showUpgradeAction)
        # self.cw.menuButton.menu().addSeparator()

        self.cw.menuButton.menu().addAction(self.actionCollection().action(KStandardAction.name(KStandardAction.Preferences)))
        self.cw.menuButton.menu().addAction(self.actionCollection().action(KStandardAction.name(KStandardAction.Help)))
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionCollection().action(KStandardAction.name(KStandardAction.AboutApp)))
        self.cw.menuButton.menu().addAction(self.actionCollection().action(KStandardAction.name(KStandardAction.AboutKDE)))
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionCollection().action(KStandardAction.name(KStandardAction.Quit)))

        self.cw._states = {self.cw.state.ALL    :(0, self.showAllAction),
                           self.cw.state.INSTALL:(1, self.showInstallAction),
                           self.cw.state.REMOVE :(2, self.showRemoveAction),
                           self.cw.state.UPGRADE:(3, self.showUpgradeAction)}
        #                  self.cw.state.HISTORY:(4, self.showHistoryAction)}

        self.showAllAction.setChecked(True)
        self.cw.checkUpdatesButton.hide()
        self.cw.checkUpdatesButton.setIcon(KIcon('view-refresh'))
        self.cw.showBasketButton.clicked.connect(self.cw.showBasket)

        # Little time left for the new ui
        self.menuBar().setVisible(False)
        self.cw.switchState(self.cw.state.ALL)

    def statusWaiting(self):
        self.updateStatusBar(i18n('Calculating dependencies...'), busy = True)

    def updateStatusBar(self, text, busy = False):
        if text == '':
            text = i18n("Currently your basket is empty.")
            self.busy.hide()
            self.cw.showBasketButton.hide()
        else:
            self.cw.showBasketButton.show()

        if busy:
            self.busy.busy()
            self.cw.showBasketButton.hide()
        else:
            self.busy.hide()

        self.cw.statusLabel.setText(text)

    def queryClose(self):
        if config.PMConfig().systemTray() and not KApplication.kApplication().sessionSaving():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray:
                del self.tray.notification
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
Exemplo n.º 28
0
 def initializeTray(self):
     self.tray = Tray(self, self.iface)
     self.connect(self.centralWidget().operation, SIGNAL("finished(QString)"), self.trayAction)
     self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)
Exemplo n.º 29
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, app=None):
        QMainWindow.__init__(self, None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(QIcon(":/data/package-manager.png"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)

    def connectMainSignals(self):
        self.cw.connectMainSignals()
        self.connect(
            QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab), self), SIGNAL("activated()"), lambda: self.moveTab("next")
        )
        self.connect(
            QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Tab), self),
            SIGNAL("activated()"),
            lambda: self.moveTab("prev"),
        )
        self.connect(
            QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F), self), SIGNAL("activated()"), self.cw.searchLine.setFocus
        )
        self.connect(QShortcut(QKeySequence(Qt.Key_F3), self), SIGNAL("activated()"), self.cw.searchLine.setFocus)

        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.cw.initialize)
        self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"), self.cw.updateSettings)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged)
        self.connect(self.cw.state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu)
        self.connect(self.cw, SIGNAL("repositoriesUpdated()"), self.tray.updateTrayUnread)
        self.connect(qApp, SIGNAL("shutDown()"), self.slotQuit)

    def moveTab(self, direction):
        new_index = self.cw.stateTab.currentIndex() - 1
        if direction == "next":
            new_index = self.cw.stateTab.currentIndex() + 1
        if new_index not in range(self.cw.stateTab.count()):
            new_index = 0
        self.cw.stateTab.setCurrentIndex(new_index)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.trayAction)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("operationCancelled()"), self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("started(QString)"), self.tray.animate)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)

        self.cw.switchState(StateManager.UPGRADE)

        KApplication.kApplication().updateUserTimestamp()

        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in [
            "System.Manager.updateRepository",
            "System.Manager.updateAllRepositories",
        ]:
            self.tray.showPopup()
        if self.tray.isVisible() and operation in [
            "System.Manager.updatePackage",
            "System.Manager.installPackage",
            "System.Manager.removePackage",
        ]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.cw.mainLayout.insertWidget(0, self.busy)
        self.statusBar().addPermanentWidget(self.cw.actions, 1)
        self.statusBar().show()

        self.updateStatusBar("")

        self.connect(self.cw, SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar)
        self.connect(self.cw, SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.initializeOperationActions()

    def initializeOperationActions(self):

        self.showAllAction = QAction(KIcon(("applications-other", "package_applications")), i18n("All Packages"), self)
        self.connect(self.showAllAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.ALL))
        self.cw.stateTab.addTab(QWidget(), KIcon(("applications-other", "package_applications")), i18n("All Packages"))

        self.showInstallAction = QAction(KIcon(("list-add", "add")), i18n("Installable Packages"), self)
        self.connect(self.showInstallAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.INSTALL))
        self.cw.stateTab.addTab(QWidget(), KIcon(("list-add", "add")), i18n("Installable Packages"))

        self.showRemoveAction = QAction(KIcon(("list-remove", "remove")), i18n("Installed Packages"), self)
        self.connect(self.showRemoveAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.REMOVE))
        self.cw.stateTab.addTab(QWidget(), KIcon(("list-remove", "remove")), i18n("Installed Packages"))

        self.showUpgradeAction = QAction(KIcon(("system-software-update", "gear")), i18n("Updates"), self)
        self.connect(self.showUpgradeAction, SIGNAL("triggered()"), lambda: self.cw.switchState(StateManager.UPGRADE))
        self.cw.stateTab.addTab(QWidget(), KIcon(("system-software-update", "gear")), i18n("Updates"))

        self.showPreferences = QAction(KIcon(("preferences-system", "package_settings")), i18n("Settings"), self)
        self.connect(self.showPreferences, SIGNAL("triggered()"), self.settingsDialog.show)

        self.actionQuit = QAction(KIcon("exit"), i18n("Quit"), self)
        self.actionQuit.setShortcuts(QKeySequence.Quit)
        self.connect(self.actionQuit, SIGNAL("triggered()"), qApp.exit)

        self.cw.menuButton.setMenu(QMenu("MainMenu", self.cw.menuButton))
        self.cw.menuButton.setIcon(KIcon(("preferences-system", "package_settings")))
        self.cw.menuButton.menu().clear()

        self.cw.contentHistory.hide()

        self.cw.menuButton.menu().addAction(self.showPreferences)
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionQuit)

        self.cw._states = {
            self.cw.state.ALL: (0, self.showAllAction),
            self.cw.state.INSTALL: (1, self.showInstallAction),
            self.cw.state.REMOVE: (2, self.showRemoveAction),
            self.cw.state.UPGRADE: (3, self.showUpgradeAction),
        }

        self.showAllAction.setChecked(True)
        self.cw.checkUpdatesButton.hide()
        self.cw.checkUpdatesButton.setIcon(KIcon(("view-refresh", "reload")))
        self.cw.showBasketButton.clicked.connect(self.cw.showBasket)

        # Little time left for the new ui
        self.menuBar().setVisible(False)
        self.cw.switchState(self.cw.state.ALL)

    def statusWaiting(self):
        self.updateStatusBar(i18n("Calculating dependencies..."), busy=True)

    def updateStatusBar(self, text, busy=False):
        if text == "":
            text = i18n("Currently your basket is empty.")
            self.busy.hide()
            self.cw.showBasketButton.hide()
        else:
            self.cw.showBasketButton.show()

        if busy:
            self.busy.busy()
            self.cw.showBasketButton.hide()
        else:
            self.busy.hide()

        self.cw.statusLabel.setText(text)
        self.cw.statusLabel.setToolTip(text)

    def queryClose(self):
        if config.PMConfig().systemTray():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray:
                del self.tray.notification
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
Exemplo n.º 30
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, app=None):
        QMainWindow.__init__(self, None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(QIcon(":/data/package-manager.png"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)

    activated = pyqtSignal()

    def connectMainSignals(self):
        self.cw.connectMainSignals()
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab),
                  self).activated.connect(lambda: self.moveTab('next'))
        QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Tab),
                  self).activated.connect(lambda: self.moveTab('prev'))
        QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F),
                  self).activated.connect(self.cw.searchLine.setFocus)
        QShortcut(QKeySequence(Qt.Key_F3),
                  self).activated.connect(self.cw.searchLine.setFocus)

        self.settingsDialog.packagesChanged.connect(self.cw.initialize)
        self.settingsDialog.packageViewChanged.connect(self.cw.updateSettings)
        self.settingsDialog.traySettingChanged.connect(
            self.tray.settingsChanged)
        self.cw.state.repositoriesChanged.connect(
            self.tray.populateRepositoryMenu)
        self.cw.repositoriesUpdated.connect(self.tray.updateTrayUnread)
        qApp.shutDown.connect(self.slotQuit)

    def moveTab(self, direction):
        new_index = self.cw.stateTab.currentIndex() - 1
        if direction == 'next':
            new_index = self.cw.stateTab.currentIndex() + 1
        if new_index not in range(self.cw.stateTab.count()):
            new_index = 0
        self.cw.stateTab.setCurrentIndex(new_index)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.cw.operation.finished.connect(self.trayAction)
        self.cw.operation.finished.connect(self.tray.stop)
        self.cw.operation.operationCancelled.connect(self.tray.stop)
        self.cw.operation.started.connect(self.tray.animate)
        self.tray.showUpdatesSelected.connect(self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)

        self.cw.switchState(StateManager.UPGRADE)

        KApplication.kApplication().updateUserTimestamp()

        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in [
                "System.Manager.updateRepository",
                "System.Manager.updateAllRepositories"
        ]:
            self.tray.showPopup()
        if self.tray.isVisible() and operation in [
                "System.Manager.updatePackage",
                "System.Manager.installPackage", "System.Manager.removePackage"
        ]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.cw.mainLayout.insertWidget(0, self.busy)
        self.statusBar().addPermanentWidget(self.cw.actions, 1)
        self.statusBar().show()

        self.updateStatusBar('')

        self.cw.selectionStatusChanged.connect(self.updateStatusBar)
        self.cw.updatingStatus.connect(self.statusWaiting)

    def initializeActions(self):
        self.initializeOperationActions()

    def initializeOperationActions(self):

        self.showAllAction = QAction(
            KIcon(("applications-other", "package_applications")),
            self.tr("All Packages"), self)
        self.showAllAction.triggered.connect(
            lambda: self.cw.switchState(StateManager.ALL))
        self.cw.stateTab.addTab(
            QWidget(), KIcon(("applications-other", "package_applications")),
            self.tr("All Packages"))

        self.showInstallAction = QAction(KIcon(("list-add", "add")),
                                         self.tr("Installable Packages"), self)
        self.showInstallAction.triggered.connect(
            lambda: self.cw.switchState(StateManager.INSTALL))
        self.cw.stateTab.addTab(QWidget(), KIcon(("list-add", "add")),
                                self.tr("Installable Packages"))

        self.showRemoveAction = QAction(KIcon(("list-remove", "remove")),
                                        self.tr("Installed Packages"), self)
        self.showRemoveAction.triggered.connect(
            lambda: self.cw.switchState(StateManager.REMOVE))
        self.cw.stateTab.addTab(QWidget(), KIcon(("list-remove", "remove")),
                                self.tr("Installed Packages"))

        self.showUpgradeAction = QAction(
            KIcon(("system-software-update", "gear")), self.tr("Updates"),
            self)
        self.showUpgradeAction.triggered.connect(
            lambda: self.cw.switchState(StateManager.UPGRADE))
        self.cw.stateTab.addTab(QWidget(),
                                KIcon(("system-software-update", "gear")),
                                self.tr("Updates"))

        self.showPreferences = QAction(
            KIcon(("preferences-system", "package_settings")),
            self.tr("Settings"), self)
        self.showPreferences.triggered.connect(self.settingsDialog.show)

        self.actionHelp = QAction(KIcon("help"), self.tr("Help"), self)
        self.actionHelp.setShortcuts(QKeySequence.HelpContents)
        self.actionHelp.triggered.connect(self.showHelp)

        self.actionQuit = QAction(KIcon("exit"), self.tr("Quit"), self)
        self.actionQuit.setShortcuts(QKeySequence.Quit)
        self.actionQuit.triggered.connect(qApp.exit)

        self.cw.menuButton.setMenu(QMenu('MainMenu', self.cw.menuButton))
        self.cw.menuButton.setIcon(
            KIcon(("preferences-system", "package_settings")))
        self.cw.menuButton.menu().clear()

        self.cw.contentHistory.hide()

        self.cw.menuButton.menu().addAction(self.showPreferences)
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionHelp)
        self.cw.menuButton.menu().addAction(self.actionQuit)

        self.cw._states = {
            self.cw.state.ALL: (0, self.showAllAction),
            self.cw.state.INSTALL: (1, self.showInstallAction),
            self.cw.state.REMOVE: (2, self.showRemoveAction),
            self.cw.state.UPGRADE: (3, self.showUpgradeAction)
        }

        self.showAllAction.setChecked(True)
        self.cw.checkUpdatesButton.hide()
        self.cw.checkUpdatesButton.setIcon(KIcon(("view-refresh", "reload")))
        self.cw.showBasketButton.clicked.connect(self.cw.showBasket)

        # Little time left for the new ui
        self.menuBar().setVisible(False)
        self.cw.switchState(self.cw.state.ALL)

    def statusWaiting(self):
        self.updateStatusBar(self.tr('Calculating dependencies...'), busy=True)

    def showHelp(self):
        self.Pds = pds.Pds()
        self.lang = localedata.setSystemLocale(justGet=True)

        if self.lang in os.listdir("/usr/share/package-manager/help"):
            pass
        else:
            self.lang = "en"

        if self.Pds.session == pds.Kde3:
            os.popen(
                "khelpcenter /usr/share/package-manager/help/%s/main_help.html"
                % (self.lang))
        else:
            helpdialog.HelpDialog(self, helpdialog.MAINAPP)

    def updateStatusBar(self, text, busy=False):
        if text == '':
            text = self.tr("Currently your basket is empty.")
            self.busy.hide()
            self.cw.showBasketButton.hide()
        else:
            self.cw.showBasketButton.show()

        if busy:
            self.busy.busy()
            self.cw.showBasketButton.hide()
        else:
            self.busy.hide()

        self.cw.statusLabel.setText(text)
        self.cw.statusLabel.setToolTip(text)

    def queryClose(self):
        if config.PMConfig().systemTray():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray:
                del self.tray.notification
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
Exemplo n.º 31
0
    def __init__(self):
        QMainWindow.__init__(self)

        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(
            QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()

        self.restore_wnd_geometry()

        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM),
                     _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM),
                      _('Start Download'), self.on_start_download, False)
        accounts = (QToolButton(), media.get_icon(media.ACCOUNTS,
                                                  media.MEDIUM), _('Accounts'),
                    self.on_accounts, True)
        preferences = (QToolButton(),
                       media.get_icon(media.PREFERENCES, media.MEDIUM),
                       _('Preferences'), self.on_preferences, True)
        about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM),
                 _('About'), self.on_about, True)

        self.menu = QMenu()
        preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        preferences[BTN].setMenu(self.menu)

        toolbar = Toolbar(
            self,
            [self.start, self.stop, None, accounts, preferences, None, about])

        self.toolbar = self.addToolBar(toolbar)

        #self.vbox = QVBoxLayout(self)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget(self)
        #
        self.downloads = Downloads(self)
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.add_downloads = AddDownloads(self.downloads, self)
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.log = Log()
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list, self)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        if self.tray.available:
            self.can_close = False
        else:
            self.can_close = True

        #on select button state
        self.downloads.selectionModel().selectionChanged.connect(
            self.on_selected)

        #load session.
        self.load_session()

        #add core's event loop
        self.idle_timeout(500, self.queue_loop)

        #quit event
        events.connect(cons.EVENT_QUIT, self.event_close)

        self.show()
Exemplo n.º 32
0
    if os.path.isfile(qtconf):
        os.remove(qtconf)
    qtconf_file = open(qtconf, mode='w')
    qtconf_file.write('[Paths]\n')
    qtconf_file.write('Prefix = ' + pyqt4dir + '\n')
    qtconf_file.write('Binaries = ' + pyqt4dir + '\n')
    qtconf_file.close()

from cgrupyqt import QtGui

import cgruconfig
import cmd
from refresh import Refresh
from tray import Tray
from server import Server

# Define keeper launch command if was not:
keeper_cmd = os.getenv('CGRU_KEEPER_CMD')
if keeper_cmd is None:
    keeper_cmd = '"%s" "%s"' % (os.getenv('CGRU_PYTHONEXE'), sys.argv[0])
cgruconfig.VARS['CGRU_KEEPER_CMD'] = keeper_cmd

# Create tray application with refresh:
app = QtGui.QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
cmd.Application = app
cmd.Tray = Tray(app)
refresh = Refresh(app)
server = Server(app)
app.exec_()
Exemplo n.º 33
0
from fetcher import Fetcher
from preferences import Preferences
from tray import Tray

app = QApplication([])

ICON_PATH = f"{path.abspath(path.curdir)}/icon.png"
# Create the icon
icon = QIcon(ICON_PATH)

app.setQuitOnLastWindowClosed(False)

# Create the tray
settings = Preferences()
tray = Tray(icon, settings)
fetcher = Fetcher(settings)
# tray.activated.connect(lambda ev: print(ev))
timer = QTimer()
timer.setSingleShot(False)
timer.setInterval(60 * 1000)


def notify_time(time, delay=None):
    if not delay:
        command = f"notify-send -i {ICON_PATH} '{time}'"
    else:
        command = f"notify-send -i {ICON_PATH} 'Le métro de {time} part dans {delay} minutes'"
    system(command)