コード例 #1
0
ファイル: main.py プロジェクト: afreakk/KDEWidgets
class hwTempApp(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.Square)

        self.setTheme()
        self.setLayout()
        self.startTimer(10000)
        self.resize(100, 50)

    def timerEvent(self, evt):
        setLabel()

    def setTheme(self):
        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

    def setLayout(self):
        global label
        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        label = Plasma.Label(self.applet)
        setLabel()
        self.layout.addItem(label)
        self.applet.setLayout(self.layout)
コード例 #2
0
ファイル: main.py プロジェクト: jonathanverner/qidle
class PythonShellApplet(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)

    def init(self):
        logger.debug("Starting qidle...")
        event_loop = QEventLoop()
        self.factory = InsulatedFactory(event_loop = event_loop)
        self.factory.start()
        self.factory.start_event_loop()

        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        self.editorWidget = Plasma.TextEdit(self.applet)
        self.shell_widget = ShellWidget(self.factory,self.editorWidget.nativeWidget())
        self.shell_widget._disable_completion()
        self.editorWidget.nativeWidget().setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.editorWidget.keyPressEvent = self.shell_widget.console_widget.keyPressEvent
        self.layout.addItem(self.editorWidget)
        self.resize(600,500)
        
    def __del__(self):
        self.shell_widget.quit()
        self.factory.terminate()
コード例 #3
0
class NetMonitor(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.Square)

        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)

        self.monitoring = {}
        self.widgets = {}
        for source in self.connectToEngine():
            label = Plasma.Label(self.applet)
            label.setText("%s:" % source)
            self.layout.addItem(label)
            self.widgets[str(source)] = label
            self.monitoring[str(source)] = {"in": 0, "out": 0}
        self.applet.setLayout(self.layout)

    def connectToEngine(self):
        self.engine = self.dataEngine("net_monitor_data")
        self.sources = self.engine.sources()
        for source in self.sources:
            self.engine.connectSource(source, self, 1000)
        return self.sources

    @pyqtSignature(
        "dataUpdated(const QString &, const Plasma::DataEngine::Data &)")
    def dataUpdated(self, sourceName, data):
        """Got something from data source"""
        iface = str(sourceName)
        if iface not in self.widgets:
            print "Error: data for %s not available yet" % iface
            return
        widget = self.widgets[iface]
        data_in = int(data[QString("data_in")])
        data_out = int(data[QString("data_out")])
        old_data_in = self.monitoring[iface]["in"]
        old_data_out = self.monitoring[iface]["out"]
        if old_data_in == -1:
            speed_in = 0
        else:
            speed_in = data_in - old_data_in
        if old_data_out == -1:
            speed_out = 0
        else:
            speed_out = data_out - old_data_out
        self.monitoring[iface]["in"] = data_in
        self.monitoring[iface]["out"] = data_out
        widget.setText("%s\n\/: %d\n/\: %d" %
                       (sourceName, speed_in, speed_out))

    def paintInterface(self, painter, option, rect):
        painter.save()
        painter.restore()
コード例 #4
0
ファイル: owimageviewer.py プロジェクト: waqarini/orange3
    def __init__(self, pixmap, title="", parentItem=None, **kwargs):
        super().__init__(parentItem, **kwargs)
        self.setFocusPolicy(Qt.StrongFocus)
        self._title = None
        self._size = QSizeF()

        layout = QGraphicsLinearLayout(Qt.Vertical, self)
        layout.setSpacing(2)
        layout.setContentsMargins(5, 5, 5, 5)
        self.setContentsMargins(0, 0, 0, 0)

        self.pixmapWidget = GraphicsPixmapWidget(pixmap, self)
        self.labelWidget = GraphicsTextWidget(title, self)

        layout.addItem(self.pixmapWidget)
        layout.addItem(self.labelWidget)
        layout.addStretch()
        layout.setAlignment(self.pixmapWidget, Qt.AlignCenter)
        layout.setAlignment(self.labelWidget, Qt.AlignHCenter | Qt.AlignBottom)

        self.setLayout(layout)

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        self.setFlag(QGraphicsItem.ItemIsSelectable, True)

        self.setTitle(title)
        self.setTitleWidth(100)
コード例 #5
0
ファイル: owimageviewer.py プロジェクト: TimothyXie/orange3
    def __init__(self, pixmap, title="", parent=None):
        QGraphicsWidget.__init__(self, parent)

        self._title = None
        self._size = QSizeF()

        layout = QGraphicsLinearLayout(Qt.Vertical, self)
        layout.setSpacing(2)
        layout.setContentsMargins(5, 5, 5, 5)
        self.setContentsMargins(0, 0, 0, 0)

        self.pixmapWidget = GraphicsPixmapWidget(pixmap, self)
        self.labelWidget = GraphicsTextWidget(title, self)

        layout.addItem(self.pixmapWidget)
        layout.addItem(self.labelWidget)

        layout.setAlignment(self.pixmapWidget, Qt.AlignCenter)
        layout.setAlignment(self.labelWidget, Qt.AlignHCenter | Qt.AlignBottom)
        self.setLayout(layout)

        self.setSizePolicy(QSizePolicy.MinimumExpanding,
                           QSizePolicy.MinimumExpanding)

        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setTitle(title)
        self.setTitleWidth(100)
コード例 #6
0
    def __init__(self, pixmap, title="", parent=None):
        QGraphicsWidget.__init__(self, parent)

        self._title = None
        self._size = QSizeF()

        layout = QGraphicsLinearLayout(Qt.Vertical, self)
        layout.setSpacing(2)
        layout.setContentsMargins(5, 5, 5, 5)
        self.setContentsMargins(0, 0, 0, 0)

        self.pixmapWidget = GraphicsPixmapWidget(pixmap, self)
        self.labelWidget = GraphicsTextWidget(title, self)

        layout.addItem(self.pixmapWidget)
        layout.addItem(self.labelWidget)

        layout.setAlignment(self.pixmapWidget, Qt.AlignCenter)
        layout.setAlignment(self.labelWidget, Qt.AlignHCenter | Qt.AlignBottom)
        self.setLayout(layout)

        self.setSizePolicy(QSizePolicy.MinimumExpanding,
                           QSizePolicy.MinimumExpanding)

        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setTitle(title)
        self.setTitleWidth(100)
コード例 #7
0
ファイル: main.py プロジェクト: afreakk/KDEWidgets
class hwTempApp(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)

    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.Square)

        self.setTheme()
        self.setLayout()
        self.startTimer(10000)
        self.resize(100,50)
    def timerEvent(self,evt):
        setLabel()
    def setTheme(self):
        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)
    def setLayout(self):
        global label
        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        label = Plasma.Label(self.applet)
        setLabel()
        self.layout.addItem(label)
        self.applet.setLayout(self.layout)
コード例 #8
0
class JBApplet(plasmascript.Applet):
	def __init__(self,parent,args=None):
		plasmascript.Applet.__init__(self,parent)
		
	def init(self):
		self.setHasConfigurationInterface(True)
		self.setAspectRatioMode(Plasma.Rectangle)
		self.theme = Plasma.Svg(self)
		self.theme.setImagePath("widgets/background")
		self.setBackgroundHints(Plasma.Applet.DefaultBackground)
		
		self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)
		label= Plasma.Label(self.applet)
		label.setText("Jupiter Broadcasting")
		self.layout.addItem(label)
		self.applet.setLayout(self.layout)
		self.resize(640, 480)

		app = QApplication(sys.argv)
		web = QWebView()
		web.load(QUrl("http://jb.cdn.scaleengine.net/jw/jwplayer.swf"))
		web.show()

	def CreateApplet(parent):
		return JBApplet(parent)
コード例 #9
0
    def layout_widgets(self):
      # Layout
      if self.grid_layout <> None:
        del self.grid_layout
      self.grid_layout = QGraphicsGridLayout()
      header_layout = QGraphicsLinearLayout()
      header_layout.addItem(self.invert_button)
      header_layout.addItem(self.title_label)
      self.grid_layout.addItem(header_layout, 0, 0, 1, 2)
      #self.grid_layout.addItem(self.collapse_button, 0, 0)
      #self.grid_layout.addItem(self.title_label, 0, 1)
      self.grid_layout.addItem(self.from_label, 1, 0)
      self.grid_layout.addItem(self.currency_from, 1, 1)
      self.grid_layout.addItem(self.to_label, 2, 0)
      self.grid_layout.addItem(self.currency_to, 2, 1)
      self.grid_layout.addItem(self.amount_label, 3, 0)
      self.amount_layout = QGraphicsLinearLayout()
      self.amount_layout.addItem(self.amount)
      self.amount_layout.addItem(self.from_amount_label)
      self.amount_layout.addItem(self.equal_label)
      self.amount_layout.addItem(self.conversion_result)
      self.amount_layout.addItem(self.to_amount_label)
      self.grid_layout.addItem(self.amount_layout, 3, 1)
      self.grid_layout.addItem(self.credits_label, 4, 0, 1, 2)

      self.setLayout(self.grid_layout)
コード例 #10
0
ファイル: main.py プロジェクト: grissiom/plasmoid
class TurnOffScreen(plasmascript.Applet):
	def __init__(self, parent, args = None):
		plasmascript.Applet.__init__(self, parent)

	def init(self):
                #TODO: have a configuration interface to set keybroad shortcut
		#self.setHasConfigurationInterface(True)
		self.setAspectRatioMode(Plasma.ConstrainedSquare)
                self.setBackgroundHints(self.NoBackground)

                self.sessionBus = dbus.SessionBus()
                self.powerdevil = self.sessionBus.get_object('org.freedesktop.PowerManagement',
                                                             '/modules/powerdevil')

                self.icon= Plasma.IconWidget(KIcon('preferences-desktop-screensaver'), '', self.applet)
                if KGlobalSettings.singleClick():
                        self.connect(self.icon, SIGNAL('clicked()'), self.turn_off_screen)
                else:
                        self.connect(self.icon, SIGNAL('doubleClicked()'), self.turn_off_screen)
                self.connect(self, SIGNAL('active()'), self.turn_off_screen)

                self.layout = QGraphicsLinearLayout(self.applet)
                self.layout.setContentsMargins(0, 0, 0, 0)
                self.layout.setSpacing(0)
                self.layout.addItem(self.icon)
                self.setLayout(self.layout)
                self.resize(25, 25)

        #def showConfigurationInterface(self):
        #        self.con_short = KShortcutWidget(None)
        #        self.con_short.show()

        def turn_off_screen(self):
                self.powerdevil.turnOffScreen(dbus_interface='org.kde.PowerDevil')
コード例 #11
0
ファイル: main.py プロジェクト: tadzik/mpdclient
class MPDClient(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)

        self.label = Plasma.Label(self.applet)
        self.label.setWordWrap(False)
        self.layout.addItem(self.label)

        self.mpd = mpd.MPDClient()
        try:
            self.mpd.connect(HOST, PORT)
        except:
            pass

        self.timer = QTimer()
        self.timer.connect(self.timer, SIGNAL("timeout()"), self.timeout)
        self.timer.start(1000)
        self.timeout()

    def timeout(self):
        status = ""
        try:
            status = self.mpd.status()["state"]
        except:
            try:
                self.mpd = mpd.MPDClient()
                self.mpd.connect(HOST, PORT)
            except:
                pass
        if status != "play":
            self.label.setText("Music stopped")
            return

        currentSong = self.mpd.currentsong()
        title = album = artist = ""
        longstr = "<b>"
        str = ""

        try:
            title = currentSong["title"]
        except:
            title = currentSong["file"].split("/")[-1]

        try:
            str = str + currentSong["artist"] + " - " + title
        except:
            str = str + title

        try:
            album = currentSong["album"]
        except:
            pass

        self.label.setText(str.decode("utf-8")[0:50])
コード例 #12
0
ファイル: main.py プロジェクト: eugeni/net_monitor
class NetMonitor(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)

    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.Square)

        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)

        self.monitoring = {}
        self.widgets = {}
        for source in self.connectToEngine():
            label = Plasma.Label(self.applet)
            label.setText("%s:" % source)
            self.layout.addItem(label)
            self.widgets[str(source)] = label
            self.monitoring[str(source)] = {"in": 0, "out": 0}
        self.applet.setLayout(self.layout)

    def connectToEngine(self):
        self.engine = self.dataEngine("net_monitor_data")
        self.sources = self.engine.sources()
        for source in self.sources:
            self.engine.connectSource(source, self, 1000)
        return self.sources

    @pyqtSignature("dataUpdated(const QString &, const Plasma::DataEngine::Data &)")
    def dataUpdated(self, sourceName, data):
        """Got something from data source"""
        iface = str(sourceName)
        if iface not in self.widgets:
            print "Error: data for %s not available yet" % iface
            return
        widget = self.widgets[iface]
        data_in = int(data[QString("data_in")])
        data_out = int(data[QString("data_out")])
        old_data_in = self.monitoring[iface]["in"]
        old_data_out = self.monitoring[iface]["out"]
        if old_data_in == -1:
            speed_in = 0
        else:
            speed_in = data_in - old_data_in
        if old_data_out == -1:
            speed_out = 0
        else:
            speed_out = data_out - old_data_out
        self.monitoring[iface]["in"] = data_in
        self.monitoring[iface]["out"] = data_out
        widget.setText("%s\n\/: %d\n/\: %d" % (sourceName, speed_in, speed_out))

    def paintInterface(self, painter, option, rect):
        painter.save()
        painter.restore()
コード例 #13
0
ファイル: main.py プロジェクト: tmccombs/kountdown
class Kountdown(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)

 
    def init(self):
        self.setHasConfigurationInterface(True)

        self.model = KountdownModel(self.configScheme())
        if self.model.needsConfiguration:
            self.setConfigurationRequired(True)
        else:
            self.setupMainUI()
        self.resize(300,125)



    def setupMainUI(self):
        print 'setup'
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)

        self.setBackgroundHints(Plasma.Applet.TranslucentBackground)

        self.layout = QGraphicsLinearLayout(Qt.Vertical,self.applet)
        self.label = Plasma.Label(self.applet)
        self.label.setText(self.model.message)
        self.label.setStyleSheet('''font-size: 18pt;''')
        self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.layout.addItem(self.label)
        self.applet.setLayout(self.layout)


        self.connectToEngine()
        self.model.messageChanged.connect(self.handleMessageChanged)

    def configChanged(self):
        '''handle changes in configuration'''
        plasmascript.Applet.configChanged(self)
        self.updatedConfig()

    def updatedConfig(self):
        config = self.config()
        if self.configurationRequired() and not self.model.needsConfiguration:
            self.setConfigurationRequired(False)
            self.setupMainUI()
        


    def connectToEngine(self):
        self.timeEngine = self.dataEngine("time")
        self.model.connectToEngine(self.timeEngine)

    def handleMessageChanged(self, newMessage):
        '''Update the view when the message changes.'''
        self.label.setText(newMessage)
        self.update()
コード例 #14
0
ファイル: main.py プロジェクト: tmccombs/kountdown
class Kountdown(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        self.setHasConfigurationInterface(True)

        self.model = KountdownModel(self.configScheme())
        if self.model.needsConfiguration:
            self.setConfigurationRequired(True)
        else:
            self.setupMainUI()
        self.resize(300, 125)

    def setupMainUI(self):
        print 'setup'
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)

        self.setBackgroundHints(Plasma.Applet.TranslucentBackground)

        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        self.label = Plasma.Label(self.applet)
        self.label.setText(self.model.message)
        self.label.setStyleSheet('''font-size: 18pt;''')
        self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.layout.addItem(self.label)
        self.applet.setLayout(self.layout)

        self.connectToEngine()
        self.model.messageChanged.connect(self.handleMessageChanged)

    def configChanged(self):
        '''handle changes in configuration'''
        plasmascript.Applet.configChanged(self)
        self.updatedConfig()

    def updatedConfig(self):
        config = self.config()
        if self.configurationRequired() and not self.model.needsConfiguration:
            self.setConfigurationRequired(False)
            self.setupMainUI()

    def connectToEngine(self):
        self.timeEngine = self.dataEngine("time")
        self.model.connectToEngine(self.timeEngine)

    def handleMessageChanged(self, newMessage):
        '''Update the view when the message changes.'''
        self.label.setText(newMessage)
        self.update()
コード例 #15
0
ファイル: main.py プロジェクト: afreakk/KDEWidgets
class rssWidget(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        self.setLayout()
        self.startTimer(10000)

    def timerEvent(self, evt):
        setLabels(self.applet)

    def setLayout(self):
        global labels
        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        setLabels(self.applet)
        for label in labels:
            self.layout.addItem(label)
        self.applet.setLayout(self.layout)
コード例 #16
0
ファイル: main.py プロジェクト: cdowen/weather_app
class weatherApplet(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)
 
    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.Square)
 
        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)
 
        self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)
        label = Plasma.Label(self.applet)
        label.setText("Hello world!")
        self.layout.addItem(label)
        self.applet.setLayout(self.layout)
        self.resize(125,125)
コード例 #17
0
ファイル: main.py プロジェクト: florianjacob/veromix-plasmoid
    def showModalWidget(self,mainWidget):
        #mainWidget.widgetClose.connect(self.destroyMessageOverlay)
        if self.messageOverlay:
            return
        if self.messageDialog:
            return

        corona = self.scene()
        mainWidget.adjustSize()
        hint = mainWidget.preferredSize()
        if (hint.height() > self.widget.size().height()) or (hint.width() > self.widget.size().width()):
            ## either a collapsed popup in h/v form factor or just too small,
            ## so show it in a dialog associated with ourselves
            #pass
            if (corona):
                corona.addOffscreenWidget(mainWidget)

            if (self.messageDialog):
                pass
            else:
                self.messageDialog = Plasma.Dialog()

            self.messageDialog.setGraphicsWidget(mainWidget)
            mainWidget.setParentItem(self.messageDialog.graphicsWidget ())
        else:
            self.messageOverlay = self.createMessageOverlay()
            self.formatOverlay()
            self.messageOverlay.opacity = 0.8
            mainWidget.setParentItem(self.messageOverlay)
            l = QGraphicsLinearLayout(self.messageOverlay)
            l.addItem(mainWidget)

        if self.messageDialog:
            pos = self.geometry().topLeft().toPoint()
            if (corona):
                pos = corona.popupPosition(self.applet, self.messageDialog.size())

            self.messageDialog.move(pos)
            #self.locationToDirection(self.location())
            self.messageDialog.animatedShow(Plasma.Direction(0))
            self.hidePopup()
        else:
            self.messageOverlay.show()
コード例 #18
0
class CommandesApplet(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)
 
    def init(self):
        self.setHasConfigurationInterface(False)		#interface de configuration
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)			#Possibilité de redimensionner / Plasma.IgnoreAspectRatio
        
	
        self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)	#Création du layout
        self.label = Plasma.Label(self.applet)	#Création du label
        self.layout.addItem(self.label)		#Ajout du label au layout
        
        #self.setMinimumWidth(1000)	#Largeur minimum
        #self.setMaximumHeight(900)	#Hauteur maximum
        
        self.startTimer(1000)
        
    def timerEvent(self, event):
	text = "%s" % os.popen(str('who')).read()
	self.label.setText(text)
	self.update()
コード例 #19
0
ファイル: main.py プロジェクト: janx/xmonad-log-plasmoid
class XMonadLogPlasmoid(plasmascript.Applet):

	label_signal = QtCore.pyqtSignal(str)
	session_bus = None

	def __init__(self, parent, args=None):
		plasmascript.Applet.__init__(self, parent)

	def init(self):
		global label

		self.setHasConfigurationInterface(False)
		self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
		self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
		self.setMinimumWidth(425)

		self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)
		label = Plasma.Label(self.applet)
		label.setText("Waiting for XMonad...")
		self.layout.addItem(label)
		self.applet.setLayout(self.layout)

		self.setup_dbus()
		self.label_signal.connect(update_label)

	def setup_dbus(self):
		self.session_bus = dbus.SessionBus()
		proxy = self.session_bus.get_object(
			bus_name='org.xmonad.Log',
			object_path='/org/xmonad/Log')

		self.session_bus.add_signal_receiver(
			handler_function=self.msg_receive,
			signal_name='Update',
			dbus_interface='org.xmonad.Log')

	def msg_receive(self, msg):
		self.label_signal.emit(msg)
コード例 #20
0
ファイル: main.py プロジェクト: afreakk/KDEWidgets
class hwTempApp(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)

    def init(self):
        global labels
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.Square)

        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        makeLabels(self.applet)
        for label in labels:
            self.layout.addItem(label)
        self.applet.setLayout(self.layout)
        self.startTimer(8000)
        self.resize(400,200)
    def timerEvent(self,evt):
        strings = getStrings()
        updateLabels(strings)
コード例 #21
0
class XMonadLogPlasmoid(plasmascript.Applet):

    label_signal = QtCore.pyqtSignal(str)
    session_bus = None

    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        global label

        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self.setMinimumWidth(425)

        self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)
        label = Plasma.Label(self.applet)
        label.setText("Waiting for XMonad...")
        self.layout.addItem(label)
        self.applet.setLayout(self.layout)

        self.setup_dbus()
        self.label_signal.connect(update_label)

    def setup_dbus(self):
        self.session_bus = dbus.SessionBus()
        proxy = self.session_bus.get_object(bus_name='org.xmonad.Log',
                                            object_path='/org/xmonad/Log')

        self.session_bus.add_signal_receiver(handler_function=self.msg_receive,
                                             signal_name='Update',
                                             dbus_interface='org.xmonad.Log')

    def msg_receive(self, msg):
        self.label_signal.emit(msg)
コード例 #22
0
ファイル: main.py プロジェクト: afreakk/KDEWidgets
class hwTempApp(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        global labels
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.Square)

        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        makeLabels(self.applet)
        for label in labels:
            self.layout.addItem(label)
        self.applet.setLayout(self.layout)
        self.startTimer(8000)
        self.resize(400, 200)

    def timerEvent(self, evt):
        strings = getStrings()
        updateLabels(strings)
コード例 #23
0
ファイル: main.py プロジェクト: spamalot/kdei3status
    def init(self):
        # Fill space if in a horizontal panel.
        self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Preferred))

        layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)
        layout.setContentsMargins(0, 0, 0, 0)
        self.applet.setLayout(layout)

        self.icon = Plasma.IconWidget(self.applet)
        self.label = Plasma.Label(self.applet)
        # TODO: Improve handling of very long window titles.
        self.label.setWordWrap(False)

        layout.addItem(self.icon)
        layout.addItem(self.label)
        layout.setStretchFactor(self.label, 1)

        # Reasonable default size -- can be resized later by user.
        self.resize(500, 30)

        self.refreshTimer = QTimer()
        self.refreshTimer.setInterval(I3STATUS_REFRESH_INTERVAL)
        self.refreshTimer.timeout.connect(self.reloadI3statusText)
        self.statusIterator = execute(["i3status"])
        self.refreshTimer.start()

        self.windowChangeTimer = QTimer()
        self.windowChangeTimer.setSingleShot(True)
        self.windowChangeTimer.setInterval(TITLE_DISPLAY_TIMEOUT)
        self.windowChangeTimer.timeout.connect(self.hideTitleText)

        KWindowSystem.self().windowRemoved.connect(self.windowRemoved)
        KWindowSystem.self().windowChanged.connect(self.windowChanged)
        KWindowSystem.self().activeWindowChanged.connect(
            self.activeWindowChanged)
コード例 #24
0
ファイル: main.py プロジェクト: triffid/plasmoid
class TurnOffScreen(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        #TODO: have a configuration interface to set keybroad shortcut
        #self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.ConstrainedSquare)
        self.setBackgroundHints(self.NoBackground)

        self.sessionBus = dbus.SessionBus()
        self.powerdevil = self.sessionBus.get_object(
            'org.freedesktop.PowerManagement', '/modules/powerdevil')

        self.icon = Plasma.IconWidget(KIcon('preferences-desktop-screensaver'),
                                      '', self.applet)
        if KGlobalSettings.singleClick():
            self.connect(self.icon, SIGNAL('clicked()'), self.turn_off_screen)
        else:
            self.connect(self.icon, SIGNAL('doubleClicked()'),
                         self.turn_off_screen)
        self.connect(self, SIGNAL('active()'), self.turn_off_screen)

        self.layout = QGraphicsLinearLayout(self.applet)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.layout.addItem(self.icon)
        self.setLayout(self.layout)
        self.resize(25, 25)

#def showConfigurationInterface(self):
#        self.con_short = KShortcutWidget(None)
#        self.con_short.show()

    def turn_off_screen(self):
        self.powerdevil.turnOffScreen(dbus_interface='org.kde.PowerDevil')
コード例 #25
0
ファイル: main.py プロジェクト: stibi/karmack-plasmoid
class Karmack4(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)

    def init(self):
        self.applet.resize(480.0, 300.0)

        qmlView = Plasma.DeclarativeWidget()
        qmlView.setQmlPath("karmack4/contents/ui/main.qml")

        self.layout = QGraphicsLinearLayout(self.applet)
        self.layout.setOrientation(Qt.Vertical)
        self.layout.addItem(qmlView)

        helloLabel = Plasma.Label(self.applet)
        helloLabel.setText(PYQT_VERSION_STR)
        self.layout.addItem(helloLabel)

        buttonek = Plasma.PushButton(self.applet)
        buttonek.setText("Klikni a uvidis!")
        self.layout.addItem(buttonek)

        self.qmlRootObject = qmlView.rootObject()

        self.connect(buttonek, SIGNAL("clicked()"), self.buttonClicked)
        self.connect(KWindowSystem.self(), SIGNAL("windowAdded(WId)"), self.onWokynkoNove)
        self.connect(KWindowSystem.self(), SIGNAL("windowRemoved(WId)"), self.onWokynkoFuc)

    def buttonClicked(self):
        #print dir(self.qmlRootObject)
        self.qmlRootObject.updateQml()

    def onWokynkoNove(self):
        self.qmlRootObject.windowAdded()

    def onWokynkoFuc(self):
        self.qmlRootObject.windowRemoved()
コード例 #26
0
ファイル: main.py プロジェクト: juancarlospaco/pylou
class PylouWidget(QGraphicsWidget):

    """Main Widget for Pylou."""

    def __init__(self, parent):
        """Init class."""
        QGraphicsWidget.__init__(self)
        self.applet = parent

    def init(self):
        """Start Pylou Widget."""
        self.layou = QGraphicsLinearLayout(self)
        self.stringlist = QStringList()
        self.model = QStringListModel(self.applet)
        self.model.setStringList(self.stringlist)
        self.treeview = MyTreeView(self)
        self.treeview.setModel(self.model)
        self.lineEdit, self.label = MyLineEdit(self), Plasma.Label(self)
        self.label.setText("Search")
        self.layou.setOrientation(0x2)  # Qt.Vertical
        self.layou.addItem(self.treeview)
        self.layou.addItem(self.label)
        self.layou.addItem(self.lineEdit)
        self.setLayout(self.layou)
        self.lineEdit.returnPressed.connect(self.addItem)
        self.setMinimumSize(200, 99)
        self.setMaximumSize(666, 666)
        # custom user choosed fonts
        user_font_family = QVariant(self.applet.configurations.readEntry(
            "TextFont", QVariant(QFont())))
        self.treeview.nativeWidget().setFont(QFont(user_font_family))
        # custom user choosed styles
        user_style_sheet = "color:{};alternate-background-color:{}".format(
            self.applet.configurations.readEntry("TextColor"),
            self.applet.configurations.readEntry("AlternateBColor"))
        self.treeview.nativeWidget().setStyleSheet(user_style_sheet)
        # Qt connecting people
        Applet.connect(
            self.lineEdit, SIGNAL("keyUPPressed"), self.prevHistoryItem)
        Applet.connect(
            self.lineEdit, SIGNAL("keyDownPressed"), self.nextHistoryItem)
        Applet.connect(self.treeview, SIGNAL("DblClick"), self.openFile)
        Applet.connect(self.treeview, SIGNAL("Click"), self.openDirectory)
        self.applet.appletDestroyed.connect(self.saveHistory)
        # History file
        self.histfile = HISTORY_FILE_PATH
        with open(self.histfile, 'r') as history_file:
            self.history = history_file.readlines()
        self.historyCurrentItem = 0
        self.treeview.nativeWidget().hide()
        self.resize(self.minimumSize())

    def saveHistory(self):
        """Write History to History file."""
        with open(self.histfile, 'w') as history_file:
            history_file.writelines(self.history)

    def prevHistoryItem(self):
        """Navigate the History 1 Item Backwards."""
        if self.historyCurrentItem < len(self.history):
            self.historyCurrentItem = self.historyCurrentItem + 1
        try:
            self.lineEdit.setText(str(self.history[-self.historyCurrentItem]))
        except IndexError as error:
            print(error)
            self.label.setText("ERROR: History Empty.")

    def nextHistoryItem(self):
        """Navigate the History 1 Item Forwards."""
        if self.historyCurrentItem > 1:
            self.historyCurrentItem = self.historyCurrentItem - 1
        try:
            self.lineEdit.setText(str(self.history[-self.historyCurrentItem]))
        except IndexError as error:
            print(error)
            self.label.setText("ERROR: History Empty.")

    def addItem(self):
        """Add Items from Locate command."""
        start_time = datetime.now().second
        self.stringlist.clear()
        lineText = self.lineEdit.text()
        if len(lineText) and str(lineText).strip() not in self.history:
            self.history.append(lineText + "\n")
            self.historyCurrentItem = 1
            self.saveHistory()
        self.historyCurrentItem = self.historyCurrentItem - 1
        command = "ionice --ignore --class 3 chrt --idle 0 "  # Nice CPU / IO
        command += "locate --ignore-case --existing --quiet --limit 9999 {}"
        condition = str(self.applet.configurations.readEntry("Home")) == "true"
        if len(str(lineText).strip()) and condition:
            command_to_run = command.format(  # Only Search inside Home folders
                path.join(path.expanduser("~"), "*{}*".format(lineText)))
        else:
            command_to_run = command.format(lineText)
        locate_output = Popen(command_to_run, shell=True, stdout=PIPE).stdout
        results = tuple(locate_output.readlines())
        banned = self.applet.configurations.readEntry("Banned")
        banned_regex_pattern = str(banned).strip().lower().replace(" ", "|")
        for item in results:
            if not search(banned_regex_pattern, str(item)):  # banned words
                self.stringlist.append(item[:-1])
        purge()  # Purge RegEX Cache
        self.model.setStringList(self.stringlist)
        self.treeview.nativeWidget().resizeColumnToContents(0)
        number_of_results = len(results)
        if number_of_results:  # if tems found Focus on item list
            self.lineEdit.nativeWidget().clear()
            self.label.setText("Found {} results on {} seconds !".format(
                number_of_results, abs(datetime.now().second - start_time)))
            self.resize(500, 12 * number_of_results)
            self.treeview.nativeWidget().show()
            self.treeview.nativeWidget().setFocus()
        else:  # if no items found Focus on LineEdit
            self.label.setText("Search")
            self.resize(self.minimumSize())
            self.treeview.nativeWidget().hide()
            self.lineEdit.nativeWidget().selectAll()
            self.lineEdit.nativeWidget().setFocus()

    def openDirectory(self, index):
        """Take a model index and find the folder name then open the folder."""
        item_to_open = path.dirname(str(self.model.data(index, 0).toString()))
        Popen("xdg-open '{}'".format(item_to_open), shell=True)

    def openFile(self, index):
        """Take a model index and find the filename then open the file."""
        item_to_open = self.model.data(index, 0).toString()
        Popen("xdg-open '{}'".format(item_to_open), shell=True)
コード例 #27
0
class Channel(QGraphicsWidget):

    def __init__(self , parent):
        QGraphicsWidget.__init__(self)
        self.veromix = parent
        self.index = -1
        self.pa = parent.getPulseAudio()
        self.set_name("")
        self.deleted = True
        self.pa_sink = None
        self.extended_panel_shown = False
        self.extended_panel= None
        self.show_meter = True
        self.expander = None
        self.popup_menu = None
        self.card_settings = None
        self.menus = None
        self.port_actions = None

        self.double_click_filter = ChannelEventFilter(self)
        self.installEventFilter(self.double_click_filter)

        self.init()
        self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed,True))

    def init(self):
        self.layout = QGraphicsLinearLayout(Qt.Vertical)
        self.layout.setContentsMargins(2,2,2,0)
        self.setLayout(self.layout)
        self.initArrangement()
        self.composeArrangement()
        self.setAcceptDrops(True)
        self._on_upate_expander_enabled()

    def initArrangement(self):
        self.create_frame()
        self.create_panel()
        self.createMute()
        self.createMiddle()
        self.create_expander()

    def composeArrangement(self):
        self.layout.addItem(self.frame)
        self.frame_layout.addItem(self.panel)
        self.panel_layout.addItem(self.mute)
        self.panel_layout.addItem(self.middle)

    def create_frame(self):
        self.frame = Plasma.Frame()
        self.frame_layout = QGraphicsLinearLayout(Qt.Vertical)
        self.frame.setEnabledBorders (Plasma.FrameSvg.NoBorder)
        self.frame.setFrameShadow(Plasma.Frame.Plain)
        self.frame_layout.setContentsMargins(0,0,0,0)
        self.frame.setLayout(self.frame_layout)

    def create_panel(self):
        self.panel = QGraphicsWidget()
        self.panel_layout = QGraphicsLinearLayout(Qt.Horizontal)
        self.panel_layout.setContentsMargins(6,8,10,6)
        self.panel.setLayout(self.panel_layout)

    def createMute(self):
        self.mute = MuteButton(self)
        self.connect(self.mute, SIGNAL("clicked()"), self.on_mute_cb)

    def createMiddle(self):
        self.middle = QGraphicsWidget()
        self.middle_layout = QGraphicsLinearLayout(Qt.Vertical)
        #self.middle_layout.setContentsMargins(6,8,6,0)
        self.middle_layout.setContentsMargins(0,0,0,0)
        self.middle.setLayout(self.middle_layout)
        self.middle.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum))
        self.createSlider()
        self.middle_layout.addItem(self.slider)

    def createSlider(self):
        self.slider = MeterSlider(None, self.veromix.is_slider_unit_value_visible())
        self.slider.installEventFilter(self.double_click_filter)
        self.slider.set_meter_visible(self.veromix.is_meter_visible())
        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setMaximum(self.veromix.get_max_volume_value())
        self.slider.setMinimum(0)
        self.slider.volumeChanged.connect( self.on_slider_cb)

    def create_expander(self):
        self.expander = Plasma.IconWidget(self.panel)
        self.expander.setZValue(10)
        self.connect(self, SIGNAL("geometryChanged()"), self._resize_widgets)
        self.expander.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed))
        self.expander.clicked.connect(self.on_expander_clicked)
        self.expander.setSvg("widgets/arrows", "left-arrow")

    def create_context_menu(self, event):
        self.popup_menu = QMenu()
        self.popup_menu.triggered.connect(self.on_contextmenu_clicked)
        self.context_menu_create_custom()
        self.context_menu_create_mute()
        self.context_menu_create_meter()
        self.context_menu_create_unlock_channels()
        self.context_menu_create_effects()
        self.create_menu_kill_sink()
        self.context_menu_create_settings()
        if event:
            self.popup_menu.exec_(event.screenPos())
        else:
            self.popup_menu.exec_(QCursor.pos())

    def context_menu_create_mute(self):
        action_mute = QAction(i18n("Muted"), self.popup_menu)
        self.popup_menu.addAction(action_mute)
        action_mute.setCheckable(True)
        action_mute.setChecked(self.isMuted())
        action_mute.triggered.connect(self.on_mute_cb)

    def context_menu_create_meter(self):
        action_meter = QAction(i18n("Volume meter"), self.popup_menu)
        self.popup_menu.addAction(action_meter)
        action_meter.setCheckable(True)
        action_meter.setChecked(self.pa_sink.has_monitor())
        action_meter.triggered.connect(self.on_meter_cb)

    def context_menu_create_unlock_channels(self):
        action_unlock = QAction(i18n("Unlock channels"), self.popup_menu)
        self.popup_menu.addAction(action_unlock)
        action_unlock.setCheckable(True)
        action_unlock.setChecked(self.extended_panel_shown)
        action_unlock.triggered.connect(self.toggle_channel_lock)

    def context_menu_create_ports(self):
        self.port_actions = {}
        if len(self.pa_sink.ports.keys()) > 1:
            ports_menu = QMenu(i18n("Ports"), self.popup_menu)
            ports = self.pa_sink.ports

            for port in ports.keys():
                action = QAction(in_unicode(ports[port]), self.popup_menu)
                self.port_actions[action]=port
                if port == self.pa_sink.active_port:
                    action.setCheckable(True)
                    action.setChecked(True)
                else:
                    action.setChecked(False)
                    action.setCheckable(False)
                ports_menu.addAction(action)
            self.popup_menu.addMenu(ports_menu)

    def create_menu_kill_sink(self):
        pass

    def context_menu_create_sounddevices(self):
        self.card_settings = {}
        self.menus = []
        for card in self.veromix.card_infos.values():
            current = self.veromix.get_card_info_for(self)
            if current != None and  current.get_description() == card.get_description():
                card_menu = QMenu(i18n("Profile"), self.popup_menu)
                self.popup_menu.addMenu(card_menu)
            else:
                card_menu = QMenu(card.get_description(), self.popup_menu)
                self.menus.append(card_menu)
            active_profile_name = card.get_active_profile_name()
            self.profiles = card.get_profiles()
            for profile in self.profiles:
                action = QAction(in_unicode(profile.description), card_menu)
                self.card_settings[action] = card
                if profile.name == active_profile_name:
                    action.setCheckable(True)
                    action.setChecked(True)
                card_menu.addAction(action)

    def context_menu_create_sounddevices_other(self):
        if len(self.menus) > 0:
            self.popup_menu.addSeparator()
            for each in self.menus:
                self.popup_menu.addMenu(each)

    def context_menu_create_custom(self):
        pass

    def context_menu_create_effects(self):
        pass

    def context_menu_create_settings(self):
        self.popup_menu.addSeparator()
        action_settings = QAction(i18n("Veromix Settings"), self.popup_menu)
        self.popup_menu.addAction(action_settings)
        action_settings.triggered.connect(self.veromix.applet.showConfigurationInterface)

    def _resize_widgets(self):
        self.expander.setPos(int(self.panel.size().width() - self.expander.size().width()) ,0)

    def on_double_clicked(self):
        self.slider.toggle_meter()
        self.pa_sink.toggle_monitor()
        self.slider.set_meter_value(0)

    def on_step_volume(self, up):
        vol = self.pa_sink.get_volume()
        STEP = 5
        if up:
            vol = vol + STEP
        else:
            vol = vol - STEP
        if vol < 0:
            vol = 0
        if vol > self.veromix.get_max_volume_value():
            vol = self.veromix.get_max_volume_value()
        self.setVolume(vol)

    def setVolume(self, value):
        vol = self.pa_sink.volumeDiffFor(value)
        if self.veromix.get_auto_mute():
            for c in vol:
                if c <= 0:
                    ## FIXME HACK for MurzNN this should be conditional
                    self.pa.set_sink_mute(self.index, True)
                    self.automatically_muted = True
                    return
            if self.automatically_muted :
                self.automatically_muted = False
                self.pa.set_sink_mute(self.index, False)
        self.set_channel_volumes(vol)

    def get_volume(self):
        if self.pa_sink:
            return self.pa_sink.get_volume()
        return [0]

    def on_expander_clicked(self):
        self.contextMenuEvent(None)

    def toggle_channel_lock(self):
        self.middle_layout.removeItem(self.slider)
        self.slider = None
        if (self.extended_panel_shown):
            self.extended_panel_shown = False
            self.expander.setSvg("widgets/arrows", "left-arrow")
            self.createSlider()
            self.middle_layout.addItem(self.slider)
        else:
            self.extended_panel_shown = True
            self.expander.setSvg("widgets/arrows", "down-arrow")
            self.slider = SinkChannelWidget(self.veromix, self)
            self.slider.installEventFilter(self.double_click_filter)
            self.middle_layout.addItem(self.slider)
        self.middle_layout.setContentsMargins(0,0,0,0)
        self.middle.setContentsMargins(0,0,0,0)
        self.update_with_info(self.pa_sink)
        self.veromix.check_geometries()

    def on_update_configuration(self):
        self.slider.set_meter_visible(self.veromix.is_meter_visible())
        self.slider.setMaximum(self.veromix.get_max_volume_value())
        self.slider.set_unit_value_visible(self.veromix.is_slider_unit_value_visible())
        self._on_upate_expander_enabled()

    def _on_upate_expander_enabled(self):
        if self.veromix.is_expander_enabled():
            self.expander.show()
        else:
            self.expander.hide()

    def on_contextmenu_clicked(self, action):
        if action in self.card_settings.keys():
            card = self.card_settings[action]
            for profile in card.get_profiles():
                if action.text() == profile.description:
                    self.veromix.pa.set_card_profile(card.index, profile.name)
        if action in self.port_actions.keys():
            self.pa_sink.set_port(self.port_actions[action])

    def contextMenuEvent(self,event):
        self.create_context_menu(event)

    def on_mute_cb(self):
        self.pa_sink.toggle_mute()

    def on_meter_cb(self):
        self.on_double_clicked()

    def sink_input_kill(self):
        self.pa_sink.kill()

    def set_channel_volumes(self, values):
        self.pa_sink.set_volume(values)

    def on_update_meter(self, index, value, number_of_sinks):
        if self.index == index:
            self.slider.set_meter_value(int(value))

    def update_with_info(self,info):
        self.pa_sink = info
        self.index = info.index
        self.update_label()
        self.updateIcon()
        if self.slider:
            self.slider.update_with_info(info)
        if self.extended_panel:
            self.extended_panel.update_with_info(info)
        self.update()

    def update_label(self):
        if self.pa_sink:
            self.set_name(self.pa_sink.name)

    def getOutputIndex(self):
        return self.index

    def sinkIndexFor( self, index):
        return (index * 100000) + 100000

    def updateIcon(self):
        pass

    def on_slider_cb(self, value):
        self.setVolume(value)

    def isDefaultSink(self):
        if self.pa_sink and "isdefault" in self.pa_sink.props:
            return self.pa_sink.props["isdefault"] == "True"
        return False

    def startDrag(self,event):
        pass

    def removeSlider(self):
        # if a slider is not visible, plasmoidviewer crashes if the slider is not removed.. (dont ask me)
        if self.slider:
            self.middle_layout.removeItem(self.slider)
        self.slider = None

    def isMuted(self):
        if self.pa_sink:
            return self.pa_sink.isMuted()
        return False

    def isSinkOutput(self):
        if self.pa_sink:
            return self.pa_sink.is_sinkoutput()
        return False

    def isSinkInput(self):
        if self.pa_sink:
            return self.pa_sink.is_sinkinput()
        return False

    def isSink(self):
        if self.pa_sink:
            return self.pa_sink.is_sink()
        return False

    def isNowplaying(self):
        return False

    def isSourceOutput(self):
        if self.pa_sink:
            return self.pa_sink.is_sourceoutput()
        return False

    def wheelEvent(self, event):
        if self.slider:
            self.slider.wheelEvent(event)

    def set_name(self, string):
        self._name = in_unicode(string)

    def name(self):
        return self._name

    def update_module_info(self, index, name, argument, n_used, auto_unload):
        pass

    def get_ladspa_type(self):
        return str(type(self))

    def get_pasink_name(self):
        return self.pa_sink.name

## LADSPA helpers

    def populate_presets_menu(self, target_menu, checked_item, add_actions):
        effect_menu = QMenu(i18n("Presets"), target_menu)
        if add_actions:
            self.action_save_preset = QAction(i18n("Save"),effect_menu)
            effect_menu.addAction(self.action_save_preset)
            if not self.is_preset():
                self.action_save_preset.setEnabled(False)

            self.action_save_as_preset = QAction(i18n("Save As..."),effect_menu)
            effect_menu.addAction(self.action_save_as_preset)
            effect_menu.addSeparator()

        for preset in LADSPAPresetLoader().presets():
            action = QAction(preset["preset_name"],effect_menu)
            effect_menu.addAction(action)
            if checked_item == preset["preset_name"]:
                action.setCheckable(True)
                action.setChecked(True)
                action.setEnabled(False)
        target_menu.addMenu(effect_menu)

    def populate_switch_effect_menu(self, target_menu, checked_item):
        effect_menu = QMenu(i18n("Effect"), target_menu)
        for preset in LADSPAEffects().effects():
            action = QAction(preset["preset_name"],effect_menu)
            effect_menu.addAction(action)
            if checked_item == preset["label"]:
                action.setCheckable(True)
                action.setChecked(True)
                action.setEnabled(False)
        target_menu.addMenu(effect_menu)

    def on_set_ladspa_effect(self, value, master):
        parameters = ""
        preset = None
        for p in LADSPAEffects().effects():
            if p["preset_name"] == value:
                parameters = "sink_name=" + urllib.quote(p["name"])
                preset = p

        for p in LADSPAPresetLoader().presets():
            if p["preset_name"] == value:
                parameters = "sink_name=" + urllib.quote(p["preset_name"])
                preset = p

        parameters =  parameters + " master=" + master + " "
        parameters =  parameters + " plugin=" + preset["plugin"]
        parameters =  parameters + " label=" + preset["label"]
        parameters =  parameters + " control=" + preset["control"]
        self.pa_sink.set_ladspa_sink(parameters)

    def next_focus(self, forward=True):
        channels = self.veromix.get_visible_channels()
        if len(channels) > 0:
            index = 0
            if self in channels:
                index = channels.index(self)
                if forward:
                    index = index + 1
                    if index >= len(channels):
                        index = 0
                else:
                    index = index - 1
                    if index < 0:
                        index = len(channels) - 1
            channels[index].set_focus()

    def set_focus(self):
        self.slider.set_focus()

    def pa_sink_proxy(self):
        return self.pa_sink
コード例 #28
0
class ForecastModule:
	def __init__(self):
		self.name = "Napoved"
		self.updateTimer = QTimer()
		self.updateTimer.timeout.connect(self.update)
	
	def makeLayout(self):
		self.layout = QGraphicsLinearLayout(Qt.Vertical)
		self.forecastTopLayout = QGraphicsLinearLayout(Qt.Horizontal)
		
		#Forecast Layout
		self.forecastIcons = [QGraphicsWebView() for i in range(4)]
		[v.setEnabled(False) for v in self.forecastIcons]
		[v.setMaximumSize(40,40) for v in self.forecastIcons]
		[v.setMinimumSize(40,40) for v in self.forecastIcons]
		[v.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) for v in self.forecastIcons]
		[v.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) for v in self.forecastIcons]

		self.forecastDays = [Plasma.Label() for i in range(4)]
		[l.setAlignment(Qt.AlignCenter) for l in self.forecastDays]

		self.forecastTemperatures = [Plasma.Label() for i in range(4)]
		[l.setAlignment(Qt.AlignCenter) for l in self.forecastTemperatures]
		
		
		self.forecastIconFrames = [QGraphicsLinearLayout(Qt.Horizontal) for i in range(4)]
		[self.forecastIconFrames[i].addStretch() for i in range(4)]
		[self.forecastIconFrames[i].addItem(self.forecastIcons[i]) for i in range(4)]
		[self.forecastIconFrames[i].addStretch() for i in range(4)]
		
		self.forecastFrames = [QGraphicsLinearLayout(Qt.Vertical) for i in range(4)]
		[self.forecastFrames[i].addStretch() for i in range(4)]
		[self.forecastFrames[i].addItem(self.forecastDays[i]) for i in range(4)]
		[self.forecastFrames[i].addItem(self.forecastIconFrames[i]) for i in range(4)]
		[self.forecastFrames[i].addItem(self.forecastTemperatures[i]) for i in range(4)]
		[self.forecastFrames[i].addStretch() for i in range(4)]

		self.forecastTopFrame = QGraphicsLinearLayout(Qt.Horizontal)
		self.forecastTopFrame.addStretch()
		self.forecastTopFrame.addItem(self.forecastFrames[0])
		self.forecastTopFrame.addStretch()
		
		self.forecastBottomFrames = QGraphicsLinearLayout(Qt.Horizontal)
		self.forecastBottomFrames.addStretch()
		[self.forecastBottomFrames.addItem(self.forecastFrames[i]) for i in range(1,4)]
		self.forecastBottomFrames.addStretch()

		self.forecastRefreshButton = Plasma.IconWidget()
		self.forecastRefreshButton.setIcon("view-refresh")
		self.forecastRefreshButton.clicked.connect(self.update)

		self.forecastStatusLabel = Plasma.Label()

		self.forecastTopLayout.addItem(self.forecastStatusLabel)
		self.forecastTopLayout.addItem(self.forecastRefreshButton)
		self.forecastTopLayout.setMaximumHeight(32)
		
		self.forecastUpdateTimeSelector = UpdateTimeSelector()
		self.forecastUpdateTimeSelector.setDefaultTime(4)
		self.forecastUpdateTimeSelector.setDefaultInterval('h')
		self.forecastUpdateTimeSelector.updateTimeSpin.valueChanged.connect(self.forecastTimeChanged)
		self.forecastUpdateTimeSelector.updateCheckBox.toggled.connect(self.forecastTimerToggle)
		
		
		self.layout.addItem(self.forecastTopLayout)
		self.layout.addStretch()
		self.layout.addItem(self.forecastTopFrame)
		self.layout.addItem(self.forecastBottomFrames)
		self.layout.addStretch()
		self.layout.addItem(self.forecastUpdateTimeSelector.layout)
	
	def forecastTimerToggle(self, toggled):
		if toggled:
			multiplier = 1
			if self.forecastUpdateTimeSelector.getInterval() == 'min':
				multiplier = 60
			if self.forecastUpdateTimeSelector.getInterval() == 'h':
				multiplier = 60 * 60
			self.updateTimer.start(self.forecastUpdateTimeSelector.getTime() * 1000 * multiplier)
			self.update()
		else:
			self.updateTimer.stop()
			
	def forecastTimeChanged(self, value):
		if self.forecastUpdateTimeSelector.isChecked():
			self.updateTimer.stop()
		self.forecastTimerToggle(self.forecastUpdateTimeSelector.isChecked())
	
	def update(self):
		forecast = NoForecast()
		forecastData = forecast.getData()
		date = forecast.getForecastDate()
		try:
			urllib.urlopen('http://www.google.com', timeout=2)
			forecast = BohinjForecast()
			forecastData = forecast.getData()
			date = forecast.getForecastDate()
		except:
			self.offlineMode()
			return
		date = date.split('-')
		try:
			self.forecastStatusLabel.setText(u"Bohinj, napoved dne <b>%s.%s.%s</b>" % (date[2], date[1], date[0]))
		except:
			pass
		
		for i in range(4):
			self.forecastDays[i].setText(u'<b>' + forecastData[i].day + u'</b>')
			self.forecastIcons[i].setUrl(QUrl(forecastData[i].icon))
			self.forecastTemperatures[i].setText(u"<b>%s</b> | <b>%s</b>" % (forecastData[i].low, forecastData[i].high))
	
	def offlineMode(self):
		self.forecastStatusLabel.setText(u"Bohinj, napoved ni na voljo.")
		[a.setUrl(QUrl("weather-none-available.png")) for a in self.forecastIcons]
		for i in range(4):
			self.forecastTemperatures[i].setText(u"<b>N/A</b>")
			self.forecastDays[i].setText(u'<b>N/A</b>')
コード例 #29
0
ファイル: main.py プロジェクト: rangalo/plasma_pyweather
class WeatherApplet(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)
        self._unit = "SI"
        self._image_prefix = ":/images/"

        self._img_width = 16
        self._img_height = 16
        self._big_img_width = 48
        self._big_img_height = 48
        self._fc_column_width = 100

    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)

        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        # self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        self.layout_main = QGraphicsGridLayout(self.applet)
        self.layout_top_left = QGraphicsLinearLayout(Qt.Vertical, self.layout_main)
        self.layout_bottom = QGraphicsGridLayout(self.layout_main)
        self.layout_bottom.setColumnMaximumWidth(0, self._fc_column_width)
        self.layout_bottom.setColumnMaximumWidth(1, self._fc_column_width)
        self.layout_bottom.setColumnMaximumWidth(2, self._fc_column_width)

        self.lb_location = Plasma.Label(self.applet)
        self.lb_temperature = Plasma.Label(self.applet)
        self.lb_condition = Plasma.Label(self.applet)
        self.lb_humidity = Plasma.Label(self.applet)
        self.lb_wind = Plasma.Label(self.applet)

        # create svg widgets for conditions
        self.svg_w_current = Plasma.SvgWidget(self.applet)
        self.svg_w_fc1 = Plasma.SvgWidget(self.applet)
        self.svg_w_fc2 = Plasma.SvgWidget(self.applet)
        self.svg_w_fc3 = Plasma.SvgWidget(self.applet)

        # self.svg_w_fc1.resize(self._img_width,self._img_height)

        # create labels for forecast
        self.lb_temp_fc1 = Plasma.Label(self.applet)
        self.lb_temp_fc2 = Plasma.Label(self.applet)
        self.lb_temp_fc3 = Plasma.Label(self.applet)

        self.lb_day_fc1 = Plasma.Label(self.applet)
        self.lb_day_fc2 = Plasma.Label(self.applet)
        self.lb_day_fc3 = Plasma.Label(self.applet)

        # create images to display conditions
        self.svg_current = Plasma.Svg(self.applet)
        self.svg_fc1 = Plasma.Svg(self.applet)
        self.svg_fc2 = Plasma.Svg(self.applet)
        self.svg_fc3 = Plasma.Svg(self.applet)

        self.layout_main.addItem(self.layout_top_left, 0, 0)
        self.layout_main.addItem(self.svg_w_current, 0, 1)
        self.layout_main.addItem(self.layout_bottom, 1, 0, 1, 2, Qt.Alignment(Qt.AlignCenter))

        # add current conditions
        self.layout_top_left.addItem(self.lb_location)
        self.layout_top_left.addItem(self.lb_temperature)
        self.layout_top_left.addItem(self.lb_condition)
        self.layout_top_left.addItem(self.lb_humidity)
        self.layout_top_left.addItem(self.lb_wind)

        # add forecast labels for days
        self.layout_bottom.addItem(self.lb_day_fc1, 0, 0, 1, 1, Qt.Alignment(Qt.AlignHorizontal_Mask))
        self.layout_bottom.addItem(self.lb_day_fc2, 0, 1, 1, 1, Qt.Alignment(Qt.AlignHCenter))
        self.layout_bottom.addItem(self.lb_day_fc3, 0, 2, 1, 1, Qt.Alignment(Qt.AlignHCenter))
        # add forecast images
        self.layout_bottom.addItem(self.svg_w_fc1, 1, 0, 1, 1, Qt.Alignment(Qt.AlignLeft))
        self.layout_bottom.addItem(self.svg_w_fc2, 1, 1, 1, 1, Qt.Alignment(Qt.AlignLeft))
        self.layout_bottom.addItem(self.svg_w_fc3, 1, 2, 1, 1, Qt.Alignment(Qt.AlignLeft))
        # add forecast labels for temp
        self.layout_bottom.addItem(self.lb_temp_fc1, 2, 0, 1, 1, Qt.Alignment(Qt.AlignCenter))
        self.layout_bottom.addItem(self.lb_temp_fc2, 2, 1, 1, 1, Qt.Alignment(Qt.AlignCenter))
        self.layout_bottom.addItem(self.lb_temp_fc3, 2, 2, 1, 1, Qt.Alignment(Qt.AlignCenter))

        self.setLayout(self.layout_main)
        self.resize(375, 375)

        self.checkWeather()

        self.timer = QTimer()
        self.connect(self.timer, SIGNAL("timeout()"), self.checkWeather)
        self.timer.start(0.5 * 60000)

    def checkWeather(self):
        wi = WeatherInfo()
        mapper = ConditionMapper()
        wi.parse()
        weather = Weather()
        weather.extractData(wi, self._unit)

        self.lb_location.setText("Location: " + weather.location)

        self.lb_temperature.setText(weather.current_temperature)
        self.lb_condition.setText("Condition: " + weather.current_condition)
        self.lb_humidity.setText(weather.current_humidity)
        self.lb_wind.setText(weather.current_wind)

        # current condition image
        self.svg_current.setImagePath(self._image_prefix + mapper.getMappedImageName(weather.current_condition))
        self.svg_current.resize(self._big_img_width, self._big_img_height)
        self.svg_w_current.setSvg(self.svg_current)

        # load forecast days
        fc_day = weather.fc_dl[0]
        # self.lb_day_fc1.setText("Tomorrow")
        self.lb_day_fc1.setText(fc_day)

        fc_day = weather.fc_dl[1]
        self.lb_day_fc2.setText(fc_day)

        fc_day = weather.fc_dl[2]
        self.lb_day_fc3.setText(fc_day)

        # load forecast images
        fc = weather.fc_conditions[0]
        print fc
        self.svg_fc1.setImagePath(self._image_prefix + mapper.getMappedImageName(fc))
        self.svg_fc1.resize(self._img_width, self._img_height)
        self.svg_w_fc1.setSvg(self.svg_fc1)

        fc = weather.fc_conditions[1]
        print fc
        self.svg_fc2.setImagePath(self._image_prefix + mapper.getMappedImageName(fc))
        self.svg_fc2.resize(self._img_width, self._img_height)
        self.svg_w_fc2.setSvg(self.svg_fc2)

        fc = weather.fc_conditions[2]
        print fc
        self.svg_fc3.setImagePath(self._image_prefix + mapper.getMappedImageName(fc))
        self.svg_fc3.resize(self._img_width, self._img_height)
        self.svg_w_fc3.setSvg(self.svg_fc3)

        self.lb_temp_fc1.setText(weather.fc_low_high[0])
        self.lb_temp_fc2.setText(weather.fc_low_high[1])
        self.lb_temp_fc3.setText(weather.fc_low_high[2])

        # self.layout.addItem(label)
        # self.setLayout(self.layout)
        self.update()
コード例 #30
0
class CurrencyConverter(QGraphicsWidget):
    updated = pyqtSignal()

    def __init__(self,parent):
        QGraphicsWidget.__init__(self)
        self.applet = parent


    def init(self):
        print ("CurrencyConverter: init")

        self.swapping = False
        self.grid_layout = None
        self.timer = None
        self.last_updated = ""

        self.def_from = self.applet.cfg.readEntry("default_from", QString("USD")).toString()
        print "System default country:", KGlobal.locale().country()
        print "System default currency code:", KGlobal.locale().currencyCode()
        self.def_to = self.applet.cfg.readEntry("default_to", KGlobal.locale().currencyCode()).toString()
        #self.def_to = self.applet.cfg.readEntry("default_to", QString("EUR")).toString()
        self.def_amount = self.applet.cfg.readEntry("default_amount", 1.0).toString()
        self.update_interval = self.applet.cfg.readEntry("update_interval", QVariant(60)).toInt()[0] # why does this return a tuple?

        print "Update interval:", self.update_interval

        #self.theme = Plasma.Svg(self)
        #self.theme.setImagePath("widgets/background")
        #self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        # init arrows svg
        #self.arrows_svg = Plasma.Svg(self);
        #self.arrows_svg.setImagePath("widgets/configuration-icons");
        #self.arrows_svg.setContainsMultipleImages(True);
        #self.arrows_svg.resize(KIconLoader.SizeSmall, KIconLoader.SizeSmall);

        #self.collapse_button = Plasma.ToolButton()
        #self.collapse_button.setZValue(3)
        #self.collapse_button.nativeWidget().setMaximumSize(QSize(24, 24))
        #if self.collapsed:
            #self.collapse_button.nativeWidget().setIcon(KIcon(QIcon(self.arrows_svg.pixmap("collapse"))))
            ##self.collapse_button.nativeWidget().setIcon(KIcon("arrow-down"))
        #else:
            #self.collapse_button.nativeWidget().setIcon(KIcon(QIcon(self.arrows_svg.pixmap("restore"))))
            ##self.collapse_button.nativeWidget().setIcon(KIcon("arrow-up"))
        #self.collapse_button.nativeWidget().setToolTip(i18n("Show/Hide controls"))
        #self.collapse_button.clicked.connect(self.collapse_or_expand)

        invert = "%scontents/icons/invert.png" % self.applet.package().path()
        self.invert_button = Plasma.ToolButton()
        self.invert_button.setZValue(3)
        self.invert_button.nativeWidget().setMaximumSize(QSize(24, 24))
        self.invert_button.nativeWidget().setIcon(KIcon(invert))
        self.invert_button.nativeWidget().setToolTip(i18n("Swap currencies"))
        self.invert_button.clicked.connect(self.invert_currencies)

        self.title_label = Plasma.Label()
        self.title_label.nativeWidget().setWordWrap(False)
        #self.title_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)
        self.title_label.setText(i18n("Currency Converter"))
        self.title_label.setAlignment(Qt.AlignCenter)
        f = self.title_label.nativeWidget().font()
        f.setBold(True)
        self.title_label.nativeWidget().setFont(f)

        self.from_label = Plasma.Label()
        self.from_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)
        self.from_label.nativeWidget().setAlignment(Qt.AlignRight)
        self.from_label.setText(i18n("From:"))

        self.currency_from = Plasma.ComboBox()
        self.currency_from.setZValue(2)
        self.currency_from.setFocusPolicy(Qt.NoFocus)

        self.to_label = Plasma.Label()
        self.to_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)
        self.to_label.nativeWidget().setAlignment(Qt.AlignRight)
        self.to_label.setText(i18n("To:"))

        self.currency_to = Plasma.ComboBox()
        self.currency_to.setZValue(1)
        self.currency_to.setFocusPolicy(Qt.NoFocus)

        self.amount_label = Plasma.Label()
        self.amount_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)
        self.amount_label.nativeWidget().setAlignment(Qt.AlignTop) # NOTE: This is a hack because otherwise it flows down when you resize :-/
        self.amount_label.nativeWidget().setAlignment(Qt.AlignRight)
        self.amount_label.setText(i18n("Amount:"))

        self.amount = Plasma.LineEdit()
        self.amount.setClearButtonShown(True)
        self.amount_validator = QDoubleValidator(self.amount.nativeWidget())
        #if KGlobal.locale().decimalSymbol() == ",":
        #    self.amount_validator.setAcceptLocalizedNumbers(True)
        self.amount.nativeWidget().setValidator(self.amount_validator)
        print "Default amount:", self.def_amount
        self.amount.setText(self.def_amount)
        self.amount.setFocus()

        self.amount.editingFinished.connect(self.amount_editing_finished)

        self.from_amount_label = Plasma.Label()
        self.from_amount_label.setMinimumWidth(30)

        self.equal_label = Plasma.Label()
        self.equal_label.setText("=")

        # shows the currency symbol or abbreviation
        self.to_amount_label = Plasma.Label()
        self.to_amount_label.setMinimumWidth(30)

        self.conversion_result = Plasma.LineEdit()
        self.conversion_result.nativeWidget().setAlignment(Qt.AlignRight)
        self.conversion_result.nativeWidget().setReadOnly(True)

        self.credits_label = Plasma.Label()
        self.credits_label.setAlignment(Qt.AlignRight)
        self.credits_label.nativeWidget().setOpenExternalLinks(True)
        logo = "%scontents/images/yahoo-attribution.png" % self.applet.package().path()
        self.credits_label.setText(i18n("Data from <a href=\"http://finance.yahoo.com/currency-converter\"><img src=\"%s\"</a>" % logo))
        f = self.credits_label.nativeWidget().font()
        f.setPointSize(self.font_size()-2)
        self.credits_label.nativeWidget().setFont(f)
        QObject.connect(self.credits_label.nativeWidget(), SIGNAL("linkActivated(const QString&)"), self.open_link)
        QObject.connect(self.credits_label, SIGNAL("linkActivated(const QString&)"), self.open_link)
        self.credits_label.linkActivated.connect(self.open_link)

        # Limit the number of currencies shown at a time if docked in bottom panel.
        #if ((self.applet.formFactor() == Plasma.Horizontal) or (self.applet.formFactor() == Plasma.Vertical)):
        if ((self.applet.formFactor() == Plasma.Horizontal) and (self.applet.location() == Plasma.BottomEdge)):
          self.currency_from.nativeWidget().setMaxVisibleItems(6)
          self.currency_to.nativeWidget().setMaxVisibleItems(4)

        m_locale = KGlobal.locale()
        #cc_list = l.currency().allCurrencyCodesList(KCurrencyCode.ActiveCurrency|KCurrencyCode.SuspendedCurrency|KCurrencyCode.ObsoleteCurrency)
        cc_list = m_locale.currency().allCurrencyCodesList(KCurrencyCode.ActiveCurrency)
        cc_namelist = []
        #print "CC's:", len(l.currency().allCurrencyCodesList())
        #print "# KDE Currency Codes:", len(cc_list)
        for cc in cc_list:
          cc_namelist.append(i18nc( "@item currency name and currency code", "%1 (%2)",
                                    m_locale.currency().currencyCodeToName( cc ), cc ) )

        #cc_namelist.sort()
        for cur in sorted(set(cc_namelist)):
          #print u"Currency:", unicode(cur)
          self.currency_from.nativeWidget().addItem( cur, QVariant( cur.mid( cur.length()-4, 3 ) ) )
          self.currency_to.nativeWidget().addItem( cur, QVariant( cur.mid( cur.length()-4, 3 ) ) )

        self.currency_from.nativeWidget().setCurrentIndex( self.currency_from.nativeWidget().findData( QVariant( self.def_from ) ) )
        self.currency_to.nativeWidget().setCurrentIndex( self.currency_to.nativeWidget().findData( QVariant( self.def_to ) ) )

        self.currency_from.textChanged.connect(self.currency_changed)
        self.currency_to.textChanged.connect(self.currency_changed)

        self.layout_widgets()
        if self.applet.nwmon.connected():
          self.applet.setBusy(False)
          self.start_timer()

    def open_link(self, lnk):
        print "open_link:", lnk

    def start_timer(self):
        print "CurrencyConverter::start_timer '%s'" % self.update_interval
        if not self.timer:
            self.timer = QTimer(self)
        else:
            self.timer.stop()
        if self.update_interval > 0:
            self.timer.setInterval(1000*60*self.update_interval)
            self.timer.timeout.connect(self.do_convert)
            self.timer.start()
            self.do_convert()


    def setEnabled(self, state):
        self.collapse_button.setEnabled(state)
        self.invert_button.setEnabled(state)
        self.currency_from.setEnabled(state)
        self.currency_to.setEnabled(state)
        self.amount.setEnabled(state)
        self.conversion_result.setEnabled(state)

    def invert_currencies(self):
        self.swapping = True
        idx_from = self.currency_from.nativeWidget().currentIndex()
        self.currency_from.nativeWidget().setCurrentIndex(self.currency_to.nativeWidget().currentIndex())
        self.currency_to.nativeWidget().setCurrentIndex(idx_from)
        cur = self.currency_from.text()
        self.def_from = cur.mid( cur.length()-4, 3 )
        cur = self.currency_to.text()
        self.def_to = cur.mid( cur.length()-4, 3 )
        self.swapping = False
        self.do_convert()

    def layout_widgets(self):
      # Layout
      if self.grid_layout <> None:
        del self.grid_layout
      self.grid_layout = QGraphicsGridLayout()
      header_layout = QGraphicsLinearLayout()
      header_layout.addItem(self.invert_button)
      header_layout.addItem(self.title_label)
      self.grid_layout.addItem(header_layout, 0, 0, 1, 2)
      #self.grid_layout.addItem(self.collapse_button, 0, 0)
      #self.grid_layout.addItem(self.title_label, 0, 1)
      self.grid_layout.addItem(self.from_label, 1, 0)
      self.grid_layout.addItem(self.currency_from, 1, 1)
      self.grid_layout.addItem(self.to_label, 2, 0)
      self.grid_layout.addItem(self.currency_to, 2, 1)
      self.grid_layout.addItem(self.amount_label, 3, 0)
      self.amount_layout = QGraphicsLinearLayout()
      self.amount_layout.addItem(self.amount)
      self.amount_layout.addItem(self.from_amount_label)
      self.amount_layout.addItem(self.equal_label)
      self.amount_layout.addItem(self.conversion_result)
      self.amount_layout.addItem(self.to_amount_label)
      self.grid_layout.addItem(self.amount_layout, 3, 1)
      self.grid_layout.addItem(self.credits_label, 4, 0, 1, 2)

      self.setLayout(self.grid_layout)

    def currency_changed(self):
      print "CurrencyConverter::currency_changed"
      if self.swapping or not self.applet.nwmon.connected():
        return

      try:
        cur = self.currency_from.text()
        self.def_from = cur.mid( cur.length()-4, 3 )
        #self.def_from = convert_from = self.currency_from.text()[0:3]

        cur = self.currency_to.text()
        self.def_to = cur.mid( cur.length()-4, 3 )
        #self.def_to = convert_to = self.currency_to.text()[0:3]
        self.applet.cfg.writeEntry("default_from", self.def_from)
        self.applet.cfg.writeEntry("default_to", self.def_to)
        self.applet.cfg.sync()
      except RuntimeError:
        print "CurrencyConverter::currency_changed: Regular update."
      self.do_convert()

    def do_convert(self):
        print "CurrencyConverter::do_convert"
        print "CurrencyConverter::do_convert. Update interval:", self.update_interval
        print "Convert from:", self.def_from, "to", self.def_to
        url = "http://quote.yahoo.com/d/quotes.csv?s=%s%s=X&f=l1&e=.csv" % (self.def_from, self.def_to)
        print url
        self.applet.setBusy(True)
        job = KIO.get(KUrl(url), KIO.NoReload, KIO.HideProgressInfo)
        job.warning.connect(self.job_warning)
        job.data.connect(self.job_received)
        job.result.connect(self.job_done)
        self.timer.start() # restart the timer on activity

    def job_warning(self, job, txt, richtxt):
        print "Job warning: '%s' - '%s'" % (txt, richtxt)
        self.applet.showMessage(KIcon("dialog-information"), richtxt, Plasma.ButtonOk)

    def job_done(self, job):
        print "Job done."
        if job.error():
            self.applet.notifier.notify("networkerror", job.errorString())
            print job.errorString()
            #self.applet.showMessage(KIcon("dialog-error"), job.errorString(), Plasma.ButtonOk)
            #print job.errorText()

    def job_received(self, job, data):
      if len(data) > 0:
        amount = self.def_amount
        # NOTE: Check if self.amount.text() is localized and convert it if neccesary.
        # Isn't there a better way of doing this?
        if KGlobal.locale().decimalSymbol() == ",":
          # remove any "."s and replace "," with "."
          # there ought to bet a prettier way to do this
          if amount.contains(","):
            amount = amount.replace(".", "").replace(",", ".")
        print "%f * %f = %f" % (float(amount), float(data), float(data)*float(amount))
        print float(data)*float(amount)
        self.conversion_result.setText(str(float(data)*float(amount)))
        self.from_amount_label.setText(KCurrencyCode(self.def_from).defaultSymbol())
        self.to_amount_label.setText(KCurrencyCode(self.def_to).defaultSymbol())
        #self.from_amount_label.setText(QString.fromUtf8(CURRENCY[str(self.currency_from.text())[0:3]].get_symbol()))
        #self.to_amount_label.setText(QString.fromUtf8(CURRENCY[str(self.currency_to.text())[0:3]].get_symbol()))
        print "Last updated:", KGlobal.locale().formatDateTime(KDateTime.currentLocalDateTime())
        self.last_updated = KGlobal.locale().formatDateTime(KDateTime.currentLocalDateTime())
        #self.last_updated = str(datetime.now().ctime())
        self.credits_label.nativeWidget().setToolTip(str(i18n("Last updated: %s")) % self.last_updated)
        self.applet.setBusy(False)
        print "Data recieved:", data
        self.updated.emit()

    def amount_editing_finished(self):
      print "Amount editing finished"
      self.def_amount = self.amount.text()
      self.applet.cfg.writeEntry("default_amount", self.def_amount)
      self.applet.cfg.sync()
      self.do_convert()

    def font_size(self):
      return Plasma.Theme.defaultTheme().font(Plasma.Theme.DefaultFont).pointSize()

    def fromCurrency(self):
      return KCurrencyCode(self.def_from).defaultSymbol()

    def toCurrency(self):
      return KCurrencyCode(self.def_to).defaultSymbol()

    def fromAmount(self):
      return self.amount.text()

    def toAmount(self):
      return self.conversion_result.text()

    def lastUpdated(self):
      return self.last_updated
コード例 #31
0
ファイル: main.py プロジェクト: selam/ublog
class UBlogApplet(plasmascript.Applet):

    def __init__(self, parent, **kwargs):
        plasmascript.Applet.__init__(self, parent)
        self._layout = None
        self.flash = None
        self.tab_bar = None
        self.ui = None
        self.status_edit = None
        self.scroll_widget = None
        self.tweets_layout = None
        self.main_frame = None
        self.pm = None
        self.consumer = oauth.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
        self.client = oauth.Client(self.consumer)
        self.icon = None
        self.oauth_secret = None
        self.oauth_key = None
        self.history_size = 10
        self.timer = QTimer(self)
        self.history_refresh = 1
        self.tweets_widget = None
        self.message_id = None
        self._wallet_timer = QTimer(self)

    def init(self):
        """
        create interface, this method invoked by plasma it self
        """
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        #
        self.flash = Plasma.FlashingLabel(self.applet)
        self.flash.setAutohide(True)
        self.flash.setMinimumSize(0, 20)
        self.flash.setDuration(2000)
        self.tab_bar = Plasma.TabBar()

        self._layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        self._layout.setSpacing(3)

        flash_layout = QGraphicsLinearLayout(Qt.Horizontal)
        flash_layout.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        fnt = Plasma.Theme.defaultTheme().font(Plasma.Theme.DefaultFont)
        fnt.setBold(True)
        fm = QFontMetrics(fnt)

        self.flash.setFont(fnt)
        self.flash.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        title_layout = QGraphicsLinearLayout(Qt.Vertical)

        flash_layout.addItem(self.flash)
        flash_layout.addItem(title_layout)

        self.main_frame = Plasma.Frame(self.applet)
        m_header_layout = QGraphicsAnchorLayout(self.main_frame)
        m_header_layout.setSpacing(5)

        self.icon = Plasma.IconWidget(self.main_frame)
        self.icon.setIcon(KIcon("user-identity"))
        self.icon.setTextBackgroundColor(QColor())
        icon_size = self.icon.sizeFromIconSize(48)
        self.icon.setMinimumSize(icon_size)
        self.icon.setMaximumSize(icon_size)

        m_header_layout.addAnchor(self.icon, Qt.AnchorVerticalCenter, m_header_layout, Qt.AnchorVerticalCenter)
        m_header_layout.addAnchor(self.icon, Qt.AnchorLeft, m_header_layout, Qt.AnchorLeft)

        status_edit_frame = Plasma.Frame(self.main_frame)
        status_edit_frame.setFrameShadow(Plasma.Frame.Sunken)
        status_edit_layout = QGraphicsLinearLayout(status_edit_frame)
        self.status_edit = Plasma.TextEdit()
        self.status_edit.setPreferredHeight(fm.height() * 4)
        self.status_edit.setEnabled(False)
        status_edit_layout.addItem(self.status_edit)

        edit_pal = self.status_edit.palette()
        m_color_scheme = KColorScheme(QPalette.Active, KColorScheme.View, Plasma.Theme.defaultTheme().colorScheme())
        edit_pal.setColor(QPalette.Text, m_color_scheme.foreground().color())
        self.status_edit.nativeWidget().setPalette(edit_pal)
        self.status_edit.nativeWidget().installEventFilter(self)
        m_header_layout.addAnchor(self.icon, Qt.AnchorRight, status_edit_frame, Qt.AnchorLeft)
        m_header_layout.addAnchors(status_edit_frame, m_header_layout, Qt.Vertical)
        m_header_layout.addAnchor(status_edit_frame, Qt.AnchorRight, m_header_layout, Qt.AnchorRight)
        m_header_layout.activate()
        m_header_layout.setMaximumHeight(m_header_layout.effectiveSizeHint(Qt.PreferredSize).height())

        self.scroll_widget = Plasma.ScrollWidget(self.applet)
        self.tweets_widget = QGraphicsWidget(self.scroll_widget)
        self.scroll_widget.setWidget(self.tweets_widget)
        self.tweets_layout = QGraphicsLinearLayout(Qt.Vertical, self.tweets_widget)
        self.tweets_layout.setSpacing(3)
        self.tweets_layout.addItem(self.main_frame)

        self.tab_bar.addTab(self.trUtf8("Timeline"))
        self.tab_bar.addTab(self.trUtf8("Replies"))
        self.tab_bar.addTab(self.trUtf8("Messages"))

        self._layout.addItem(flash_layout)
        self._layout.addItem(self.tab_bar)
        self._layout.addItem(self.scroll_widget)

        self.applet.setLayout(self._layout)
        self.connect(self.tab_bar, SIGNAL('currentChanged(int)'), self.mode_changed)
        self.connect(self.status_edit, SIGNAL('textChanged()'), self.edit_text_changed)
        self.check_config()

    def check_config(self):       
        if self.pm is None:
            self._wallet_timer.setSingleShot(True)
            self._wallet_timer.setInterval(1000)            
            self.connect(self._wallet_timer, SIGNAL("timeout()"), self.open_wallet);
            self._wallet_timer.start()
            return None
        
        self.oauth_secret = unicode(self.pm.readPassword("twitter_secret")[1])
        self.oauth_key = unicode(self.pm.readPassword("twitter_token")[1])
        self.history_size = int(self.pm.readEntry("historySize")[1])
        self.history_refresh = int(self.pm.readEntry("historyRefresh")[1])

        if self.history_size == '':
            self.history_size = 10

        if self.history_refresh is None or self.history_refresh == '':
            self.history_refresh = 5

        if self.oauth_key == '' or self.oauth_secret == '':
            self.authenticate()
        else:
            self.status_edit.setEnabled(True)
            self.connect(self.timer, SIGNAL('timeout()'), self.update)
            self.update()
            self.timer.start(self.history_refresh * 60 * 1000)

    def open_wallet(self):
        if self.view() is None:
            self._wallet_timer.start()
            return None
        if self.view().winId() is None:
            self._wallet_timer.start()
            return None
        
        self.pm = PasswordManager(self.view().winId())
        self.check_config()
        

    def edit_text_changed(self):
        remaining_char = 140 - self.status_edit.nativeWidget().toPlainText().length()
        self.flash.flash(unicode(self.trUtf8("%s character left", "%s character left")) % remaining_char, 2000)

    def createConfigurationInterface(self, dialog):
        """
            create configuration settings for user parameters
        """
        self.connect(dialog, SIGNAL('applyClicked()'), self.config_accepted)
        self.connect(dialog, SIGNAL('okClicked()'), self.config_accepted)
        widget = QWidget(dialog)
        self.ui = uic.loadUi(self.package().filePath('ui', 'configuration.ui'), widget)
        history_size = self.pm.readEntry("historySize")[1]
        history_refresh = self.pm.readEntry("historyRefresh")[1]
        if history_size:
            self.ui.historySizeSpinBox.setValue(int(str(history_size)))
        if history_refresh:
            self.ui.historyRefreshSpinBox.setValue(int(str(history_refresh)))
        dialog.addPage(widget, self.trUtf8("General"), "view-pim-journal")

    def config_accepted(self):
        """
            we must update timer object after these settings changed
        """
        self.pm.writeEntry("historyRefresh", str(self.ui.historyRefreshSpinBox.value()))
        self.pm.writeEntry("historySize", str(self.ui.historySizeSpinBox.value()))
        self.history_size = str(self.ui.historyRefreshSpinBox.value())
        self.history_refresh = int(self.ui.historySizeSpinBox.value())

        self.status_edit.setEnabled(True)
        self.timer.stop()
        self.timer.start(self.history_refresh * 60 * 1000)
        self.update()

    def mode_changed(self):
        self.flash.flash(self.trUtf8("Refreshing timeline..."))
        self.timer.stop()
        self.update()
        self.timer.start(int(self.history_refresh) * 60 * 1000)

    def update(self):
        self.flash.flash(self.trUtf8("Refreshing timeline..."))
        current_idx = self.tab_bar.currentIndex()
        if current_idx == 0:
            self.__update_timeline()
        elif current_idx == 1:
            self.__update_replies()
        else:
            self.__update_messages()

    def __make_rest_calls(self, url, user=True):
        token = oauth.Token(self.oauth_key, self.oauth_secret)
        client = oauth.Client(self.consumer, token=token)
        resp, content = client.request(url+"?count="+str(self.history_size))
        self.tweets_widget.prepareGeometryChange()
        if resp['status'] == '200':
            # we must clear all tweets widgets before
            for i in xrange(0, self.tweets_layout.count()-1):
                widget = self.tweets_layout.itemAt(1)
                if isinstance(widget, TweetWidget):
                    widget.deleteLater()
                    self.tweets_layout.removeAt(1)
            tweets = json.loads(content)
            for tweet in tweets:
                widget = TweetWidget(self.tweets_widget)
                widget.set_data(tweet, user=user)
                self.connect(widget, SIGNAL('reply(QString, QString)'), self.reply)
                self.connect(widget, SIGNAL('profile(QString)'), self.profile)
                self.connect(widget, SIGNAL('retweet(QString)'), self.retweet)
                self.connect(widget, SIGNAL('favorite(QString, bool)'), self.favorite)
                self.tweets_layout.addItem(widget)
            self.layout()

    def __update_timeline(self):
        self.__make_rest_calls("https://api.twitter.com/1.1/statuses/home_timeline.json")

    def __update_messages(self):
        self.__make_rest_calls("https://api.twitter.com/1.1/direct_messages.json", user=False)

    def __update_replies(self):
        self.__make_rest_calls("https://api.twitter.com/1.1/statuses/mentions_timeline.json")

    def reply(self, message_id, authorname):
        self.status_edit.setText(authorname + ' ')
        self.message_id = message_id

    def profile(self, user):
        KToolInvocation.invokeBrowser("https://twitter.com/%s" % (user,))

    def __make_post_calls(self, url, body):
        self.timer.stop()
        token = oauth.Token(self.oauth_key, self.oauth_secret)
        client = oauth.Client(self.consumer, token=token)
        resp, content = client.request(url,
                                       method='POST', body=body)
        if resp['status'] == '200':
            self.update()
        self.timer.start()
	
    def retweet(self, message_id):
        self.flash.flash(self.trUtf8("Retweetting..."))
        self.__make_post_calls("https://api.twitter.com/1.1/statuses/retweet/"+str(message_id)+".json",
                               body='id='+str(message_id))

    def favorite(self, message_id, add):
        if add:            
            self.flash.flash(self.trUtf8("Adding favorites..."))
        else:
            self.flash.flash(self.trUtf8("Removing from favorites..."))
        self.__make_post_calls("https://api.twitter.com/1.1/favorites/"+("create" if add else "destroy")+".json",
                               body='id='+str(message_id))

    def update_status(self):
        tweet = unicode(self.status_edit.nativeWidget().toPlainText())
        self.status_edit.setText(' ')
        self.flash.flash(self.trUtf8("Tweet sending..."))
        self.setBusy(True)
        body = 'status='+tweet
        if tweet.startswith('@') and self.message_id is not None:
            body += '&in_reply_to_status_id='+str(self.message_id)
        self.message_id = None
        self.__make_post_calls("https://api.twitter.com/1.1/statuses/update.json",
                               body=body)
	self.setBusy(False)

    def eventFilter(self, obj, event):
        if isinstance(obj, KTextEdit):
            if event.type() == QEvent.KeyPress:
                key_event = QKeyEvent(event)
                key = key_event.key()
                if (key_event.modifiers() == Qt.ControlModifier) and (key == Qt.Key_Enter or key == Qt.Key_Return):
                    self.update_status()
                    return True

                safe_keys = [Qt.Key_Delete, Qt.Key_Backspace,
                             Qt.Key_Up, Qt.Key_Down,
                             Qt.Key_Right, Qt.Key_Left,
                             Qt.Key_Home, Qt.Key_End]

                if key not in safe_keys:
                    if self.status_edit.nativeWidget().toPlainText().length() >= 140:
                        return True
            return False

        elif isinstance(obj, KTabBar) and event.type() == QEvent.MouseButtonPress:
            self.scroll_widget.ensureItemVisible(self.main_frame)
            self.status_edit.setFocus()
            return False
        else:
            return self.applet.eventFilter(obj, event)

    def authenticate(self, loop_count):
        if loop_count >= 5:
            return self.quit()
        loop_count += 1
        resp, content = self.client.request("https://twitter.com/oauth/request_token", "GET")
        if resp['status'] != '200':
            raise Exception("Invalid response %s." % resp['status'])
        request_token = dict(urlparse.parse_qsl(content))

        KToolInvocation.invokeBrowser("https://twitter.com/oauth/authorize?oauth_token=%s&oauth_callback=oob" % (
                                                                                request_token['oauth_token']))

        dialog = KInputDialog.getText(self.trUtf8("PIN"), self.trUtf8("Enter the PIN received from Twitter:"))
        if dialog[1] is True and not dialog[0].isEmpty():
            token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
            token.set_verifier(str(dialog[0]))
            client = oauth.Client(self.consumer, token)
            resp, content = client.request("https://twitter.com/oauth/access_token", "POST")
            if resp['status'] == '200':
                access_token = dict(urlparse.parse_qsl(content))
                self.oauth_secret = access_token['oauth_token_secret']
                self.oauth_key = access_token['oauth_token']
                self.pm.writePassword("twitter_secret", self.oauth_secret)
                self.pm.writePassword("twitter_token", self.oauth_key)
            else:
                self.authenticate(loop_count)
        else:
            self.quit()

    def quit(self):
        self.close()
コード例 #32
0
class OWHierarchicalClustering(widget.OWWidget):
    name = "Hierarchical Clustering"
    description = ("Hierarchical clustering based on distance matrix, and "
                   "a dendrogram viewer.")
    icon = "icons/HierarchicalClustering.svg"
    priority = 2100

    inputs = [("Distances", Orange.misc.DistMatrix, "set_distances")]

    outputs = [("Selected Data", Orange.data.Table),
               ("Other Data", Orange.data.Table)]

    #: Selected linkage
    linkage = settings.Setting(1)
    #: Index of the selected annotation item (variable, ...)
    annotation_idx = settings.Setting(0)
    #: Selected tree pruning (none/max depth)
    pruning = settings.Setting(0)
    #: Maximum depth when max depth pruning is selected
    max_depth = settings.Setting(10)

    #: Selected cluster selection method (none, cut distance, top n)
    selection_method = settings.Setting(0)
    #: Cut height ratio wrt root height
    cut_ratio = settings.Setting(75.0)
    #: Number of top clusters to select
    top_n = settings.Setting(3)

    append_clusters = settings.Setting(True)
    cluster_role = settings.Setting(2)
    cluster_name = settings.Setting("Cluster")
    autocommit = settings.Setting(False)

    #: Cluster variable domain role
    AttributeRole, ClassRole, MetaRole = 0, 1, 2

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

        self.matrix = None
        self.items = None
        self.linkmatrix = None
        self.root = None
        self._displayed_root = None
        self.cutoff_height = 0.0

        gui.comboBox(gui.widgetBox(self.controlArea, "Linkage"),
                     self, "linkage", items=LINKAGE,
                     callback=self._invalidate_clustering)

        box = gui.widgetBox(self.controlArea, "Annotation")
        self.label_cb = gui.comboBox(
            box, self, "annotation_idx", callback=self._update_labels)

        self.label_cb.setModel(itemmodels.VariableListModel())
        self.label_cb.model()[:] = ["None", "Enumeration"]

        box = gui.radioButtons(
            self.controlArea, self, "pruning", box="Pruning",
            callback=self._invalidate_pruning
        )
        grid = QGridLayout()
        box.layout().addLayout(grid)
        grid.addWidget(
            gui.appendRadioButton(box, "None", addToLayout=False),
            0, 0
        )
        self.max_depth_spin = gui.spin(
            box, self, "max_depth", minv=1, maxv=100,
            callback=self._invalidate_pruning,
            keyboardTracking=False
        )

        grid.addWidget(
            gui.appendRadioButton(box, "Max depth", addToLayout=False),
            1, 0)
        grid.addWidget(self.max_depth_spin, 1, 1)

        box = gui.radioButtons(
            self.controlArea, self, "selection_method",
            box="Selection",
            callback=self._selection_method_changed)

        grid = QGridLayout()
        box.layout().addLayout(grid)
        grid.addWidget(
            gui.appendRadioButton(box, "Manual", addToLayout=False),
            0, 0
        )
        grid.addWidget(
            gui.appendRadioButton(box, "Height ratio", addToLayout=False),
            1, 0
        )
        self.cut_ratio_spin = gui.spin(
            box, self, "cut_ratio", 0, 100, step=1e-1, spinType=float,
            callback=self._selection_method_changed
        )
        self.cut_ratio_spin.setSuffix("%")

        grid.addWidget(self.cut_ratio_spin, 1, 1)

        grid.addWidget(
            gui.appendRadioButton(box, "Top N", addToLayout=False),
            2, 0
        )
        self.top_n_spin = gui.spin(box, self, "top_n", 1, 20,
                                   callback=self._selection_method_changed)
        grid.addWidget(self.top_n_spin, 2, 1)
        box.layout().addLayout(grid)

        self.controlArea.layout().addStretch()

        box = gui.widgetBox(self.controlArea, "Output")
        gui.checkBox(box, self, "append_clusters", "Append cluster IDs",
                     callback=self._invalidate_output)

        ibox = gui.indentedBox(box)
        name_edit = gui.lineEdit(ibox, self, "cluster_name")
        name_edit.editingFinished.connect(self._invalidate_output)

        cb = gui.comboBox(
            ibox, self, "cluster_role", callback=self._invalidate_output,
            items=["Attribute",
                   "Class variable",
                   "Meta variable"]
        )
        form = QFormLayout(
            fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow,
            labelAlignment=Qt.AlignLeft,
            spacing=8
        )
        form.addRow("Name", name_edit)
        form.addRow("Place", cb)

        ibox.layout().addSpacing(5)
        ibox.layout().addLayout(form)
        ibox.layout().addSpacing(5)

        gui.auto_commit(box, self, "autocommit", "Send data", "Auto send is on",
                        box=False)

        self.scene = QGraphicsScene()
        self.view = QGraphicsView(
            self.scene,
            horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
            alignment=Qt.AlignLeft | Qt.AlignVCenter
        )

        def axis_view(orientation):
            ax = pg.AxisItem(orientation=orientation, maxTickLength=7)
            scene = QGraphicsScene()
            scene.addItem(ax)
            view = QGraphicsView(
                scene,
                horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
                verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
                alignment=Qt.AlignLeft | Qt.AlignVCenter
            )
            view.setFixedHeight(ax.size().height())
            ax.line = SliderLine(orientation=Qt.Horizontal,
                                 length=ax.size().height())
            scene.addItem(ax.line)
            return view, ax

        self.top_axis_view, self.top_axis = axis_view("top")
        self.mainArea.layout().setSpacing(1)
        self.mainArea.layout().addWidget(self.top_axis_view)
        self.mainArea.layout().addWidget(self.view)
        self.bottom_axis_view, self.bottom_axis = axis_view("bottom")
        self.mainArea.layout().addWidget(self.bottom_axis_view)

        self._main_graphics = QGraphicsWidget()
        self._main_layout = QGraphicsLinearLayout(Qt.Horizontal)
        self._main_layout.setSpacing(1)

        self._main_graphics.setLayout(self._main_layout)
        self.scene.addItem(self._main_graphics)

        self.dendrogram = DendrogramWidget()
        self.dendrogram.setSizePolicy(QSizePolicy.MinimumExpanding,
                                      QSizePolicy.MinimumExpanding)
        self.dendrogram.selectionChanged.connect(self._invalidate_output)
        self.dendrogram.selectionEdited.connect(self._selection_edited)

        fm = self.fontMetrics()
        self.dendrogram.setContentsMargins(
            5, fm.lineSpacing() / 2,
            5, fm.lineSpacing() / 2
        )
        self.labels = GraphicsSimpleTextList()
        self.labels.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.labels.setAlignment(Qt.AlignLeft)
        self.labels.setMaximumWidth(200)
        self.labels.layout().setSpacing(0)

        self._main_layout.addItem(self.dendrogram)
        self._main_layout.addItem(self.labels)

        self._main_layout.setAlignment(
            self.dendrogram, Qt.AlignLeft | Qt.AlignVCenter)
        self._main_layout.setAlignment(
            self.labels, Qt.AlignLeft | Qt.AlignVCenter)

        self.view.viewport().installEventFilter(self)
        self.top_axis_view.viewport().installEventFilter(self)
        self.bottom_axis_view.viewport().installEventFilter(self)
        self._main_graphics.installEventFilter(self)

        self.cut_line = SliderLine(self.dendrogram,
                                   orientation=Qt.Horizontal)
        self.cut_line.valueChanged.connect(self._dendrogram_slider_changed)
        self.cut_line.hide()

        self.bottom_axis.line.valueChanged.connect(self._axis_slider_changed)
        self.top_axis.line.valueChanged.connect(self._axis_slider_changed)
        self.dendrogram.geometryChanged.connect(self._dendrogram_geom_changed)
        self._set_cut_line_visible(self.selection_method == 1)

    def set_distances(self, matrix):
        self.matrix = matrix
        self._invalidate_clustering()
        self._set_items(matrix.row_items if matrix is not None else None)

    def _set_items(self, items):
        self.items = items
        if items is None:
            self.label_cb.model()[:] = ["None", "Enumeration"]
        elif isinstance(items, Orange.data.Table):
            vars = list(items.domain)
            self.label_cb.model()[:] = ["None", "Enumeration"] + vars
        elif isinstance(items, list) and \
                all(isinstance(var, Orange.data.Variable) for var in items):
            self.label_cb.model()[:] = ["None", "Enumeration", "Name"]
        else:
            self.label_cb.model()[:] = ["None", "Enumeration"]
        self.annotation_idx = min(self.annotation_idx,
                                  len(self.label_cb.model()) - 1)

    def handleNewSignals(self):
        self._update_labels()

    def _clear_plot(self):
        self.labels.set_labels([])
        self.dendrogram.set_root(None)

    def _set_displayed_root(self, root):
        self._clear_plot()
        self._displayed_root = root
        self.dendrogram.set_root(root)

        self._update_labels()

        self._main_graphics.resize(
            self._main_graphics.size().width(),
            self._main_graphics.sizeHint(Qt.PreferredSize).height()
        )
        self._main_graphics.layout().activate()

    def _update(self):
        self._clear_plot()

        distances = self.matrix

        if distances is not None:
            # Convert to flat upper triangular distances
            i, j = numpy.triu_indices(distances.X.shape[0], k=1)
            distances = distances.X[i, j]

            method = LINKAGE[self.linkage].lower()
            Z = scipy.cluster.hierarchy.linkage(
                distances, method=method
            )
            tree = tree_from_linkage(Z)
            self.linkmatrix = Z
            self.root = tree

            self.top_axis.setRange(tree.value.height, 0.0)
            self.bottom_axis.setRange(tree.value.height, 0.0)

            if self.pruning:
                self._set_displayed_root(prune(tree, level=self.max_depth))
            else:
                self._set_displayed_root(tree)
        else:
            self.linkmatrix = None
            self.root = None
            self._set_displayed_root(None)

        self._apply_selection()

    def _update_labels(self):
        labels = []
        if self.root and self._displayed_root:
            indices = [leaf.value.index for leaf in leaves(self.root)]

            if self.annotation_idx == 0:
                labels = []
            elif self.annotation_idx == 1:
                labels = [str(i) for i in indices]
            elif isinstance(self.items, Orange.data.Table):
                var = self.label_cb.model()[self.annotation_idx]
                col = self.items[:, var]
                labels = [var.repr_val(next(iter(row))) for row in col]
                labels = [labels[idx] for idx in indices]
            else:
                labels = []

            if labels and self._displayed_root is not self.root:
                joined = leaves(self._displayed_root)
                labels = [", ".join(labels[leaf.value.first: leaf.value.last])
                          for leaf in joined]

        self.labels.set_labels(labels)
        self.labels.setMinimumWidth(1 if labels else -1)

    def _invalidate_clustering(self):
        self._update()
        self._update_labels()

    def _invalidate_output(self):
        self.commit()

    def _invalidate_pruning(self):
        if self.root:
            selection = self.dendrogram.selected_nodes()
            ranges = [node.value.range for node in selection]
            if self.pruning:
                self._set_displayed_root(
                    prune(self.root, level=self.max_depth))
            else:
                self._set_displayed_root(self.root)
            selected = [node for node in preorder(self._displayed_root)
                        if node.value.range in ranges]

            self.dendrogram.set_selected_clusters(selected)

        self._apply_selection()

    def commit(self):
        items = getattr(self.matrix, "items", self.items)
        if not items:
            # nothing to commit
            return

        selection = self.dendrogram.selected_nodes()
        selection = sorted(selection, key=lambda c: c.value.first)

        indices = [leaf.value.index for leaf in leaves(self.root)]

        maps = [indices[node.value.first:node.value.last]
                for node in selection]

        selected_indices = list(chain(*maps))
        unselected_indices = sorted(set(range(self.root.value.last)) -
                                    set(selected_indices))

        selected = [items[k] for k in selected_indices]
        unselected = [items[k] for k in unselected_indices]

        if not selected:
            self.send("Selected Data", None)
            self.send("Other Data", None)
            return
        selected_data = unselected_data = None

        if isinstance(items, Orange.data.Table):
            c = numpy.zeros(len(items))

            for i, indices in enumerate(maps):
                c[indices] = i
            c[unselected_indices] = len(maps)

            mask = c != len(maps)

            if self.append_clusters:
                clust_var = Orange.data.DiscreteVariable(
                    str(self.cluster_name),
                    values=["Cluster {}".format(i + 1)
                            for i in range(len(maps))] +
                           ["Other"], ordered=True
                )
                data, domain = items, items.domain

                attrs = domain.attributes
                class_ = domain.class_vars
                metas = domain.metas

                if self.cluster_role == self.AttributeRole:
                    attrs = attrs + (clust_var,)
                elif self.cluster_role == self.ClassRole:
                    class_ = class_ + (clust_var,)
                elif self.cluster_role == self.MetaRole:
                    metas = metas + (clust_var,)

                domain = Orange.data.Domain(attrs, class_, metas)
                data = Orange.data.Table(domain, data)
                data.get_column_view(clust_var)[0][:] = c
            else:
                data = items

            if selected:
                selected_data = data[mask]
            if unselected:
                unselected_data = data[~mask]

        self.send("Selected Data", selected_data)
        self.send("Other Data", unselected_data)

    def sizeHint(self):
        return QSize(800, 500)

    def eventFilter(self, obj, event):
        if obj is self.view.viewport() and event.type() == QEvent.Resize:
            width = self.view.viewport().width() - 2
            self._main_graphics.setMaximumWidth(width)
            self._main_graphics.setMinimumWidth(width)
            self._main_graphics.layout().activate()
        elif event.type() == QEvent.MouseButtonPress and \
                (obj is self.top_axis_view.viewport() or
                 obj is self.bottom_axis_view.viewport()):
            self.selection_method = 1
            # Map click point to cut line local coordinates
            pos = self.top_axis_view.mapToScene(event.pos())
            cut = self.top_axis.line.mapFromScene(pos)
            self.top_axis.line.setValue(cut.x())
            # update the line visibility, output, ...
            self._selection_method_changed()

        return super().eventFilter(obj, event)

    def _dendrogram_geom_changed(self):
        pos = self.dendrogram.pos_at_height(self.cutoff_height)
        geom = self.dendrogram.geometry()
        crect = self.dendrogram.contentsRect()

        self._set_slider_value(pos.x(), geom.width())
        self.cut_line.setLength(geom.height())

        self.top_axis.resize(crect.width(), self.top_axis.height())
        self.top_axis.setPos(geom.left() + crect.left(), 0)
        self.top_axis.line.setPos(self.cut_line.scenePos().x(), 0)

        self.bottom_axis.resize(crect.width(), self.bottom_axis.height())
        self.bottom_axis.setPos(geom.left() + crect.left(), 0)
        self.bottom_axis.line.setPos(self.cut_line.scenePos().x(), 0)

        geom = self._main_graphics.geometry()
        assert geom.topLeft() == QPointF(0, 0)
        self.scene.setSceneRect(geom)

        geom.setHeight(self.top_axis.size().height())

        self.top_axis.scene().setSceneRect(geom)
        self.bottom_axis.scene().setSceneRect(geom)

    def _axis_slider_changed(self, value):
        self.cut_line.setValue(value)

    def _dendrogram_slider_changed(self, value):
        p = QPointF(value, 0)
        cl_height = self.dendrogram.height_at(p)

        self.set_cutoff_height(cl_height)

        # Sync the cut positions between the dendrogram and the axis.
        self._set_slider_value(value, self.dendrogram.size().width())

    def _set_slider_value(self, value, span):
        with blocked(self.cut_line):
            self.cut_line.setValue(value)
            self.cut_line.setRange(0, span)

        with blocked(self.top_axis.line):
            self.top_axis.line.setValue(value)
            self.top_axis.line.setRange(0, span)

        with blocked(self.bottom_axis.line):
            self.bottom_axis.line.setValue(value)
            self.bottom_axis.line.setRange(0, span)

    def set_cutoff_height(self, height):
        self.cutoff_height = height
        if self.root:
            self.cut_ratio = 100 * height / self.root.value.height
        self.select_max_height(height)

    def _set_cut_line_visible(self, visible):
        self.cut_line.setVisible(visible)
        self.top_axis.line.setVisible(visible)
        self.bottom_axis.line.setVisible(visible)

    def select_top_n(self, n):
        root = self._displayed_root
        if root:
            clusters = top_clusters(root, n)
            self.dendrogram.set_selected_clusters(clusters)

    def select_max_height(self, height):
        root = self._displayed_root
        if root:
            clusters = clusters_at_height(root, height)
            self.dendrogram.set_selected_clusters(clusters)

    def _selection_method_changed(self):
        self._set_cut_line_visible(self.selection_method == 1)
        if self.root:
            self._apply_selection()

    def _apply_selection(self):
        if not self.root:
            return

        if self.selection_method == 0:
            pass
        elif self.selection_method == 1:
            height = self.cut_ratio * self.root.value.height / 100
            self.set_cutoff_height(height)
            pos = self.dendrogram.pos_at_height(height)
            self._set_slider_value(pos.x(), self.dendrogram.size().width())
        elif self.selection_method == 2:
            self.select_top_n(self.top_n)

    def _selection_edited(self):
        # Selection was edited by clicking on a cluster in the
        # dendrogram view.
        self.selection_method = 0
        self._selection_method_changed()
コード例 #33
0
class OWHierarchicalClustering(widget.OWWidget):
    name = "Hierarchical Clustering"
    description = ("Hierarchical clustering based on distance matrix, and "
                   "a dendrogram viewer.")
    icon = "icons/HierarchicalClustering.svg"
    priority = 2100

    inputs = [("Distances", Orange.misc.DistMatrix, "set_distances")]

    outputs = [("Selected Data", Orange.data.Table),
               ("Other Data", Orange.data.Table)]

    #: Selected linkage
    linkage = settings.Setting(1)
    #: Index of the selected annotation item (variable, ...)
    annotation_idx = settings.Setting(0)
    #: Selected tree pruning (none/max depth)
    pruning = settings.Setting(0)
    #: Maximum depth when max depth pruning is selected
    max_depth = settings.Setting(10)

    #: Selected cluster selection method (none, cut distance, top n)
    selection_method = settings.Setting(0)
    #: Cut height ratio wrt root height
    cut_ratio = settings.Setting(75.0)
    #: Number of top clusters to select
    top_n = settings.Setting(3)

    append_clusters = settings.Setting(True)
    cluster_role = settings.Setting(2)
    cluster_name = settings.Setting("Cluster")
    autocommit = settings.Setting(False)

    #: Cluster variable domain role
    AttributeRole, ClassRole, MetaRole = 0, 1, 2

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

        self.matrix = None
        self.items = None
        self.linkmatrix = None
        self.root = None
        self._displayed_root = None
        self.cutoff_height = 0.0
        self._invalidated = False

        gui.comboBox(gui.widgetBox(self.controlArea, "Linkage"),
                     self,
                     "linkage",
                     items=LINKAGE,
                     callback=self._invalidate_clustering)

        box = gui.widgetBox(self.controlArea, "Annotation")
        self.label_cb = gui.comboBox(box,
                                     self,
                                     "annotation_idx",
                                     callback=self._update_labels)

        self.label_cb.setModel(itemmodels.VariableListModel())
        self.label_cb.model()[:] = ["None", "Enumeration"]

        box = gui.radioButtons(self.controlArea,
                               self,
                               "pruning",
                               box="Pruning",
                               callback=self._invalidate_pruning)
        grid = QGridLayout()
        box.layout().addLayout(grid)
        grid.addWidget(gui.appendRadioButton(box, "None", addToLayout=False),
                       0, 0)
        self.max_depth_spin = gui.spin(box,
                                       self,
                                       "max_depth",
                                       minv=1,
                                       maxv=100,
                                       callback=self._invalidate_pruning,
                                       keyboardTracking=False)

        grid.addWidget(
            gui.appendRadioButton(box, "Max depth", addToLayout=False), 1, 0)
        grid.addWidget(self.max_depth_spin, 1, 1)

        box = gui.radioButtons(self.controlArea,
                               self,
                               "selection_method",
                               box="Selection",
                               callback=self._selection_method_changed)

        grid = QGridLayout()
        box.layout().addLayout(grid)
        grid.addWidget(gui.appendRadioButton(box, "Manual", addToLayout=False),
                       0, 0)
        grid.addWidget(
            gui.appendRadioButton(box, "Height ratio", addToLayout=False), 1,
            0)
        self.cut_ratio_spin = gui.spin(box,
                                       self,
                                       "cut_ratio",
                                       0,
                                       100,
                                       step=1e-1,
                                       spinType=float,
                                       callback=self._selection_method_changed)
        self.cut_ratio_spin.setSuffix("%")

        grid.addWidget(self.cut_ratio_spin, 1, 1)

        grid.addWidget(gui.appendRadioButton(box, "Top N", addToLayout=False),
                       2, 0)
        self.top_n_spin = gui.spin(box,
                                   self,
                                   "top_n",
                                   1,
                                   20,
                                   callback=self._selection_method_changed)
        grid.addWidget(self.top_n_spin, 2, 1)
        box.layout().addLayout(grid)

        self.controlArea.layout().addStretch()

        box = gui.widgetBox(self.controlArea, "Output")
        gui.checkBox(box,
                     self,
                     "append_clusters",
                     "Append cluster IDs",
                     callback=self._invalidate_output)

        ibox = gui.indentedBox(box)
        name_edit = gui.lineEdit(ibox, self, "cluster_name")
        name_edit.editingFinished.connect(self._invalidate_output)

        cb = gui.comboBox(
            ibox,
            self,
            "cluster_role",
            callback=self._invalidate_output,
            items=["Attribute", "Class variable", "Meta variable"])
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow,
                           labelAlignment=Qt.AlignLeft,
                           spacing=8)
        form.addRow("Name", name_edit)
        form.addRow("Place", cb)

        ibox.layout().addSpacing(5)
        ibox.layout().addLayout(form)
        ibox.layout().addSpacing(5)

        cb = gui.checkBox(box, self, "autocommit", "Commit automatically")
        b = gui.button(box, self, "Commit", callback=self.commit, default=True)
        gui.setStopper(self, b, cb, "_invalidated", callback=self.commit)

        self.scene = QGraphicsScene()
        self.view = QGraphicsView(
            self.scene,
            horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
            alignment=Qt.AlignLeft | Qt.AlignVCenter)

        def axis_view(orientation):
            ax = pg.AxisItem(orientation=orientation, maxTickLength=7)
            scene = QGraphicsScene()
            scene.addItem(ax)
            view = QGraphicsView(
                scene,
                horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
                verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
                alignment=Qt.AlignLeft | Qt.AlignVCenter)
            view.setFixedHeight(ax.size().height())
            ax.line = SliderLine(orientation=Qt.Horizontal,
                                 length=ax.size().height())
            scene.addItem(ax.line)
            return view, ax

        self.top_axis_view, self.top_axis = axis_view("top")
        self.mainArea.layout().setSpacing(1)
        self.mainArea.layout().addWidget(self.top_axis_view)
        self.mainArea.layout().addWidget(self.view)
        self.bottom_axis_view, self.bottom_axis = axis_view("bottom")
        self.mainArea.layout().addWidget(self.bottom_axis_view)

        self._main_graphics = QGraphicsWidget()
        self._main_layout = QGraphicsLinearLayout(Qt.Horizontal)
        self._main_layout.setSpacing(1)

        self._main_graphics.setLayout(self._main_layout)
        self.scene.addItem(self._main_graphics)

        self.dendrogram = DendrogramWidget()
        self.dendrogram.setSizePolicy(QSizePolicy.MinimumExpanding,
                                      QSizePolicy.MinimumExpanding)
        self.dendrogram.selectionChanged.connect(self._invalidate_output)
        self.dendrogram.selectionEdited.connect(self._selection_edited)

        fm = self.fontMetrics()
        self.dendrogram.setContentsMargins(5,
                                           fm.lineSpacing() / 2, 5,
                                           fm.lineSpacing() / 2)
        self.labels = GraphicsSimpleTextList()
        self.labels.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.labels.setAlignment(Qt.AlignLeft)
        self.labels.setMaximumWidth(200)
        self.labels.layout().setSpacing(0)

        self._main_layout.addItem(self.dendrogram)
        self._main_layout.addItem(self.labels)

        self._main_layout.setAlignment(self.dendrogram,
                                       Qt.AlignLeft | Qt.AlignVCenter)
        self._main_layout.setAlignment(self.labels,
                                       Qt.AlignLeft | Qt.AlignVCenter)

        self.view.viewport().installEventFilter(self)
        self.top_axis_view.viewport().installEventFilter(self)
        self.bottom_axis_view.viewport().installEventFilter(self)
        self._main_graphics.installEventFilter(self)

        self.cut_line = SliderLine(self.dendrogram, orientation=Qt.Horizontal)
        self.cut_line.valueChanged.connect(self._dendrogram_slider_changed)
        self.cut_line.hide()

        self.bottom_axis.line.valueChanged.connect(self._axis_slider_changed)
        self.top_axis.line.valueChanged.connect(self._axis_slider_changed)
        self.dendrogram.geometryChanged.connect(self._dendrogram_geom_changed)
        self._set_cut_line_visible(self.selection_method == 1)

    def set_distances(self, matrix):
        self.matrix = matrix
        self._invalidate_clustering()
        self._set_items(matrix.row_items if matrix is not None else None)

    def _set_items(self, items):
        self.items = items
        if items is None:
            self.label_cb.model()[:] = ["None", "Enumeration"]
        elif isinstance(items, Orange.data.Table):
            vars = list(items.domain)
            self.label_cb.model()[:] = ["None", "Enumeration"] + vars
        elif isinstance(items, list) and \
                all(isinstance(var, Orange.data.Variable) for var in items):
            self.label_cb.model()[:] = ["None", "Enumeration", "Name"]
        else:
            self.label_cb.model()[:] = ["None", "Enumeration"]
        self.annotation_idx = min(self.annotation_idx,
                                  len(self.label_cb.model()) - 1)

    def handleNewSignals(self):
        self._update_labels()

    def _clear_plot(self):
        self.labels.set_labels([])
        self.dendrogram.set_root(None)

    def _set_displayed_root(self, root):
        self._clear_plot()
        self._displayed_root = root
        self.dendrogram.set_root(root)

        self._update_labels()

        self._main_graphics.resize(
            self._main_graphics.size().width(),
            self._main_graphics.sizeHint(Qt.PreferredSize).height())
        self._main_graphics.layout().activate()

    def _update(self):
        self._clear_plot()

        distances = self.matrix

        if distances is not None:
            # Convert to flat upper triangular distances
            i, j = numpy.triu_indices(distances.X.shape[0], k=1)
            distances = distances.X[i, j]

            method = LINKAGE[self.linkage].lower()
            Z = scipy.cluster.hierarchy.linkage(distances, method=method)
            tree = tree_from_linkage(Z)
            self.linkmatrix = Z
            self.root = tree

            self.top_axis.setRange(tree.value.height, 0.0)
            self.bottom_axis.setRange(tree.value.height, 0.0)

            if self.pruning:
                self._set_displayed_root(prune(tree, level=self.max_depth))
            else:
                self._set_displayed_root(tree)
        else:
            self.linkmatrix = None
            self.root = None
            self._set_displayed_root(None)

        self._apply_selection()

    def _update_labels(self):
        labels = []
        if self.root and self._displayed_root:
            indices = [leaf.value.index for leaf in leaves(self.root)]

            if self.annotation_idx == 0:
                labels = []
            elif self.annotation_idx == 1:
                labels = [str(i) for i in indices]
            elif isinstance(self.items, Orange.data.Table):
                var = self.label_cb.model()[self.annotation_idx]
                col = self.items[:, var]
                labels = [var.repr_val(next(iter(row))) for row in col]
                labels = [labels[idx] for idx in indices]
            else:
                labels = []

            if labels and self._displayed_root is not self.root:
                joined = leaves(self._displayed_root)
                labels = [
                    ", ".join(labels[leaf.value.first:leaf.value.last])
                    for leaf in joined
                ]

        self.labels.set_labels(labels)
        self.labels.setMinimumWidth(1 if labels else -1)

    def _invalidate_clustering(self):
        self._update()
        self._update_labels()

    def _invalidate_output(self):
        self._invalidated = True
        if self.autocommit:
            self.commit()

    def _invalidate_pruning(self):
        if self.root:
            selection = self.dendrogram.selected_nodes()
            ranges = [node.value.range for node in selection]
            if self.pruning:
                self._set_displayed_root(prune(self.root,
                                               level=self.max_depth))
            else:
                self._set_displayed_root(self.root)
            selected = [
                node for node in preorder(self._displayed_root)
                if node.value.range in ranges
            ]

            self.dendrogram.set_selected_clusters(selected)

        self._apply_selection()

    def commit(self):
        self._invalidated = False

        items = getattr(self.matrix, "items", self.items)
        if not items:
            # nothing to commit
            return

        selection = self.dendrogram.selected_nodes()
        selection = sorted(selection, key=lambda c: c.value.first)

        indices = [leaf.value.index for leaf in leaves(self.root)]

        maps = [
            indices[node.value.first:node.value.last] for node in selection
        ]

        selected_indices = list(chain(*maps))
        unselected_indices = sorted(
            set(range(self.root.value.last)) - set(selected_indices))

        selected = [items[k] for k in selected_indices]
        unselected = [items[k] for k in unselected_indices]

        if not selected:
            self.send("Selected Data", None)
            self.send("Other Data", None)
            return
        selected_data = unselected_data = None

        if isinstance(items, Orange.data.Table):
            c = numpy.zeros(len(items))

            for i, indices in enumerate(maps):
                c[indices] = i
            c[unselected_indices] = len(maps)

            mask = c != len(maps)

            if self.append_clusters:
                clust_var = Orange.data.DiscreteVariable(
                    str(self.cluster_name),
                    values=[
                        "Cluster {}".format(i + 1) for i in range(len(maps))
                    ] + ["Other"])
                data, domain = items, items.domain

                attrs = domain.attributes
                class_ = domain.class_vars
                metas = domain.metas

                X, Y, M = data.X, data.Y, data.metas
                if self.cluster_role == self.AttributeRole:
                    attrs = attrs + (clust_var, )
                    X = numpy.c_[X, c]
                elif self.cluster_role == self.ClassRole:
                    class_ = class_ + (clust_var, )
                    Y = numpy.c_[Y, c]
                elif self.cluster_role == self.MetaRole:
                    metas = metas + (clust_var, )
                    M = numpy.c_[M, c]

                domain = Orange.data.Domain(attrs, class_, metas)
                data = Orange.data.Table(domain, X, Y, M)
            else:
                data = items

            if selected:
                selected_data = data[mask]
            if unselected:
                unselected_data = data[~mask]

        self.send("Selected Data", selected_data)
        self.send("Other Data", unselected_data)

    def sizeHint(self):
        return QSize(800, 500)

    def eventFilter(self, obj, event):
        if obj is self.view.viewport() and event.type() == QEvent.Resize:
            width = self.view.viewport().width() - 2
            self._main_graphics.setMaximumWidth(width)
            self._main_graphics.setMinimumWidth(width)
            self._main_graphics.layout().activate()
        elif event.type() == QEvent.MouseButtonPress and \
                (obj is self.top_axis_view.viewport() or
                 obj is self.bottom_axis_view.viewport()):
            self.selection_method = 1
            # Map click point to cut line local coordinates
            pos = self.top_axis_view.mapToScene(event.pos())
            cut = self.top_axis.line.mapFromScene(pos)
            self.top_axis.line.setValue(cut.x())
            # update the line visibility, output, ...
            self._selection_method_changed()

        return super().eventFilter(obj, event)

    def _dendrogram_geom_changed(self):
        pos = self.dendrogram.pos_at_height(self.cutoff_height)
        geom = self.dendrogram.geometry()
        crect = self.dendrogram.contentsRect()

        self._set_slider_value(pos.x(), geom.width())
        self.cut_line.setLength(geom.height())

        self.top_axis.resize(crect.width(), self.top_axis.height())
        self.top_axis.setPos(geom.left() + crect.left(), 0)
        self.top_axis.line.setPos(self.cut_line.scenePos().x(), 0)

        self.bottom_axis.resize(crect.width(), self.bottom_axis.height())
        self.bottom_axis.setPos(geom.left() + crect.left(), 0)
        self.bottom_axis.line.setPos(self.cut_line.scenePos().x(), 0)

        geom = self._main_graphics.geometry()
        assert geom.topLeft() == QPointF(0, 0)
        self.scene.setSceneRect(geom)

        geom.setHeight(self.top_axis.size().height())

        self.top_axis.scene().setSceneRect(geom)
        self.bottom_axis.scene().setSceneRect(geom)

    def _axis_slider_changed(self, value):
        self.cut_line.setValue(value)

    def _dendrogram_slider_changed(self, value):
        p = QPointF(value, 0)
        cl_height = self.dendrogram.height_at(p)

        self.set_cutoff_height(cl_height)

        # Sync the cut positions between the dendrogram and the axis.
        self._set_slider_value(value, self.dendrogram.size().width())

    def _set_slider_value(self, value, span):
        with blocked(self.cut_line):
            self.cut_line.setValue(value)
            self.cut_line.setRange(0, span)

        with blocked(self.top_axis.line):
            self.top_axis.line.setValue(value)
            self.top_axis.line.setRange(0, span)

        with blocked(self.bottom_axis.line):
            self.bottom_axis.line.setValue(value)
            self.bottom_axis.line.setRange(0, span)

    def set_cutoff_height(self, height):
        self.cutoff_height = height
        if self.root:
            self.cut_ratio = 100 * height / self.root.value.height
        self.select_max_height(height)

    def _set_cut_line_visible(self, visible):
        self.cut_line.setVisible(visible)
        self.top_axis.line.setVisible(visible)
        self.bottom_axis.line.setVisible(visible)

    def select_top_n(self, n):
        root = self._displayed_root
        if root:
            clusters = top_clusters(root, n)
            self.dendrogram.set_selected_clusters(clusters)

    def select_max_height(self, height):
        root = self._displayed_root
        if root:
            clusters = clusters_at_height(root, height)
            self.dendrogram.set_selected_clusters(clusters)

    def _selection_method_changed(self):
        self._set_cut_line_visible(self.selection_method == 1)
        if self.root:
            self._apply_selection()

    def _apply_selection(self):
        if not self.root:
            return

        if self.selection_method == 0:
            pass
        elif self.selection_method == 1:
            height = self.cut_ratio * self.root.value.height / 100
            self.set_cutoff_height(height)
            pos = self.dendrogram.pos_at_height(height)
            self._set_slider_value(pos.x(), self.dendrogram.size().width())
        elif self.selection_method == 2:
            self.select_top_n(self.top_n)

    def _selection_edited(self):
        # Selection was edited by clicking on a cluster in the
        # dendrogram view.
        self.selection_method = 0
        self._selection_method_changed()
コード例 #34
0
ファイル: main.py プロジェクト: Fxrh/aur-updates
class AurApplet(plasmascript.Applet):
    def __init__(self, parent):
        plasmascript.Applet.__init__(self, parent)
        
    def _getData(self):
        try:
            self.data = aur_py2.aurUpdates()
        except subprocess.CalledProcessError:
            self.errorMsg = "Could not run pacman"
            self.data = None
        except IOError:
            self.errorMsg = "Could not access the AUR"
            self.data = None
            
    def _writeData(self):
        print self.data
        string = ""
        for line in self.data[0]:
            string = string+line[0]+"\t"+line[1]+" -> "+line[2]+"\n"
        self.updateData.setText(string)
        string = ""
        for line in self.data[1]:
            string = string+line[0]+"\t"+line[1]+"\n"
        self.oodData.setText(string)
        string = ""
        for line in self.data[2]:
            string = string+line[0]+"\t"+line[1]+"\n"
        self.orphanData.setText(string)
        string = ""
        for line in self.data[3]:
            string = string+line[0]+"\t"+line[1]+"\n"
        self.notFoundData.setText(string)
        
        
    def _checkForNone(self):
        if self.data == None:
            self.updateInfo.setText("<h1>"+self.errorMsg+"</h1>")
        else:
            self.updateInfo.setText("<h1>Updates</h1>")
            self.oodInfo.setText("<h1>Out Of Date</h1>")
            self.orphanInfo.setText("<h1>Orphans</h1>")
            self.notFoundInfo.setText("<h1>Not Found</h1>")
            self._writeData()
        
    def init(self):
        self.updateInfo = Plasma.Label(self.applet)
        self.updateData = Plasma.Label(self.applet)
        self.oodInfo = Plasma.Label(self.applet)
        self.oodData = Plasma.Label(self.applet)
        self.orphanInfo = Plasma.Label(self.applet)
        self.orphanData = Plasma.Label(self.applet)
        self.notFoundInfo = Plasma.Label(self.applet)
        self.notFoundData = Plasma.Label(self.applet)
        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        self.layout.addItem(self.updateInfo)
        self.layout.addItem(self.updateData)
        self.layout.addItem(self.oodInfo)
        self.layout.addItem(self.oodData)
        self.layout.addItem(self.orphanInfo)
        self.layout.addItem(self.orphanData)
        self.layout.addItem(self.notFoundInfo)
        self.layout.addItem(self.notFoundData)
        
        self._getData()
        
        self._checkForNone()
コード例 #35
0
ファイル: flowmodule.py プロジェクト: dbittman/config-files
class FlowModule:
	def __init__(self):
		self.name = "Pretok"
		self.updateTimer = QTimer()
		self.updateTimer.timeout.connect(self.update)
	
	def makeLayout(self):
		self.layout = QGraphicsLinearLayout(Qt.Vertical)
		self.flowComboLayout = QGraphicsLinearLayout(Qt.Horizontal)
		self.flowLabelLayout = QGraphicsGridLayout()
		
		#Flow Layout
		self.flowData = SvJanez()
		self.flowView = QGraphicsWebView()
		self.flowView.setUrl( QUrl(self.flowData.flowImageUrl) )
		self.flowView.setEnabled(False)

		self.flowSelectorCombo = Plasma.ComboBox()
		self.flowSelectorCombo.addItem(u"Sveti Janez")
		self.flowSelectorCombo.addItem(u"Soteska")
		self.flowSelectorCombo.setMinimumWidth(125)
		self.flowSelectorCombo.textChanged.connect(self.flowSourceChanged)

		self.flowRefresh = Plasma.IconWidget()
		self.flowRefresh.setIcon("view-refresh")
		self.flowRefresh.clicked.connect(self.update)

		self.flowEnlargeButton = Plasma.IconWidget()
		self.flowEnlargeButton.setIcon("zoom-in")
		self.flowEnlargeButton.clicked.connect(self.showFullFlowWidget)

		self.flowLabel = Plasma.Label()
		self.flowLabel.setText(u"<b>Pretok:</b> ")
		self.flowDataLabel = Plasma.Label()
		self.flowLevelLabel = Plasma.Label()
		self.flowLevelLabel.setText(u"<b>Višina:</b> ")
		self.flowLevelDataLabel = Plasma.Label()
		self.flowTempLabel = Plasma.Label()
		self.flowTempLabel.setText(u"<b>Temperatura:</b> ")
		self.flowTempDataLabel = Plasma.Label()

		self.flowLabelLayout.addItem(self.flowLevelLabel,0,0)
		self.flowLabelLayout.addItem(self.flowLevelDataLabel,0,1)
		self.flowLabelLayout.addItem(self.flowLabel,1,0)
		self.flowLabelLayout.addItem(self.flowDataLabel,1,1)
		self.flowLabelLayout.addItem(self.flowTempLabel,2,0)
		self.flowLabelLayout.addItem(self.flowTempDataLabel,2,1)
		
		self.flowUpdateTimeSelector = UpdateTimeSelector()
		self.flowUpdateTimeSelector.setDefaultTime(4)
		self.flowUpdateTimeSelector.setDefaultInterval('h')
		self.flowUpdateTimeSelector.updateTimeSpin.valueChanged.connect(self.flowTimeChanged)
		self.flowUpdateTimeSelector.updateCheckBox.toggled.connect(self.flowTimerToggle)
		
		
		self.flowComboLayout.addItem(self.flowSelectorCombo)
		self.flowComboLayout.addStretch()
		self.flowComboLayout.addItem(self.flowEnlargeButton)
		self.flowComboLayout.addItem(self.flowRefresh)
		self.layout.addItem(self.flowComboLayout)
		self.layout.addItem(self.flowView)
		self.layout.addItem(self.flowLabelLayout)
		self.layout.addStretch()
		self.layout.addItem(self.flowUpdateTimeSelector.layout)
		self.layout.itemAt(0).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.DefaultType)
		self.layout.itemAt(2).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.DefaultType)
	
	def flowTimerToggle(self, toggled):
		if toggled:
			multiplier = 1
			if self.flowUpdateTimeSelector.getInterval() == 'min':
				multiplier = 60
			if self.flowUpdateTimeSelector.getInterval() == 'h':
				multiplier = 60 * 60
			self.updateTimer.start(self.flowUpdateTimeSelector.getTime() * 1000 * multiplier)
			self.update()
		else:
			self.updateTimer.stop()
	
	def flowTimeChanged(self, value):
		if self.flowUpdateTimeSelector.isChecked():
			self.updateTimer.stop()
		self.flowTimerToggle(self.flowUpdateTimeSelector.isChecked())
		
	def flowSourceChanged(self, text):
		if text == "Sveti Janez":
			self.flowData = SvJanez()
		else:
			self.flowData = Soteska()
		self.flowView.setUrl(QUrl(self.flowData.flowImageUrl))
		self.updateFlowLabels()
	
	def updateFlowImage(self):
		self.flowSourceChanged(self.flowSelectorCombo.text())
	
	def updateFlowLabels(self):
		self.flowData.fetchData()
		self.flowDataLabel.setText(u"%s %s" % (self.flowData.currentFlow, u' m3/s'))
		self.flowTempDataLabel.setText(u"%s %s" % (self.flowData.temperature , u' °C'))
		self.flowLevelDataLabel.setText(u"%s %s" % (self.flowData.waterLevel , u' cm'))
	
	def update(self):
		try:
			urllib.urlopen('http://www.google.com', timeout=2)
		except:
			self.offlineMode()
			return
		self.updateFlowLabels()
		self.updateFlowImage()
		
	def offlineMode(self):
		self.flowView.setUrl(QUrl("weather-none-available.png"))
		self.flowDataLabel.setText(u"N/A")
		self.flowTempDataLabel.setText(u"N/A")
		self.flowLevelDataLabel.setText(u"N/A")
	
	def showFullFlowWidget(self):
		fullcamwidget = FullCamWidget()
		fullcamwidget.show(self.flowView.url(), 840, 400)
コード例 #36
0
ファイル: widget.py プロジェクト: hersche/MultiSms
class Multimobilewidget(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)
 
    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.Square)
        self.theme = Plasma.Svg(self)
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)
        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        self.getLogin()
        self.setHasConfigurationInterface(True)
        self.label = Plasma.Label(self.applet)
        self.label.setText(i18n("Welcome to the Multimobilewidget"))
        nrlabel = Plasma.Label(self.applet)
        nrlabel.setText(i18n("Phonenr(s)"))
        self.messagelabel = Plasma.Label(self.applet)
        self.messagelabel.setText(i18n("Message - 0 signs used"))
        self.nrfield = Plasma.LineEdit()
        self.messageText = Plasma.TextEdit(self.applet)
        self.messageText.nativeWidget()
        sendButton = Plasma.PushButton(self.applet)
        sendButton.setText(i18n("Send the SMS!"))
        sendButton.resize(20, 40)
        configButton = Plasma.PushButton(self.applet)
        configButton.setText("Config")
        configButton.resize(20, 40)
        self.layout.addItem(self.label)
        self.layout.addItem(nrlabel)
        self.layout.addItem(self.nrfield)
        self.layout.addItem(self.messagelabel)
        self.layout.addItem(self.messageText)
        self.layout.addItem(sendButton)
        self.layout.addItem(configButton)
        self.applet.setLayout(self.layout)
        self.connect(sendButton, SIGNAL("clicked()"), self.onSendClick)
        self.connect(configButton, SIGNAL("clicked()"), self.onConfigClick)
        self.connect(self.messageText, SIGNAL("textChanged()"), self.onTextChanged)
        fullPath = str(self.package().path())
        self.providerPluginManager = PluginManager("multimobilewidget/contents/code/providerplugins/","", providerplugins.Provider.Provider)
        self.providerpluginlist = self.providerPluginManager.getPluginClassList()
        for provider in self.providerpluginlist:
            self.ui.providerList.addItem(provider.getObjectname())
            print provider.getObjectname()
            self.ui.providerList.setCurrentRow(0)
        self.adressplugins = PluginManager("multimobilewidget/contents/code/adressplugins/","", adressplugins.AdressPlugin.AdressPlugin)
        self.adresspluginlist = self.adressplugins.getPluginClassList()
        self.adressList = list()
        
        
    def onConfigClick(self):
        from config import config
        self.startAssistant = config(self.providerPluginManager, self.adressplugins)
        self.startAssistant.show()
        self.connect(self.startAssistant, SIGNAL("finished(int)"), self.getLogin)
    def connectToAkonadi(self):
        self.akonadiEngine = Plasma.DataEngine()
        self.akonadiEngine.setName("akonadi")
    def onSendClick(self):
        for provider in self.providerpluginlist:
            if(provider.getObjectname() == self.ui.providerList.selectedItems()[0].text()):
                sms = provider
        if self.ui.smstext.toPlainText() != "":
            if self.ui.phonenr.text() != "":
                self.getLogin()
                try:
                    sms.setConfig(self.config)
                except Exception:
                    self.onConfigClick()
                    return
                sms.clearNrs()
                for nr in re.findall("(\+\d*)", self.ui.phonenr.text()):
                    sms.addNr(nr)
                sms.setText(self.ui.smstext.toPlainText())
                savenr = self.ui.phonenr.text()
                try:
                    sms.execute()
#                    self.notification.setText(i18n("Wurde erfolgreich an <i>%1</i> geschickt!").arg(savenr ))
#                    self.notification.setTitle("Erfolg!")
#                    self.notification.sendEvent()
                    KMessageBox.information(None, i18n("SMS sendet successfully to " + savenr + ". Service: "+sms.getProvidername()), i18n("Success!"))
                except Exception, error:
                    KMessageBox.error(None, i18n(error.message), i18n("Sendproblems"))
                self.ui.phonenr.clear()
                self.ui.smstext.clear()
            else:
                KMessageBox.error(None, i18n("Please fill in a phonenr"), i18n("Please fill in a phonenr"))
        else:
コード例 #37
0
ファイル: main.py プロジェクト: Ascaf0/PlasmaFreq
class PlasmaFreq(plasmascript.Applet):
    def __init__(self, parent, args=None):
        # Init for plasma applet
        plasmascript.Applet.__init__(self, parent)

    def listGovernors(self):
        # Lists governors aka power modes available in current system.
        self.listGovPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"
        governorsFile = open(self.listGovPath, 'r')  # Open the file
        availableGovernors = governorsFile.read()
        governorsList = split(
            " +", availableGovernors
        )  # Splitting the string to list, space is the separator
        governorsList.remove(
            "\n")  # Remove newline item from list, added by split
        governorsFile.close()
        return governorsList

    def listFrequencies(self):
        # Lists processor core frequencies available for scaling
        self.listFreqPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies"
        frequenciesFile = open(self.listFreqPath, 'r')
        availableFrequencies = frequenciesFile.read()
        frequenciesList = split(" +", availableFrequencies)
        frequenciesList.remove("\n")
        frequenciesFile.close()
        return frequenciesList

    def currentFrequency(self):
        # Returns a string containing the current governor
        self.curFreqPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"
        frequencyFile = open(self.curFreqPath, 'r')
        if self.curFreqPath not in self.watcher.files():
            self.watcher.addPath(self.curFreqPath)
        currentFrequency = frequencyFile.read()
        currentFrequency = currentFrequency.rstrip(
        )  # Removes newline from string, since we don't need a list for this.
        frequencyFile.close()
        return currentFrequency

    def currentGovernor(self):
        self.curGovPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"
        governorFile = open(self.curGovPath, 'r')
        if self.curGovPath not in self.watcher.files(
        ):  # Not adding file to watcher in case of it excists already
            self.watcher.addPath(self.curGovPath)
        currentGovernor = governorFile.read()
        currentGovernor = currentGovernor.rstrip(
        )  # Removes newline from string, since we don't need a list for this.
        governorFile.close()
        return currentGovernor

    def file_changed(self, path):
        if path == self.curGovPath:  # When scaling governor has changed, this is true
            self.currentGovernorStr = self.currentGovernor()
            self.radioButton[self.currentGovernorStr].setChecked(
                True)  # Check radioButton that represents the new governor

        if path == self.curFreqPath:
            self.currentFrequencyStr = self.currentFrequency()

    def applyChanges(self):

        # With some Linux distros kdesudo is not default/not even available in official software repositories
        kdesudoY = True
        try:
            call(["kdesudo", "--"])
        except OSError:
            kdesudoY = False
        #kdesudoY := just a flag to change command in the cycle below while keeping changes to code separated

        # We basically run a for-loop to try out that which radioButton is checked. Better ways warmly welcome.
        for x in self.availableGovernors:
            if self.radioButton[x].isChecked(
            ) == True:  # radioButton for x governor is checked
                cpufreqFiles = " ".join(
                    self.cpufreqGovPath
                )  # Converting list to space-separated string
                if kdesudoY:
                    governor = '"%s"' % x  # Adding quotes to governor name
                    # Insert some variables to command. We should use KAuth instead of kdesudo but I have no idea how to use KAuth in python
                    cmd = "kdesudo -i %s --comment '<b>PlasmaFreq</b> need administrative priviledges. Please enter your password.' -c 'echo %s | tee %s'" % (
                        self.icon, governor, cpufreqFiles)
                else:
                    # no kdesudo: use kdesu in cmd
                    governor = "%s" % x  # Adding single (to work with kdesu + tee) quotes to governor name
                    # Insert some variables to command. We should use KAuth instead of kdesu(do) but I have no idea how to use KAuth in python
                    cmd = "kdesu -i %s -c 'echo %s | tee %s'" % (
                        self.icon, governor, cpufreqFiles)
                # Run the command. shell=True would be a security vulnerability (shell injection) if the cmd parameter would have something from user input
                fnull = open(
                    devnull,
                    'w')  # Open /dev/null for stdout/stderr redirection
                call(cmd, shell=True, stdout=fnull, stderr=fnull)
                fnull.close()

    def init(self):

        # Setting some Plasma-specific settings
        self.setHasConfigurationInterface(
            False)  # We dont have a configuration interface, yet.
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.theme = Plasma.Svg(self)
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)
        self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        self.applet.setLayout(self.layout)
        self.icon = self.package().path(
        ) + "plasmafreq.svg"  # Finding a path for our apps icon

        # Adding a nice-looking GroupBox for RadioButtons
        self.setGovernorBox = Plasma.GroupBox(self.applet)
        self.setGovernorBox.setText("Mode selection")
        self.setGovernorBox.setLayout(
            QGraphicsLinearLayout(Qt.Vertical, self.setGovernorBox))
        self.setGovernorBox.setSizePolicy(
            QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding))
        self.layout.addItem(self.setGovernorBox)
        self.governorGroup = QButtonGroup(
            self.applet
        )  # Creating a abstract ButtonGroup in order to link RadioButtons together

        # Creating a QFileSystemWatcher to watch changes in current frequency and governor
        self.watcher = QFileSystemWatcher(self)
        QObject.connect(self.watcher, SIGNAL("fileChanged(const QString&)"),
                        self.file_changed)

        # Setting paths for cpufreq
        self.cpuCores = glob(path.join("/sys/devices/system/cpu/",
                                       "cpu?"))  # List all CPU cores
        self.cpufreqGovPath = []
        # This is going to be ugly...but hey, it works (at least if you dont have many physical CPUs. Cores are ok)
        for x in self.cpuCores:
            self.cpufreqGovPath.append(
                x + "/cpufreq/scaling_governor"
            )  # path.join doesn't work here, dunno why

        # Initializing some variables and setting variables to them.
        self.availableFrequencies = self.listFrequencies()
        self.availableGovernors = self.listGovernors()
        self.currentGovernorStr = self.currentGovernor()
        self.currentFrequencyStr = self.currentFrequency()
        self.radioButton = {}

        # This contains texts and tooltips for RadioButtons
        self.governorTextsDict = {
            'conservative': [
                'Conservative',
                'Similiar to On Demand, but CPU clock speed switches gradually through all its available frequencies based on system load '
            ],
            'ondemand': [
                'On Demand',
                'Dynamically switches between the CPU available clock speeds based on system load '
            ],
            'userspace':
            ['User Defined', 'Lets user to manually configure clock speeds'],
            'powersave': ['Powersave', 'Runs the CPU at minimum clock speeds'],
            'performance':
            ['Performance', 'Runs the CPU at maximum clock speeds']
        }

        for x in self.availableGovernors:
            # Makes a RadioButton for each governor available.
            self.radioButton[x] = Plasma.RadioButton(self.applet)
            self.radioButton[x].setText(
                self.governorTextsDict[x][0]
            )  # Sets the text for radioButton from governorTextsDict above
            self.radioButton[x].setToolTip(self.governorTextsDict[x][1])
            self.radioButton[x].setSizePolicy(
                QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))
            self.governorGroup.addButton(self.radioButton[x].nativeWidget(
            ))  # We need to add radioButton's native widget
            self.setGovernorBox.layout().addItem(self.radioButton[x])
            if x == self.currentGovernorStr:
                self.radioButton[x].setChecked(
                    True
                )  # Checks if x is current governor and should we have a tick on RadioButton

        # Add a button for applying changes
        self.applyButton = Plasma.PushButton(self.applet)
        self.applyButton.setText("Apply")
        self.applyButton.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum))
        self.layout.addItem(self.applyButton)
        QObject.connect(self.applyButton, SIGNAL("clicked()"),
                        self.applyChanges)
コード例 #38
0
ファイル: main.py プロジェクト: selam/ublog
    def init(self):
        """
        create interface, this method invoked by plasma it self
        """
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        #
        self.flash = Plasma.FlashingLabel(self.applet)
        self.flash.setAutohide(True)
        self.flash.setMinimumSize(0, 20)
        self.flash.setDuration(2000)
        self.tab_bar = Plasma.TabBar()

        self._layout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
        self._layout.setSpacing(3)

        flash_layout = QGraphicsLinearLayout(Qt.Horizontal)
        flash_layout.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        fnt = Plasma.Theme.defaultTheme().font(Plasma.Theme.DefaultFont)
        fnt.setBold(True)
        fm = QFontMetrics(fnt)

        self.flash.setFont(fnt)
        self.flash.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        title_layout = QGraphicsLinearLayout(Qt.Vertical)

        flash_layout.addItem(self.flash)
        flash_layout.addItem(title_layout)

        self.main_frame = Plasma.Frame(self.applet)
        m_header_layout = QGraphicsAnchorLayout(self.main_frame)
        m_header_layout.setSpacing(5)

        self.icon = Plasma.IconWidget(self.main_frame)
        self.icon.setIcon(KIcon("user-identity"))
        self.icon.setTextBackgroundColor(QColor())
        icon_size = self.icon.sizeFromIconSize(48)
        self.icon.setMinimumSize(icon_size)
        self.icon.setMaximumSize(icon_size)

        m_header_layout.addAnchor(self.icon, Qt.AnchorVerticalCenter, m_header_layout, Qt.AnchorVerticalCenter)
        m_header_layout.addAnchor(self.icon, Qt.AnchorLeft, m_header_layout, Qt.AnchorLeft)

        status_edit_frame = Plasma.Frame(self.main_frame)
        status_edit_frame.setFrameShadow(Plasma.Frame.Sunken)
        status_edit_layout = QGraphicsLinearLayout(status_edit_frame)
        self.status_edit = Plasma.TextEdit()
        self.status_edit.setPreferredHeight(fm.height() * 4)
        self.status_edit.setEnabled(False)
        status_edit_layout.addItem(self.status_edit)

        edit_pal = self.status_edit.palette()
        m_color_scheme = KColorScheme(QPalette.Active, KColorScheme.View, Plasma.Theme.defaultTheme().colorScheme())
        edit_pal.setColor(QPalette.Text, m_color_scheme.foreground().color())
        self.status_edit.nativeWidget().setPalette(edit_pal)
        self.status_edit.nativeWidget().installEventFilter(self)
        m_header_layout.addAnchor(self.icon, Qt.AnchorRight, status_edit_frame, Qt.AnchorLeft)
        m_header_layout.addAnchors(status_edit_frame, m_header_layout, Qt.Vertical)
        m_header_layout.addAnchor(status_edit_frame, Qt.AnchorRight, m_header_layout, Qt.AnchorRight)
        m_header_layout.activate()
        m_header_layout.setMaximumHeight(m_header_layout.effectiveSizeHint(Qt.PreferredSize).height())

        self.scroll_widget = Plasma.ScrollWidget(self.applet)
        self.tweets_widget = QGraphicsWidget(self.scroll_widget)
        self.scroll_widget.setWidget(self.tweets_widget)
        self.tweets_layout = QGraphicsLinearLayout(Qt.Vertical, self.tweets_widget)
        self.tweets_layout.setSpacing(3)
        self.tweets_layout.addItem(self.main_frame)

        self.tab_bar.addTab(self.trUtf8("Timeline"))
        self.tab_bar.addTab(self.trUtf8("Replies"))
        self.tab_bar.addTab(self.trUtf8("Messages"))

        self._layout.addItem(flash_layout)
        self._layout.addItem(self.tab_bar)
        self._layout.addItem(self.scroll_widget)

        self.applet.setLayout(self._layout)
        self.connect(self.tab_bar, SIGNAL('currentChanged(int)'), self.mode_changed)
        self.connect(self.status_edit, SIGNAL('textChanged()'), self.edit_text_changed)
        self.check_config()
コード例 #39
0
class IMAPresourceStatus(plasmascript.Applet):
  def __init__(self,parent,args=None):
    plasmascript.Applet.__init__(self,parent)

  def init(self):
    self.setHasConfigurationInterface(False)
    self.setAspectRatioMode(Plasma.Square)

    # Theme
    self.theme = Plasma.Svg(self)
    self.theme.setImagePath("widgets/background")
    self.theme.setContainsMultipleImages(False)
    self.setBackgroundHints(Plasma.Applet.DefaultBackground)

    # DBus
    loop = DBusQtMainLoop()
    dbus.set_default_main_loop(loop)
    self.sessionBus = dbus.SessionBus()

    i = 0

    while i < 10:
      # ugly hack to wait for service to be available
      i = i + 1
      try:
        self.imap_res = self.sessionBus.get_object('org.freedesktop.Akonadi.Agent.' + RES, '/')
        self.imap_res.connect_to_signal("onlineChanged", self.onlineChanged)
      except dbus.exceptions.DBusException as e:
        if(e.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown"):
          # Service is not yet ready
          print "Waiting for 'org.freedesktop.Akonadi.Agent.%s/' to become available..." % RES
          time.sleep(0.2)
        else:
          break
      else:
        break

    # Icon
    self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)
    self.icon = Plasma.IconWidget()
    self.icon.mousePressEvent = self.mousePressEvent
    self.icon.mouseReleaseEvent = self.mouseReleaseEvent
    if self.isOnline():
      self.onlineChanged(True)
    else:
      self.onlineChanged(False)

    self.layout.addItem(self.icon)
    self.applet.setLayout(self.layout)


  def isOnline(self):
    return self.imap_res.isOnline(dbus_interface='org.freedesktop.Akonadi.Agent.Status')


  def onlineChanged(self, status):
    if status:
      self.icon.setIcon(self.package().path() + "contents/icons/network-server-on.png")
    else:
      self.icon.setIcon(self.package().path() + "contents/icons/network-server-off.png")


  def mouseReleaseEvent(self,event):
    if self.isOnline():
      state = False
    else:
      state = True

    self.imap_res.setOnline(state, dbus_interface='org.freedesktop.Akonadi.Agent.Status')


  def mousePressEvent(self, event):
    if event.buttons() == Qt.LeftButton:
      self.clicked = self.scenePos().toPoint()
      event.setAccepted(True)
コード例 #40
0
ファイル: cammodule.py プロジェクト: dbittman/config-files
class CamModule:
	def __init__(self):
		self.name = "Kamere"
		#Cam urls
		self.camUrls = {u"Ribčev Laz (v živo)": "http://firma.sportnet.si:8080/dvs2000/r1.jpg",\
						u"Ribčev Laz": "http://www.bohinj.si/cam/slika3.jpg",\
						u"Vogel - 1" : "http://www.snezni-telefon.si/Images/Kamere/6_a.jpg",\
						u"Vogel - 2" : "http://www.snezni-telefon.si/Images/Kamere/6_b.jpg",\
						u"Vogel - 3" : "http://www.snezni-telefon.si/Images/Kamere/6_c.jpg",\
						u"Vogel - 4" : "http://www.snezni-telefon.si/Images/Kamere/6_d.jpg",\
						u"Bohinjska Češnjica" : "http://www2.arnes.si/~smisma1/canon.jpg",\
						u"Bohinjska Bistrica" : "http://www.drsc.si/kamere/kamslike/bohinjska/slike/boh1_0001.jpg",\
						u"Orožnova koča": "http://www.bohinj.si/cam/lisc/slika1.jpg"}

		self.camSizes ={u"Ribčev Laz (v živo)": "352x228", \
						u"Ribčev Laz": "2048x1536",\
						u"Vogel - 1" : "1280x1024",\
						u"Vogel - 2" : "640x480",\
						u"Vogel - 3" : "1280x1024",\
						u"Vogel - 4" : "640x480",\
						u"Bohinjska Češnjica" : "800x600",\
						u"Bohinjska Bistrica" : "352x228",\
						u"Orožnova koča": "1280x1024"}
						
		self.updateTimer = QTimer()
		self.updateTimer.timeout.connect(self.update)
		
	
	def makeLayout(self):
		self.layout = QGraphicsLinearLayout(Qt.Vertical)
		self.topCamLayout = QGraphicsLinearLayout(Qt.Horizontal)
		
		# Cam layout
		self.camRefreshButton = Plasma.IconWidget()
		self.camRefreshButton.setIcon("view-refresh")
		self.camRefreshButton.clicked.connect(self.update)
		
		self.camTimeLabel = Plasma.Label()
		self.camTimeLabel.setText(u"ob")

		self.camEnlargeButton = Plasma.IconWidget()
		self.camEnlargeButton.setIcon("zoom-in")
		self.camEnlargeButton.clicked.connect(self.showFullCamWidget)

		self.camSelectorCombo = Plasma.ComboBox()
		for source in sorted(self.camUrls.keys()):
			self.camSelectorCombo.addItem(source)
		self.camSelectorCombo.setMinimumWidth(125)
		self.camSelectorCombo.textChanged.connect(self.camChanged)

		self.camView = QGraphicsWebView()
		self.camView.setEnabled(False)

		self.camTimeDataLabel = Plasma.Label()

		self.camUpdateTimeSelector = UpdateTimeSelector()
		self.camUpdateTimeSelector.setDefaultTime(30)
		self.camUpdateTimeSelector.setDefaultInterval('min')
		self.camUpdateTimeSelector.updateTimeSpin.valueChanged.connect(self.camTimeChanged)
		self.camUpdateTimeSelector.updateCheckBox.toggled.connect(self.camTimerToggle)

		self.topCamLayout.addItem(self.camSelectorCombo)
		self.topCamLayout.addItem(self.camTimeLabel)
		self.topCamLayout.addItem(self.camTimeDataLabel)
		self.topCamLayout.addStretch()
		self.topCamLayout.addItem(self.camEnlargeButton)
		self.topCamLayout.addItem(self.camRefreshButton)

		self.layout.addItem(self.topCamLayout)
		self.layout.addItem(self.camView)
		self.layout.addItem(self.camUpdateTimeSelector.layout)
		self.layout.itemAt(0).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.DefaultType)
		self.layout.itemAt(2).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.DefaultType)
	
	def update(self, text=None):
		try:
			urllib.urlopen('http://www.google.com', timeout=2)
		except:
			self.offlineMode()
			return
		if not self.camUpdateTimeSelector.updateCheckBox.isChecked():
			self.updateTimer.stop()
		self.camChanged(self.camSelectorCombo.text())
		self.setCamTimeLabel()
		
	def offlineMode(self):
		self.camView.setUrl(QUrl("weather-none-available.png"))
		self.camTimeDataLabel.setText(" ni na voljo.")
		
	def setCamTimeLabel(self):
		hour = time.localtime().tm_hour if not time.localtime().tm_hour in range(10) else '0' + str(time.localtime().tm_hour)
		minute = time.localtime().tm_min if not time.localtime().tm_min in range(10) else '0' + str(time.localtime().tm_min)
		second = time.localtime().tm_sec if not time.localtime().tm_sec in range(10) else '0' + str(time.localtime().tm_sec)
		self.camTimeDataLabel.setText(u'<b>%s:%s:%s</b>' % (str(hour), str(minute), str(second)) )
    
	def camTimerToggle(self, toggled):
		if toggled:
			multiplier = 1
			if self.camUpdateTimeSelector.getInterval() == 'min':
				multiplier = 60
			if self.camUpdateTimeSelector.getInterval() == 'h':
				multiplier = 60 * 60
			self.updateTimer.start(self.camUpdateTimeSelector.getTime() * 1000 * multiplier)
			self.update()
		else:
			self.updateTimer.stop()
	
	def camChanged(self, text):
		self.camView.setUrl( QUrl( self.camUrls[unicode(text)] ) )
		self.setCamTimeLabel()
		
	def camTimeChanged(self, value):
		if self.camUpdateTimeSelector.isChecked():
			self.updateTimer.stop()
		self.camTimerToggle(self.camUpdateTimeSelector.isChecked())
	
	def showFullCamWidget(self):
		fullcamwidget = FullCamWidget()
		size = self.camSizes[unicode(self.camSelectorCombo.text())]
		size = [ int(i) for i in size.split('x')]
		if size[0] < 640 and size[1] < 480:
			fullcamwidget.show(self.camView.url(), size[0] + 25, size[1] + 125)
		else:
			fullcamwidget.show(self.camView.url(), 645, 505)