Ejemplo n.º 1
0
    class Tray(KSystemTrayIcon, PTray):
        def __init__(self, parent, iface):
            KSystemTrayIcon.__init__(self, parent)
            self.appWindow = parent
            PTray.__init__(self, iface)

        def initializePopup(self):
            self.setIcon(self.defaultIcon)
            self.actionMenu = KActionMenu(i18n("Update"), self)
            self.populateRepositoryMenu()
            self.contextMenu().addAction(self.actionMenu)
            self.contextMenu().addSeparator()

        def populateRepositoryMenu(self):
            self.actionMenu.menu().clear()
            for name, address in self.iface.getRepositories():
                self._addAction(name, self.actionMenu)
            self._addAction(i18n("All"), self.actionMenu)

        def showPopup(self):
            if self._ready_to_popup():
                if self.notification:
                    del self.notification
                self.notification = KNotification("Updates")
                self.notification.setText(i18n("There are <b>%1</b> updates available!", self.unread))
                self.notification.setActions(QStringList((i18n("Show Updates"), i18n("Ignore"))))
                self.notification.setFlags(KNotification.Persistent)
                self.notification.setComponentData(KComponentData("package-manager","package-manager"))
                self.connect(self.notification, SIGNAL("action1Activated()"), lambda:self.emit(SIGNAL("showUpdatesSelected()")))
                self.notification.sendEvent()
Ejemplo n.º 2
0
 def notify(self, strType, msg=""):
     KNotification.event(strType,
         msg,
         QPixmap(), #self.icon.pixmap(QSize(22,22)), #KIcon("google-translator").pixmap(QSize(22,22))
         None,
         KNotification.CloseOnTimeout,
         KComponentData(str(self.applet.metadata.pluginName()), str(self.applet.metadata.pluginName()), KComponentData.SkipMainComponentRegistration)
         )
Ejemplo n.º 3
0
 def notifyFinished(self):
     if not self.operation.totalPackages:
         return
     KNotification.event("Summary",
             self.state.getSummaryInfo(self.operation.totalPackages, self.operation.extraPackages),
             QPixmap(),
             None,
             KNotification.CloseOnTimeout,
             KComponentData("package-manager", "package-manager", KComponentData.SkipMainComponentRegistration))
Ejemplo n.º 4
0
 def notifyFinished(self):
     if not self.operation.totalPackages:
         return
     KNotification.event("Summary",
             self.state.getSummaryInfo(self.operation.totalPackages, self.operation.extraPackages),
             QPixmap(),
             None,
             KNotification.CloseOnTimeout,
             KComponentData("package-manager", "package-manager", KComponentData.SkipMainComponentRegistration))
Ejemplo n.º 5
0
 def createNotify(self, content):
     """function to create notification for label"""
     notification = KNotification(content[0])
     notification.setComponentData(KComponentData("plasma_applet_pytextmonitor"))
     notification.setTitle("PyTextMonitor info ::: " + content[0]);
     notification.setText(content[1]);
     notification.sendEvent();
Ejemplo n.º 6
0
 def __handleReply(self, reply) :
     self.activeQuery = ""
     
     if reply.error() != QNetworkReply.NoError :
         print(">>>>>>>> ERROR! : Network Error (" + reply.errorString() + ")")
         self.__notifications = -1
         self.queryFailed.emit()
         return
         
     doc = QDomDocument()
     doc.setContent(reply)
     root = doc.documentElement()
     
     if root.tagName() == "error_response" :
         print(">>>>>>>> ERROR! : Facebook Server Returned Error ")
         err = root.firstChildElement("error_code").text()
         if int(err) == 190 :
             self.queryFailed.emit()
             self.__notifications = -1
             self.authExpired.emit()
         print("\tError Code : " + err)
         print("\tError Message : " + root.firstChildElement("error_msg").text())
         
     elif root.tagName() == "fql_query_response" :           
         notificationList = root.elementsByTagName("notification")
         print("== Recived Query Result ==")
         print("\tTotal Notifications : " + str(notificationList.length()))
         
         for i in range(notificationList.length()) :
             notification = notificationList.at(i)
             print(unicode(notification.namedItem("title_html").toElement().text()))
             
             children = notification.namedItem("title_html").toElement().childNodes()
             print("title has " + str(children.length()) + " children")
             
             for j in range(children.length()) :
                 print(notification.nodeType())
                 print(children.at(j).nodeName())
                 
             if (int(notification.namedItem("anon").toElement().text()) - int(notification.namedItem("created_time").toElement().text())) <= self.settings["pollinterval"] :
                 print("\tNotification " + str(i) + " is New! Firing KNotification::event()")
                 
                 icon = QPixmap(self.settings["notification_icon"])
                 text = self.settings["notification_title"]
                 text.replace("%title_html%", notification.namedItem("title_html").toElement().text())
                 
                 KNotification.event(KNotification.Notification, "Facebook", text, icon)
             
     else :
         print(">>>>>>>> ERROR! : Facebook Server returned Unexpected Output : ")
         print(doc.toByteArray())
         
     if notificationList.length() != self.__notifications :
         self.__notifications = notificationList.length()
         self.notificationsChanged.emit()
Ejemplo n.º 7
0
 def createNotify(self, content):
     """function to create notification for label"""
     if self.debug: qDebug("[PTM] [ptmnotify.py] [createNotify]")
     if self.debug: qDebug("[PTM] [ptmnotify.py] [createNotify] : Run function with content '%s'" %(content))
     notification = KNotification(content[0])
     notification.setComponentData(KComponentData("plasma_applet_pytextmonitor"))
     notification.setTitle("PyTextMonitor info ::: " + content[0]);
     notification.setText(content[1]);
     notification.sendEvent();
Ejemplo n.º 8
0
 def notify_touchpad_state(self, is_off=None):
     if is_off is None:
         is_off = self.touchpad.off
     # show a notification
     if is_off:
         event_id = 'touchpadOff'
         text = i18nc('touchpad switched notification',
                      'Touchpad switched off')
     else:
         event_id = 'touchpadOn'
         text = i18nc('touchpad switched notification',
                      'Touchpad switched on')
     icon = KIconLoader.global_().loadIcon('synaptiks', KIconLoader.Panel)
     KNotification.event(event_id, text, icon)
Ejemplo n.º 9
0
 def showPopup(self):
     if self._ready_to_popup():
         if self.notification:
             del self.notification
         self.notification = KNotification("Updates")
         self.notification.setText(
             i18n("There are <b>%1</b> updates available!", self.unread))
         self.notification.setActions(
             QStringList((i18n("Show Updates"), i18n("Ignore"))))
         self.notification.setFlags(KNotification.Persistent)
         self.notification.setComponentData(
             KComponentData("package-manager", "package-manager"))
         self.connect(self.notification, SIGNAL("action1Activated()"),
                      lambda: self.emit(SIGNAL("showUpdatesSelected()")))
         self.notification.sendEvent()
Ejemplo n.º 10
0
 def notifyFinished(self):
     if not self.operation.totalPackages:
         return
     if self.state.silence:
         Pds.notify(i18n('Package Manager'), self.state.getSummaryInfo(self.operation.totalPackages))
     elif Pds.session == pds.Kde4:
         from PyKDE4.kdeui import KNotification
         from PyKDE4.kdecore import KComponentData
         KNotification.event("Summary",
                 self.state.getSummaryInfo(self.operation.totalPackages),
                 QtGui.QPixmap(),
                 None,
                 KNotification.CloseOnTimeout,
                 KComponentData("package-manager", "package-manager", KComponentData.SkipMainComponentRegistration)
                 )
     else:
         Pds.notify(i18n('Package Manager'), self.state.getSummaryInfo(self.operation.totalPackages))
Ejemplo n.º 11
0
 def showPopup(self):
     if self._ready_to_popup():
         if self.notification:
             del self.notification
         self.notification = KNotification("Updates")
         self.notification.setText(i18n("There are <b>%1</b> updates available!", self.unread))
         self.notification.setActions(QStringList((i18n("Show Updates"), i18n("Ignore"))))
         self.notification.setFlags(KNotification.Persistent)
         self.notification.setComponentData(KComponentData("package-manager","package-manager"))
         self.connect(self.notification, SIGNAL("action1Activated()"), lambda:self.emit(SIGNAL("showUpdatesSelected()")))
         self.notification.sendEvent()
Ejemplo n.º 12
0
	def notification(self, msg):
		if self.Settings.value('Notify', True).toBool() :
			saveNotify	=	KNotification.event(KNotification.Notification, \
						QString('<b>ALSA Volume Control</b>'), \
						QString(msg), \
						self._icon.pixmap(QSize(64, 64)), \
						None, \
						KNotification.CloseOnTimeout)
			saveNotify.setActions( QStringList() << "Don't tell anymore" )
			saveNotify.activated['unsigned int'].connect(self.dontTellAnymore)
			saveNotify.sendEvent()
Ejemplo n.º 13
0
class Tray(KStatusNotifierItem, PTray):
    def __init__(self, parent, iface):
        KSystemTrayIcon.__init__(self, parent)
        self.appWindow = parent
        self.setAssociatedWidget(parent)
        PTray.__init__(self, iface)

    def initializePopup(self):
        self.setIconByPixmap(self.defaultIcon)
        self.actionMenu = KActionMenu(i18n("Update"), self)
        self.populateRepositoryMenu()
        self.contextMenu().addAction(self.actionMenu)
        self.contextMenu().addSeparator()

    def populateRepositoryMenu(self):
        self.actionMenu.menu().clear()
        has_repo = False
        for name, address in self.iface.getRepositories(only_active=True):
            self._addAction(name, self.actionMenu)
            has_repo = True
        if has_repo:
            self._addAction(i18n("All"), self.actionMenu)

    def showPopup(self):
        if self._ready_to_popup():
            if self.notification:
                del self.notification
            self.notification = KNotification("Updates")
            self.notification.setText(
                i18n("There are <b>%1</b> updates available!", self.unread))
            self.notification.setActions(
                QStringList((i18n("Show Updates"), i18n("Ignore"))))
            self.notification.setFlags(KNotification.Persistent)
            self.notification.setComponentData(
                KComponentData("package-manager", "package-manager"))
            self.connect(self.notification, SIGNAL("action1Activated()"),
                         lambda: self.emit(SIGNAL("showUpdatesSelected()")))
            self.notification.sendEvent()
Ejemplo n.º 14
0
	def showAlarm(self, msgs, sounds, cmds):
		#print msgs, sounds, cmds, 'alarmed'
		playSounds = []
		runCmds = []
		for sound in sounds :
			if not os.path.isfile(sound.toLocal8Bit().data()) :
				sound = QString('/usr/share/sounds/pop.wav')
				#print (sound)
			playSounds.append(QProcess())
			playSounds[len(playSounds)-1].startDetached('/usr/bin/play', QStringList() << sound)
		for cmd in cmds :
			if cmd.isEmpty() : continue
			runCmds.append(QProcess())
			runCmds[len(runCmds)-1].startDetached('/usr/bin/sh', QStringList() << '-c' << cmd)
		for msg in msgs :
			if msg.isEmpty() : continue
			notify = KNotification.event(\
						KNotification.Notification, \
						'Alarm Clock', \
						msg, \
						QPixmap(self.alarmIconPath))
Ejemplo n.º 15
0
class MainWindow (KXmlGuiWindow):
    def __init__ (self, parent=None):
        KXmlGuiWindow.__init__ (self, parent)

        # load the .ui file
        # !!! __file__ can end with .py[co]!
        uipath= __file__[:__file__.rfind ('.')]+'.ui'
        UIMainWindow, _= uic.loadUiType (uipath)

        self.ui= UIMainWindow ()
        self.ui.setupUi (self)
        self.collectionsAwaited= 0

        self.oldSearchText= ''

        self.setupGUI ()

    def connectUi (self, player):
        self.player= player
        self.playlist= player.playlist

        # connect buttons!
        self.ui.prevButton.clicked.connect (self.player.prev)
        # the QPushButton.clicked() emits a bool,
        # and it's False on normal (non-checkable) buttons
        # no, it's not false, it's 0, which is indistinguishable from play(0)
        # so lambda the 'bool' away
        self.ui.playButton.clicked.connect (lambda b: self.player.play ())
        self.ui.pauseButton.clicked.connect (self.player.pause)
        self.ui.stopButton.clicked.connect (self.player.stop)
        self.ui.nextButton.clicked.connect (self.player.next)

        self.ui.randomCheck.setChecked (self.playlist.random)
        self.ui.randomCheck.clicked.connect (self.playlist.toggleRandom)
        self.playlist.randomChanged.connect (self.ui.randomCheck.setChecked)

        self.ui.stopAfterCheck.setChecked (self.player.stopAfter)
        self.ui.stopAfterCheck.clicked.connect (self.player.toggleStopAfter)
        self.player.stopAfterChanged.connect (self.ui.stopAfterCheck.setChecked)

        self.ui.searchEntry.textChanged.connect (self.search)
        majV, minV, patchL= utils.phononVersion ()
        if (majV>4) or (majV==4 and minV>3) or (majV==4 and minV==3 and patchL>1):
            # each second
            self.player.media.setTickInterval (1000);
            self.player.media.tick.connect (self.updateTimes)
            self.ui.seekSlider.setMediaObject (self.player.media)
        # TODO: self.ui.volumeSlider

        # TODO: better name?
        self.appModel= QPlayListModel (collaggr=self.playlist.collaggr, view=self)
        # TODO: connect after the collection has been scanned/populated
        self.appModel.dataChanged.connect (self.copyEditToSelection)
        self.copying= False
        self.setModel (self.appModel)

        self.renamer= Renamer (self.model.collaggr)

        self.playlist.songChanged.connect (self.showSong)
        self.playlist.queued.connect (self.appModel.dirtyRow)
        self.playlist.dequeued.connect (self.appModel.dirtyRow)
        self.ui.songsList.activated.connect (self.changeSong)
        self.player.songChanged.connect (self.nowPlaying)

        # FIXME: kinda hacky
        self.fontMetrics= QFontMetrics (KGlobalSettings.generalFont ())
        for i, w in enumerate (self.model.columnWidths):
            self.ui.songsList.setColumnWidth (i, self.fontMetrics.width (w))
        # this is much much slower!
        # self.ui.songsList.verticalHeader ().setResizeMode (QHeaderView.ResizeToContents)

        # FIXME: temporarily until I resolve the showSong() at boot time
        self.modelIndex= None
        self.songIndexSelectedByUser= None

        actions.create (self, self.actionCollection ())

    def setModel (self, model):
        logger.debug ("complex.setModel():", model)
        self.model= model
        self.ui.songsList.setModel (self.model)
        self.ui.songsList.resizeRowsToContents ()

    def log (self, *args):
        print args

    def showSong (self, index):
        # save the old modelIndex so we can update that row and the new one
        oldModelIndex= self.modelIndex
        if self.songIndexSelectedByUser is None:
            logger.debug ("complex.showSong()", index)
            # we use the playlist model because the index is *always* refering
            # to that model
            song= self.playlist.collaggr.songForIndex (index)
            # we save the new modelIndex in self so we can show it
            # when we come back from searching
            modelIndex= self.modelIndex= self.model.index (index, 0)
        else:
            (song, modelIndex)= self.songIndexSelectedByUser
            # I also have to save it for the same reason
            # but using the other model!
            # BUG: this is getting ugly
            self.modelIndex= self.appModel.index (index, 0)
            # we used it so we discard it
            # it will be set again by changeSong()
            self.songIndexSelectedByUser= None

        # mark data in old song and new song as dirty
        # and let the view update the hightlight
        # FIXME? yes, this could be moved to the model (too many self.appModel's)
        # FIXME: temporarily if'ed until I resolve the showSong() at boot time
        if oldModelIndex is not None:
            self.appModel.dirtyRow (oldModelIndex.row ())
        self.appModel.dirtyRow (self.modelIndex.row ())

        logger.debug ("default.showSong()", song)
        # FIXME? QAbstractItemView.EnsureVisible config?
        self.ui.songsList.scrollTo (modelIndex, QAbstractItemView.PositionAtCenter)
        # move the selection cursor too
        self.ui.songsList.setCurrentIndex (modelIndex)

        # set the window title
        # TODO: also update on tag edition
        self.setCaption (self.playlist.formatSong (song))

    def changeSong (self, modelIndex):
        # FIXME: later we ask for the index... doesn't make sense!
        logger.debug ("default.changeSong()", modelIndex.row ())
        song= self.model.collaggr.songForIndex (modelIndex.row ())
        self.songIndexSelectedByUser= (song, modelIndex)
        self.player.play (song)

    def nowPlaying (self, index):
        logger.debug ("complex.nowPlaying(): %s", self.playlist.formatSong (self.playlist.song))
        # event
        self.notif= KNotification ("nowPlaying", self)
        self.notif.setText ("Now Playing: %s" % self.playlist.formatSong (self.playlist.song))
        self.notif.sendEvent ()

    def scanBegins (self):
        # self.ui.songsList.setEnabled (False)
        # self.ui.songsList.setUpdatesEnabled (False)
        pass

    def scanFinished (self):
        # self.ui.songsList.setEnabled (True)
        # self.ui.songsList.setUpdatesEnabled (True)
        pass

    def search (self, text):
        # TODO: 23:44 < steckmqn> searching w/ the next chr cqn be done only in the qlready found set

        # oST>2 && t>=3 => search
        # (oST>=1 because it can reach that state when the user presses esc)
        # oST>=1 && t==0 => normal
        # otherwise => keep current
        if len (text)>=3 and len (self.oldSearchText)>=2:
            #                            QString->unicode
            songs= self.playlist.search (unicode (text))
            # we have to keep it
            # otherwise it pufs into inexistence after the function ends
            self.setModel (QPlayListModel (songs=songs, view=self))
        elif len (text)==0 and len (self.oldSearchText)>=1:
            self.setModel (self.appModel)
            # ensure the current song is shown
            if self.modelIndex is not None:
                self.showSong (self.modelIndex.row ())
        else:
            # print text, self.oldSearchText
            pass

        self.oldSearchText= text

    def updateTimes (self, tick):
        elapsed= tick/1000 # ms to s
        song= self.appModel.collaggr.songForIndex (self.modelIndex.row ())
        length= int (song.length)
        remaining= elapsed-length
        # print "tick! %d [%d] / %d / %d" % (elapsed, tick, length, remaining)
        
        self.ui.elapsedTime.setText (utils.secondsToTime (elapsed))
        self.ui.remainingTime.setText (utils.secondsToTime (remaining))

    def copyEditToSelection (self, tl, br):
        """copies the outcome of an edition in a cell
        to all the selected cells in the same column which.
        this lets us implement mass tag edition."""
        # print "complex.copyEditToSelection()", len (self.ui.songsList.selectedIndexes ()), self.appModel.edited
        if len (self.ui.songsList.selectedIndexes ())>1 and self.appModel.edited:
            # more than one cell selected
            # we copy was has just been edited tho the rest of selected cells
            logger.debug ("complex.copyEditToSelection()", self.copying)
            if not self.copying:
                self.copying= True
                # data() already returns QVariant
                value= self.appModel.data (tl, Qt.DisplayRole)
                logger.debug ("complex.copyEditToSelection()", value)
                # just copy the column that has been edited...
                column= tl.column ()
                for modelIndex in self.ui.songsList.selectedIndexes ():
                    # ... in the selected cells in the same column
                    if modelIndex.column ()==column:
                        # copy the value
                        self.appModel.setData (modelIndex, value, Qt.EditRole)

                # we finished copying
                self.copying= False

    def collectionAdded (self):
        self.collectionsAwaited+= 1

    def collectionLoaded (self):
        # TODO: locking here, for data race's sake!
        # really? signals get emited from threads,
        # but processed from the main loop, isn't it?
        self.collectionsAwaited-= 1
        if self.collectionsAwaited==0:
            self.showSong (self.playlist.index)

    def selectedSongs (self):
        return [self.model.collaggr.songForIndex (modelIndex.row ())
            for modelIndex in self.ui.songsList.selectedIndexes ()]

    ### actions ###
    def queue (self):
        logger.debug ("complex.queue()")
        # so we don't keep (de)queuing if several cells of the same song are selected
        selectedSongs= []
        for modelIndex in self.ui.songsList.selectedIndexes ():
            logger.debug ("complex.queue()", modelIndex.row ())
            if modelIndex.row () not in selectedSongs:
                # self.playlist.queue (modelIndex.row ())
                # not so fast, cowboy. PlayList.queue() spects 'global' indexes
                # TODO: this is not very efficient
                song= self.model.collaggr.songForIndex (modelIndex.row ())
                index= self.appModel.collaggr.indexForSong (song)
                self.playlist.queue (index)
                selectedSongs.append (modelIndex.row ())

    def rename (self):
        logger.debug ("complex.rename()")
        songs= self.selectedSongs ()

        self.renamer.rename (songs)

    def toggleVA (self):
        logger.debug ("complex.toggleVA()")
        songs= self.selectedSongs ()

    def delete (self):
        # we actually move it to a 'trash' collection
        logger.debug ("complex.delete()")
        songs= self.selectedSongs ()

        self.renamer.delete (songs)

    ### session management ###
    def saveProperties (self, config):
        logger ("saveProperties():")

    def restoreProperties (self, config):
        # not automatically called, add code in main()
        # see http://techbase.kde.org/Development/Tutorials/Session_Management#Add_session_management_support_to_your_main.28.29_function
        logger.debug ("restoreProperties():")

    def queryClose (self):
        logger.debug ("queryClose():")
        # , KApplication.sessionSaving ()
        self.player.quit ()
        self.renamer.saveConfig ()
        return True

    def queryExit (self):
        logger.debug ("queryExit():")
        # , KApplication.sessionSaving ()
        return True
Ejemplo n.º 16
0
 def nowPlaying (self, index):
     logger.debug ("complex.nowPlaying(): %s", self.playlist.formatSong (self.playlist.song))
     # event
     self.notif= KNotification ("nowPlaying", self)
     self.notif.setText ("Now Playing: %s" % self.playlist.formatSong (self.playlist.song))
     self.notif.sendEvent ()
Ejemplo n.º 17
0
        def do_show():
            notification = KNotification("Updates")

            # Keep a reference or the callback of the actions added
            # below will never work.
            # See: https://bugzilla.redhat.com/show_bug.cgi?id=241531
            self.__last_notification = notification

            notification.setFlags(KNotification.CloseOnTimeout)
            notification.setText("<b>%s</b><br/>%s" % (
                title,
                text,
            ))
            if buttons:
                notification.setActions([x[1] for x in buttons])
                notification.connect(notification,
                                     SIGNAL("activated(unsigned int)"),
                                     _action_activate_cb)

            icon_name = "okay"
            status = KStatusNotifierItem.Passive
            if urgency == "critical":
                icon_name = "critical"
                status = KStatusNotifierItem.Active

            name = self.icons.get(icon_name)
            icon = KIcon(name)
            self._window.setStatus(status)

            notification.setPixmap(icon.pixmap(48, 48))
            notification.sendEvent()
            self.last_alert = (title, text)
Ejemplo n.º 18
0
        def do_show():
            notification = KNotification("Updates")

            # Keep a reference or the callback of the actions added
            # below will never work.
            # See: https://bugzilla.redhat.com/show_bug.cgi?id=241531
            self.__last_notification = notification

            notification.setFlags(KNotification.CloseOnTimeout)
            notification.setText("<b>%s</b><br/>%s" % (title, text,))
            if buttons:
                notification.setActions([x[1] for x in buttons])
                notification.connect(
                    notification,
                    SIGNAL("activated(unsigned int)"), _action_activate_cb)

            icon_name = "okay"
            status = KStatusNotifierItem.Passive
            if urgency == "critical":
                icon_name = "critical"
                status = KStatusNotifierItem.Active

            name = self.icons.get(icon_name)
            icon = KIcon(name)
            self._window.setStatus(status)

            notification.setPixmap(icon.pixmap(48, 48))
            notification.sendEvent()
            self.last_alert = (title, text)