Exemple #1
0
 def __init__(self, parent=None):
     QGraphicsWidget.__init__(self, parent)
     self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
     self.setContentsMargins(10, 10, 10, 10)
     layout = QGraphicsGridLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(10)
     self.setLayout(layout)
Exemple #2
0
    def init(self):
	#self.moduller=self.link.Network.Firewall[dbus.String("iptables")].listModules()
	
	self.tahta=[[0,0,0],[0,0,0],[0,0,0]]
	
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.Square)
        self.resize(450,250)
 
        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)
        self.layout=QGraphicsGridLayout(self.applet)
        
        #label = Plasma.Label(self.applet)
        #label.setText("<h1>Firewall Plasmoid</h1>")
        #self.kilit=Plasma.IconWidget(self.applet)
        #self.bilgi_label=Plasma.Label(self.applet)
        
        #self.baslat_pb=Plasma.PushButton(self.applet)
        #self.baslat_pb.setText("Start")
        #self.durdur_pb=Plasma.PushButton(self.applet)
        #self.durdur_pb.setText("Stop")
        
        self.tus1=Plasma.PushButton(self.applet)
	self.tus1.setText("")
	self.tus2=Plasma.PushButton(self.applet)
	self.tus2.setText("")
	self.tus3=Plasma.PushButton(self.applet)
	self.tus3.setText("")
	
	self.tus4=Plasma.PushButton(self.applet)
	self.tus4.setText("")
	self.tus5=Plasma.PushButton(self.applet)
	self.tus5.setText("")
	self.tus6=Plasma.PushButton(self.applet)
	self.tus6.setText("")
	
	self.tus7=Plasma.PushButton(self.applet)
	self.tus7.setText("")
	self.tus8=Plasma.PushButton(self.applet)
	self.tus8.setText("")
	self.tus9=Plasma.PushButton(self.applet)
	self.tus9.setText("")
        
        self.layout.addItem(self.tus1, 0, 0)
        self.layout.addItem(self.tus2, 0, 1)
        self.layout.addItem(self.tus3, 0, 2)
        self.layout.addItem(self.tus4, 1, 0)
        self.layout.addItem(self.tus5, 1, 1)
        self.layout.addItem(self.tus6, 1, 2)
        self.layout.addItem(self.tus7, 2, 0)
        self.layout.addItem(self.tus8, 2, 1)
        self.layout.addItem(self.tus9, 2, 2)
        self.applet.setLayout(self.layout)        
Exemple #3
0
	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)
Exemple #4
0
    def init(self):

        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)

        self.settings = self.config()

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

        self.layout = QGraphicsGridLayout(self.applet)
        self.layout.setColumnSpacing(0,5.0)

        self.lblTitle = Plasma.Label(self.applet)
        self.lblTitle.nativeWidget().setText(
                                        ki18n("Stuff to get back").toString())
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setStyleSheet("""QLabel {
                                                text-align:center;
                                                font-style: italic;
                                                font-weight: bold;}""")
        self.layout.addItem(self.lblTitle,0,0,1,3)

        self.btnAdd = Plasma.PushButton(self.applet)
        self.btnAdd.nativeWidget().setGuiItem(KStandardGuiItem.Add)
        self.layout.addItem(self.btnAdd,1,0)

        self.btnRemove = Plasma.PushButton(self.applet)
        self.btnRemove.nativeWidget().setGuiItem(KStandardGuiItem.Remove)
        self.layout.addItem(self.btnRemove,1,2)

        self.db = GSBDbModel()

        self.view = Plasma.TreeView(self.applet)
        self.view.setModel(self.db)
        self.view.nativeWidget().setColumnHidden(self.db.IDCOL,True)
        self.view.nativeWidget().setRootIsDecorated(False)
        self.view.nativeWidget().setExpandsOnDoubleClick(False)
        self.view.nativeWidget().setItemsExpandable(False)
        self.view.setStyleSheet("""
            QTreeView {
                background-color: transparent;
                }
                QTreeView::item { padding-top:10px; padding-bottom: 10px; }
            """)
        self.view.nativeWidget().header().resizeSections(
                                                QHeaderView.ResizeToContents)
        self.view.nativeWidget().setItemDelegate(
                                            LoanDelegate(
                                                    self.applet,
                                                    self.view.nativeWidget()))


        self.layout.addItem(self.view,2,0,1,3)

        self.setLayout(self.layout)

        self.btnAdd.clicked.connect(self.add_loan)
        self.btnRemove.clicked.connect(self.remove_loan)
    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)
Exemple #6
0
class KTorrentView(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)

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

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

        self.layout = QGraphicsGridLayout(self.applet)
        self.layout.setColumnSpacing(0,5.0)
        
        self.setLayout(self.layout)
        self.resize(500,200)
Exemple #7
0
    def __init__(self, parent=None, **kwargs):
        super().__init__(parent, **kwargs)
        self.__layoutMode = GraphicsThumbnailGrid.AutoReflow
        self.__columnCount = -1
        self.__thumbnails = []  # type: List[GraphicsThumbnailWidget]
        #: The current 'focused' thumbnail item. This is the item that last
        #: received the keyboard focus (though it does not necessarily have
        #: it now)
        self.__current = None  # type: Optional[GraphicsThumbnailWidget]
        self.__reflowPending = False

        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.setContentsMargins(10, 10, 10, 10)
        # NOTE: Keeping a reference to the layout. self.layout()
        # returns a QGraphicsLayout wrapper (i.e. strips the
        # QGraphicsGridLayout-nes of the object).
        self.__layout = QGraphicsGridLayout()
        self.__layout.setContentsMargins(0, 0, 0, 0)
        self.__layout.setSpacing(10)
        self.setLayout(self.__layout)
Exemple #8
0
 def __init__(self, parent=None):
     QGraphicsWidget.__init__(self, parent)
     self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
     self.setContentsMargins(10, 10, 10, 10)
     layout = QGraphicsGridLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(10)
     self.setLayout(layout)
Exemple #9
0
    def __init__(self,
                 parent=None,
                 direction=Qt.LeftToRight,
                 node=None,
                 icon=None,
                 iconSize=None,
                 **args):
        QGraphicsWidget.__init__(self, parent, **args)
        self.setAcceptedMouseButtons(Qt.NoButton)
        self.__direction = direction

        self.setLayout(QGraphicsLinearLayout(Qt.Horizontal))

        # Set the maximum size, otherwise the layout can't grow beyond its
        # sizeHint (and we need it to grow so the widget can grow and keep the
        # contents centered vertically.
        self.layout().setMaximumSize(QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX))

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

        self.__iconSize = iconSize or QSize(64, 64)
        self.__icon = icon

        self.__iconItem = QGraphicsPixmapItem(self)
        self.__iconLayoutItem = GraphicsItemLayoutItem(item=self.__iconItem)

        self.__channelLayout = QGraphicsGridLayout()
        self.__channelAnchors = []

        if self.__direction == Qt.LeftToRight:
            self.layout().addItem(self.__iconLayoutItem)
            self.layout().addItem(self.__channelLayout)
            channel_alignemnt = Qt.AlignRight

        else:
            self.layout().addItem(self.__channelLayout)
            self.layout().addItem(self.__iconLayoutItem)
            channel_alignemnt = Qt.AlignLeft

        self.layout().setAlignment(self.__iconLayoutItem, Qt.AlignCenter)
        self.layout().setAlignment(self.__channelLayout,
                                   Qt.AlignVCenter | channel_alignemnt)

        if node is not None:
            self.setSchemeNode(node)
    def replot_experiments(self):
        """Replot the whole quality plot.
        """
        self.scene.clear()
        labels = []

        max_dist = numpy.nanmax(list(filter(None, self.distances)))
        rug_widgets = []

        group_pen = QPen(Qt.black)
        group_pen.setWidth(2)
        group_pen.setCapStyle(Qt.RoundCap)
        background_pen = QPen(QColor(0, 0, 250, 150))
        background_pen.setWidth(1)
        background_pen.setCapStyle(Qt.RoundCap)

        main_widget = QGraphicsWidget()
        layout = QGraphicsGridLayout()
        attributes = self.data.domain.attributes
        if self.data is not None:
            for (group, indices), dist_vec in zip(self.groups, self.distances):
                indices_set = set(indices)
                rug_items = []
                if dist_vec is not None:
                    for i, attr in enumerate(attributes):
                        # Is this a within group distance or background
                        in_group = i in indices_set
                        if in_group:
                            rug_item = ClickableRugItem(dist_vec[i] / max_dist,
                                           1.0, self.on_rug_item_clicked)
                            rug_item.setPen(group_pen)
                            tooltip = experiment_description(attr)
                            rug_item.setToolTip(tooltip)
                            rug_item.group_index = indices.index(i)
                            rug_item.setZValue(rug_item.zValue() + 1)
                        else:
                            rug_item = ClickableRugItem(dist_vec[i] / max_dist,
                                           0.85, self.on_rug_item_clicked)
                            rug_item.setPen(background_pen)
                            tooltip = experiment_description(attr)
                            rug_item.setToolTip(tooltip)

                        rug_item.group = group
                        rug_item.index = i
                        rug_item.in_group = in_group

                        rug_items.append(rug_item)

                rug_widget = RugGraphicsWidget(parent=main_widget)
                rug_widget.set_rug(rug_items)

                rug_widgets.append(rug_widget)

                label = group_label(self.selected_split_by_labels(), group)
                label_item = QGraphicsSimpleTextItem(label, main_widget)
                label_item = GraphicsSimpleTextLayoutItem(label_item, parent=layout)
                label_item.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                labels.append(label_item)

        for i, (label, rug_w) in enumerate(zip(labels, rug_widgets)):
            layout.addItem(label, i, 0, Qt.AlignVCenter)
            layout.addItem(rug_w, i, 1)
            layout.setRowMaximumHeight(i, 30)

        main_widget.setLayout(layout)
        self.scene.addItem(main_widget)
        self.main_widget = main_widget
        self.rug_widgets = rug_widgets
        self.labels = labels
        self.on_view_resize(self.scene_view.size())
Exemple #11
0
    def init(self):
	"""init method for the plasmoid. GUI stuff is located here."""
	
	self.moduller=self.link.Network.Firewall[dbus.String("iptables")].listModules()
	
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.Square)
        self.resize(450,250)
 
        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)
        self.layout=QGraphicsGridLayout(self.applet)
        
        label = Plasma.Label(self.applet)
        label.setText("<h1>Firewall Plasmoid</h1>")
        self.kilit=Plasma.IconWidget(self.applet)
        self.bilgi_label=Plasma.Label(self.applet)
        
        self.baslat_pb=Plasma.PushButton(self.applet)
        self.baslat_pb.setText("Start")
        self.durdur_pb=Plasma.PushButton(self.applet)
        self.durdur_pb.setText("Stop")
	print "osman"
        if self.link.Network.Firewall[dbus.String("iptables")].getState()==dbus.String(u"on"):
	    self.bilgi_label.setText("<p style='color:green'>Firewall is working now.</p>")
	    self.kilit.setIcon("object-locked")
	    self.kilit.setMaximumSize(32,32)
	    self.kilit.setMinimumSize(32,32)
	    self.baslat_pb.setEnabled(False)
	    
	else:
	    self.bilgi_label.setText("<p style='color:red'>Firewall is stopped now.</p>")
	    self.kilit.setMaximumSize(32,32)
	    self.kilit.setMinimumSize(32,32)
	    self.kilit.setIcon("object-unlocked")
	    self.durdur_pb.setEnabled(False)
	
	self.bilgilendirme_baslik=Plasma.Label(self.applet)
	self.bilgilendirme_baslik.setText("Latest news:")
	
	self.bilgilendirme=Plasma.Label(self.applet)
	self.bilgilendirme.setText("Firewall Plasmoid has been started.")

        gelen_simge=Plasma.IconWidget(self.applet)
        gelen_simge.setIcon("application-x-smb-workgroup")
        paylasim_simge=Plasma.IconWidget(self.applet)
        paylasim_simge.setIcon("application-x-smb-server")
        giden_simge=Plasma.IconWidget(self.applet)
        giden_simge.setIcon("security-medium")
        
        self.kutular=[]
        sayi=0
        for i in self.moduller:
	    self.kutular.append(Plasma.CheckBox(self.applet))
	    self.kutular[sayi].setText(self.link.Network.Firewall[dbus.String("iptables")].moduleInfo(i)[0])
	    sayi+=1
	    
        
        self.layout.addItem(label, 0, 0,1,4)
        self.layout.addItem(self.kilit, 1,0)
        self.layout.addItem(self.bilgi_label,1,1)
        self.layout.addItem(self.baslat_pb,1,2)
        self.layout.addItem(self.durdur_pb,1,3)
        self.layout.addItem(gelen_simge,2,0,1,1)
        self.layout.addItem(paylasim_simge,3,0,1,1)
        self.layout.addItem(giden_simge,4,0,1,1)
        self.layout.addItem(self.bilgilendirme_baslik, 5,0,1,1)
        self.layout.addItem(self.bilgilendirme, 5,1,1,4)
        m=0
        for i in range(0,len(self.moduller)):
	    self.layout.addItem(self.kutular[m], m+2,1,1,4)
	    m+=1
        self.applet.setLayout(self.layout)        
        
        QObject.connect(self.baslat_pb, SIGNAL("clicked()"), self.baslat)
        QObject.connect(self.durdur_pb, SIGNAL("clicked()"), self.durdur)
        
        fonksiyonlar=[self.blockGelen, self.paylasim, self.blockGiden]
        for i in range(0, len(self.moduller)):
	    QObject.connect(self.kutular[i], SIGNAL("toggled(bool)"), fonksiyonlar[i])
	    
	self.bilgilendirme_iletileri=["Incoming connections was blocked successfully.",
	"Sharing internet is successful.",
	"Outgoing connections was blocked successfully."]
        
        self.link.listenSignals("Network.Firewall", self.handler)
Exemple #12
0
class HelloWorldApplet(plasmascript.Applet):
    def __init__(self,parent,args=None):
	"""Regular init method for the class of the plasmoid"""
        plasmascript.Applet.__init__(self,parent)
        self.link=comar.Link()
        
    def baslat(self):
	"""Method for openning the firewall manager"""
	try:#################try blogu eklendi burasi yapilacak.
	    self.link.Network.Firewall[dbus.String("iptables")].setState("on")
	    self.bilgi_label.setText("<p style='color:green'>Firewall is working now.</p>")
	    self.bilgilendirme.setText("Firewall has been started succesfully.")
	    self.baslat_pb.setEnabled(False)
	    self.durdur_pb.setEnabled(True)
	except dbus.exceptions.DBusException as hata:
	    self.bilgilendirme.setText(u"ERROR: Operation didn't perform.")
	    #print "HATA=",hata
	    

    def durdur(self):
	"""Method for closing the firewall manager"""
	try:
	    self.link.Network.Firewall[dbus.String("iptables")].setState("off")
	    self.bilgi_label.setText("<p style='color:red'>Firewall is stopped now.</p>")
	    self.bilgilendirme.setText("Firewall has been stopped succesfully.")
	    self.durdur_pb.setEnabled(False)
	    self.baslat_pb.setEnabled(True)
	except dbus.exceptions.DBusException as hata:
	    self.bilgilendirme.setText(u"ERROR: Operation didn't perform.")
	    
	
    def blockGelen(self, value):
        if self.kutular[0].isChecked():
	    self.link.Network.Firewall[dbus.String("iptables")].setModuleState("block_incoming","on")
	    self.bilgilendirme.setText(self.bilgilendirme_iletileri[0])
	else:
	    self.link.Network.Firewall[dbus.String("iptables")].setModuleState("block_incoming","off")
	    self.bilgilendirme.setText("Incoming connection blocking was stopped")
	    
    def paylasim(self, value):
        if self.kutular[1].isChecked():
	    self.link.Network.Firewall[dbus.String("iptables")].setModuleState("internet_sharing","on")
	    self.bilgilendirme.setText(self.bilgilendirme_iletileri[1])
	else:
	    self.link.Network.Firewall[dbus.String("iptables")].setModuleState("internet_sharing","off")
	    self.bilgilendirme.setText("Sharing internet was stopped")

    def blockGiden(self, value):
        if self.kutular[2].isChecked():
	    self.link.Network.Firewall[dbus.String("iptables")].setModuleState("block_outgoing","on")
	    self.bilgilendirme.setText(self.bilgilendirme_iletileri[2])
	else:
	    self.link.Network.Firewall[dbus.String("iptables")].setModuleState("block_outgoing","off")
	    self.bilgilendirme.setText("Outgoing connection blocking was stopped")
	
    def init(self):
	"""init method for the plasmoid. GUI stuff is located here."""
	
	self.moduller=self.link.Network.Firewall[dbus.String("iptables")].listModules()
	
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.Square)
        self.resize(450,250)
 
        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)
        self.layout=QGraphicsGridLayout(self.applet)
        
        label = Plasma.Label(self.applet)
        label.setText("<h1>Firewall Plasmoid</h1>")
        self.kilit=Plasma.IconWidget(self.applet)
        self.bilgi_label=Plasma.Label(self.applet)
        
        self.baslat_pb=Plasma.PushButton(self.applet)
        self.baslat_pb.setText("Start")
        self.durdur_pb=Plasma.PushButton(self.applet)
        self.durdur_pb.setText("Stop")
	print "osman"
        if self.link.Network.Firewall[dbus.String("iptables")].getState()==dbus.String(u"on"):
	    self.bilgi_label.setText("<p style='color:green'>Firewall is working now.</p>")
	    self.kilit.setIcon("object-locked")
	    self.kilit.setMaximumSize(32,32)
	    self.kilit.setMinimumSize(32,32)
	    self.baslat_pb.setEnabled(False)
	    
	else:
	    self.bilgi_label.setText("<p style='color:red'>Firewall is stopped now.</p>")
	    self.kilit.setMaximumSize(32,32)
	    self.kilit.setMinimumSize(32,32)
	    self.kilit.setIcon("object-unlocked")
	    self.durdur_pb.setEnabled(False)
	
	self.bilgilendirme_baslik=Plasma.Label(self.applet)
	self.bilgilendirme_baslik.setText("Latest news:")
	
	self.bilgilendirme=Plasma.Label(self.applet)
	self.bilgilendirme.setText("Firewall Plasmoid has been started.")

        gelen_simge=Plasma.IconWidget(self.applet)
        gelen_simge.setIcon("application-x-smb-workgroup")
        paylasim_simge=Plasma.IconWidget(self.applet)
        paylasim_simge.setIcon("application-x-smb-server")
        giden_simge=Plasma.IconWidget(self.applet)
        giden_simge.setIcon("security-medium")
        
        self.kutular=[]
        sayi=0
        for i in self.moduller:
	    self.kutular.append(Plasma.CheckBox(self.applet))
	    self.kutular[sayi].setText(self.link.Network.Firewall[dbus.String("iptables")].moduleInfo(i)[0])
	    sayi+=1
	    
        
        self.layout.addItem(label, 0, 0,1,4)
        self.layout.addItem(self.kilit, 1,0)
        self.layout.addItem(self.bilgi_label,1,1)
        self.layout.addItem(self.baslat_pb,1,2)
        self.layout.addItem(self.durdur_pb,1,3)
        self.layout.addItem(gelen_simge,2,0,1,1)
        self.layout.addItem(paylasim_simge,3,0,1,1)
        self.layout.addItem(giden_simge,4,0,1,1)
        self.layout.addItem(self.bilgilendirme_baslik, 5,0,1,1)
        self.layout.addItem(self.bilgilendirme, 5,1,1,4)
        m=0
        for i in range(0,len(self.moduller)):
	    self.layout.addItem(self.kutular[m], m+2,1,1,4)
	    m+=1
        self.applet.setLayout(self.layout)        
        
        QObject.connect(self.baslat_pb, SIGNAL("clicked()"), self.baslat)
        QObject.connect(self.durdur_pb, SIGNAL("clicked()"), self.durdur)
        
        fonksiyonlar=[self.blockGelen, self.paylasim, self.blockGiden]
        for i in range(0, len(self.moduller)):
	    QObject.connect(self.kutular[i], SIGNAL("toggled(bool)"), fonksiyonlar[i])
	    
	self.bilgilendirme_iletileri=["Incoming connections was blocked successfully.",
	"Sharing internet is successful.",
	"Outgoing connections was blocked successfully."]
        
        self.link.listenSignals("Network.Firewall", self.handler)
        
        
    def handler(self, *args):
	"""Handler method for receiving signals from Comar"""
	if self.link.Network.Firewall[dbus.String("iptables")].getState()==dbus.String(u"on"):
	    self.bilgi_label.setText("<p style='color:green'>Firewall is working now.</p>")
	    self.kilit.setIcon("object-locked")
	    self.durdur_pb.setEnabled(True)
	    self.baslat_pb.setEnabled(False)
	    #print "baslat sinyali"
	else:
	    self.bilgi_label.setText("<p style='color:red'>Firewall is stopped now.</p>")
	    self.kilit.setIcon("object-unlocked")
	    self.durdur_pb.setEnabled(False)
	    self.baslat_pb.setEnabled(True)
	    #print "durdur sinyali"
	
	if self.link.Network.Firewall[dbus.String("iptables")].getModuleState("block_incoming")==dbus.String(u"on"):
	    self.kutular[0].setChecked(True)
	    #print "ilk kutu tiklandi sinyali"
	else:
	    self.kutular[0].setChecked(False)
	    #print "ilk kutu tiki kaldirildi sinyali"
	    
	if self.link.Network.Firewall[dbus.String("iptables")].getModuleState("internet_sharing")==dbus.String(u"on"):
	    self.kutular[1].setChecked(True)
	    #print "ikinci kutu tiklandi sinyali"
	else:
	    self.kutular[1].setChecked(False)
	    #print "ikinci kutu tiki kaldirildi sinyali"
	
	if self.link.Network.Firewall[dbus.String("iptables")].getModuleState("block_outgoing")==dbus.String(u"on"):
	    self.kutular[2].setChecked(True)
	    #print "ucuncu kutu tiklandi sinyali"
	else:
	    self.kutular[2].setChecked(False)
Exemple #13
0
    def __updateState(self):
        """
        Update the widget with the new source/sink node signal descriptions.
        """
        widget = QGraphicsWidget()
        widget.setLayout(QGraphicsGridLayout())

        # Space between left and right anchors
        widget.layout().setHorizontalSpacing(50)

        left_node = EditLinksNode(self,
                                  direction=Qt.LeftToRight,
                                  node=self.source)

        left_node.setSizePolicy(QSizePolicy.MinimumExpanding,
                                QSizePolicy.MinimumExpanding)

        right_node = EditLinksNode(self,
                                   direction=Qt.RightToLeft,
                                   node=self.sink)

        right_node.setSizePolicy(QSizePolicy.MinimumExpanding,
                                 QSizePolicy.MinimumExpanding)

        left_node.setMinimumWidth(150)
        right_node.setMinimumWidth(150)

        widget.layout().addItem(
            left_node,
            0,
            0,
        )
        widget.layout().addItem(
            right_node,
            0,
            1,
        )

        title_template = "<center><b>{0}<b></center>"

        left_title = GraphicsTextWidget(self)
        left_title.setHtml(title_template.format(escape(self.source.title)))
        left_title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        right_title = GraphicsTextWidget(self)
        right_title.setHtml(title_template.format(escape(self.sink.title)))
        right_title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        widget.layout().addItem(left_title,
                                1,
                                0,
                                alignment=Qt.AlignHCenter | Qt.AlignTop)
        widget.layout().addItem(right_title,
                                1,
                                1,
                                alignment=Qt.AlignHCenter | Qt.AlignTop)

        widget.setParentItem(self)

        max_w = max(
            left_node.sizeHint(Qt.PreferredSize).width(),
            right_node.sizeHint(Qt.PreferredSize).width())

        # fix same size
        left_node.setMinimumWidth(max_w)
        right_node.setMinimumWidth(max_w)
        left_title.setMinimumWidth(max_w)
        right_title.setMinimumWidth(max_w)

        self.layout().addItem(widget)
        self.layout().activate()

        self.sourceNodeWidget = left_node
        self.sinkNodeWidget = right_node
        self.sourceNodeTitle = left_title
        self.sinkNodeTitle = right_title
Exemple #14
0
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()
Exemple #15
0
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)
Exemple #16
0
class HelloWorldApplet(plasmascript.Applet):
    def __init__(self, parent, args=None):
        """Regular init method for the class of the plasmoid"""
        plasmascript.Applet.__init__(self, parent)
        self.link = comar.Link()

    def baslat(self):
        """Method for openning the firewall manager"""
        try:  #################try blogu eklendi burasi yapilacak.
            self.link.Network.Firewall[dbus.String("iptables")].setState("on")
            self.bilgi_label.setText(
                "<p style='color:green'>Firewall is working now.</p>")
            self.bilgilendirme.setText(
                "Firewall has been started succesfully.")
            self.baslat_pb.setEnabled(False)
            self.durdur_pb.setEnabled(True)
        except dbus.exceptions.DBusException as hata:
            self.bilgilendirme.setText(u"ERROR: Operation didn't perform.")
            #print "HATA=",hata

    def durdur(self):
        """Method for closing the firewall manager"""
        try:
            self.link.Network.Firewall[dbus.String("iptables")].setState("off")
            self.bilgi_label.setText(
                "<p style='color:red'>Firewall is stopped now.</p>")
            self.bilgilendirme.setText(
                "Firewall has been stopped succesfully.")
            self.durdur_pb.setEnabled(False)
            self.baslat_pb.setEnabled(True)
        except dbus.exceptions.DBusException as hata:
            self.bilgilendirme.setText(u"ERROR: Operation didn't perform.")

    def blockGelen(self, value):
        if self.kutular[0].isChecked():
            self.link.Network.Firewall[dbus.String("iptables")].setModuleState(
                "block_incoming", "on")
            self.bilgilendirme.setText(self.bilgilendirme_iletileri[0])
        else:
            self.link.Network.Firewall[dbus.String("iptables")].setModuleState(
                "block_incoming", "off")
            self.bilgilendirme.setText(
                "Incoming connection blocking was stopped")

    def paylasim(self, value):
        if self.kutular[1].isChecked():
            self.link.Network.Firewall[dbus.String("iptables")].setModuleState(
                "internet_sharing", "on")
            self.bilgilendirme.setText(self.bilgilendirme_iletileri[1])
        else:
            self.link.Network.Firewall[dbus.String("iptables")].setModuleState(
                "internet_sharing", "off")
            self.bilgilendirme.setText("Sharing internet was stopped")

    def blockGiden(self, value):
        if self.kutular[2].isChecked():
            self.link.Network.Firewall[dbus.String("iptables")].setModuleState(
                "block_outgoing", "on")
            self.bilgilendirme.setText(self.bilgilendirme_iletileri[2])
        else:
            self.link.Network.Firewall[dbus.String("iptables")].setModuleState(
                "block_outgoing", "off")
            self.bilgilendirme.setText(
                "Outgoing connection blocking was stopped")

    def init(self):
        """init method for the plasmoid. GUI stuff is located here."""

        self.moduller = self.link.Network.Firewall[dbus.String(
            "iptables")].listModules()

        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.Square)
        self.resize(450, 250)

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

        label = Plasma.Label(self.applet)
        label.setText("<h1>Firewall Plasmoid</h1>")
        self.kilit = Plasma.IconWidget(self.applet)
        self.bilgi_label = Plasma.Label(self.applet)

        self.baslat_pb = Plasma.PushButton(self.applet)
        self.baslat_pb.setText("Start")
        self.durdur_pb = Plasma.PushButton(self.applet)
        self.durdur_pb.setText("Stop")
        print "osman"
        if self.link.Network.Firewall[dbus.String(
                "iptables")].getState() == dbus.String(u"on"):
            self.bilgi_label.setText(
                "<p style='color:green'>Firewall is working now.</p>")
            self.kilit.setIcon("object-locked")
            self.kilit.setMaximumSize(32, 32)
            self.kilit.setMinimumSize(32, 32)
            self.baslat_pb.setEnabled(False)

        else:
            self.bilgi_label.setText(
                "<p style='color:red'>Firewall is stopped now.</p>")
            self.kilit.setMaximumSize(32, 32)
            self.kilit.setMinimumSize(32, 32)
            self.kilit.setIcon("object-unlocked")
            self.durdur_pb.setEnabled(False)

        self.bilgilendirme_baslik = Plasma.Label(self.applet)
        self.bilgilendirme_baslik.setText("Latest news:")

        self.bilgilendirme = Plasma.Label(self.applet)
        self.bilgilendirme.setText("Firewall Plasmoid has been started.")

        gelen_simge = Plasma.IconWidget(self.applet)
        gelen_simge.setIcon("application-x-smb-workgroup")
        paylasim_simge = Plasma.IconWidget(self.applet)
        paylasim_simge.setIcon("application-x-smb-server")
        giden_simge = Plasma.IconWidget(self.applet)
        giden_simge.setIcon("security-medium")

        self.kutular = []
        sayi = 0
        for i in self.moduller:
            self.kutular.append(Plasma.CheckBox(self.applet))
            self.kutular[sayi].setText(self.link.Network.Firewall[dbus.String(
                "iptables")].moduleInfo(i)[0])
            sayi += 1

        self.layout.addItem(label, 0, 0, 1, 4)
        self.layout.addItem(self.kilit, 1, 0)
        self.layout.addItem(self.bilgi_label, 1, 1)
        self.layout.addItem(self.baslat_pb, 1, 2)
        self.layout.addItem(self.durdur_pb, 1, 3)
        self.layout.addItem(gelen_simge, 2, 0, 1, 1)
        self.layout.addItem(paylasim_simge, 3, 0, 1, 1)
        self.layout.addItem(giden_simge, 4, 0, 1, 1)
        self.layout.addItem(self.bilgilendirme_baslik, 5, 0, 1, 1)
        self.layout.addItem(self.bilgilendirme, 5, 1, 1, 4)
        m = 0
        for i in range(0, len(self.moduller)):
            self.layout.addItem(self.kutular[m], m + 2, 1, 1, 4)
            m += 1
        self.applet.setLayout(self.layout)

        QObject.connect(self.baslat_pb, SIGNAL("clicked()"), self.baslat)
        QObject.connect(self.durdur_pb, SIGNAL("clicked()"), self.durdur)

        fonksiyonlar = [self.blockGelen, self.paylasim, self.blockGiden]
        for i in range(0, len(self.moduller)):
            QObject.connect(self.kutular[i], SIGNAL("toggled(bool)"),
                            fonksiyonlar[i])

        self.bilgilendirme_iletileri = [
            "Incoming connections was blocked successfully.",
            "Sharing internet is successful.",
            "Outgoing connections was blocked successfully."
        ]

        self.link.listenSignals("Network.Firewall", self.handler)

    def handler(self, *args):
        """Handler method for receiving signals from Comar"""
        if self.link.Network.Firewall[dbus.String(
                "iptables")].getState() == dbus.String(u"on"):
            self.bilgi_label.setText(
                "<p style='color:green'>Firewall is working now.</p>")
            self.kilit.setIcon("object-locked")
            self.durdur_pb.setEnabled(True)
            self.baslat_pb.setEnabled(False)
            #print "baslat sinyali"
        else:
            self.bilgi_label.setText(
                "<p style='color:red'>Firewall is stopped now.</p>")
            self.kilit.setIcon("object-unlocked")
            self.durdur_pb.setEnabled(False)
            self.baslat_pb.setEnabled(True)
            #print "durdur sinyali"

        if self.link.Network.Firewall[dbus.String("iptables")].getModuleState(
                "block_incoming") == dbus.String(u"on"):
            self.kutular[0].setChecked(True)
            #print "ilk kutu tiklandi sinyali"
        else:
            self.kutular[0].setChecked(False)
            #print "ilk kutu tiki kaldirildi sinyali"

        if self.link.Network.Firewall[dbus.String("iptables")].getModuleState(
                "internet_sharing") == dbus.String(u"on"):
            self.kutular[1].setChecked(True)
            #print "ikinci kutu tiklandi sinyali"
        else:
            self.kutular[1].setChecked(False)
            #print "ikinci kutu tiki kaldirildi sinyali"

        if self.link.Network.Firewall[dbus.String("iptables")].getModuleState(
                "block_outgoing") == dbus.String(u"on"):
            self.kutular[2].setChecked(True)
            #print "ucuncu kutu tiklandi sinyali"
        else:
            self.kutular[2].setChecked(False)
Exemple #17
0
class OWDistanceMap(widget.OWWidget):
    name = "Distance Map"
    description = "Visualize a distance matrix."
    icon = "icons/DistanceMatrix.svg"
    priority = 1200

    inputs = [("Distances", Orange.misc.DistMatrix, "set_distances")]
    outputs = [("Data", Orange.data.Table), ("Features", widget.AttributeList)]

    #: type of ordering to apply to matrix rows/columns
    NoOrdering, Clustering, OrderedClustering = 0, 1, 2

    sorting = settings.Setting(NoOrdering)

    colormap = settings.Setting(_default_colormap_index)
    color_gamma = settings.Setting(0.0)
    color_low = settings.Setting(0.0)
    color_high = settings.Setting(1.0)

    annotation_idx = settings.Setting(0)

    autocommit = settings.Setting(True)

    want_graph = True

    # Disable clustering for inputs bigger than this
    _MaxClustering = 3000

    # Disable cluster leaf ordering for inputs bigger than this
    _MaxOrderedClustering = 1000

    def __init__(self):
        super().__init__()

        self.matrix = None
        self._tree = None
        self._ordered_tree = None
        self._sorted_matrix = None
        self._sort_indices = None
        self._selection = None

        box = gui.widgetBox(self.controlArea, "Element sorting", margin=0)
        self.sorting_cb = gui.comboBox(
            box, self, "sorting",
            items=["None", "Clustering", "Clustering with ordered leaves"],
            callback=self._invalidate_ordering)

        box = gui.widgetBox(self.controlArea, "Colors")

        self.colormap_cb = gui.comboBox(
            box, self, "colormap", callback=self._update_color
        )
        self.colormap_cb.setIconSize(QSize(64, 16))
        self.palettes = list(_color_palettes)

        init_color_combo(self.colormap_cb, self.palettes, QSize(64, 16))
        self.colormap_cb.setCurrentIndex(self.colormap)

        form = QFormLayout(
            formAlignment=Qt.AlignLeft,
            labelAlignment=Qt.AlignLeft,
            fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow
        )
#         form.addRow(
#             "Gamma",
#             gui.hSlider(box, self, "color_gamma", minValue=0.0, maxValue=1.0,
#                         step=0.05, ticks=True, intOnly=False,
#                         createLabel=False, callback=self._update_color)
#         )
        form.addRow(
            "Low",
            gui.hSlider(box, self, "color_low", minValue=0.0, maxValue=1.0,
                        step=0.05, ticks=True, intOnly=False,
                        createLabel=False, callback=self._update_color)
        )
        form.addRow(
            "High",
            gui.hSlider(box, self, "color_high", minValue=0.0, maxValue=1.0,
                        step=0.05, ticks=True, intOnly=False,
                        createLabel=False, callback=self._update_color)
        )
        box.layout().addLayout(form)

        box = gui.widgetBox(self.controlArea, "Annotations")
        self.annot_combo = gui.comboBox(box, self, "annotation_idx",
                                        callback=self._invalidate_annotations,
                                        contentsLength=12)
        self.annot_combo.setModel(itemmodels.VariableListModel())
        self.annot_combo.model()[:] = ["None", "Enumeration"]
        self.controlArea.layout().addStretch()

        gui.auto_commit(self.controlArea, self, "autocommit",
                        "Send data", "Auto send is on")
        self.inline_graph_report()

        self.view = pg.GraphicsView(background="w")
        self.mainArea.layout().addWidget(self.view)

        self.grid_widget = pg.GraphicsWidget()
        self.grid = QGraphicsGridLayout()
        self.grid_widget.setLayout(self.grid)

        self.viewbox = pg.ViewBox(enableMouse=False, enableMenu=False)
        self.viewbox.setAcceptedMouseButtons(Qt.NoButton)
        self.viewbox.setAcceptHoverEvents(False)
        self.grid.addItem(self.viewbox, 1, 1)

        self.left_dendrogram = DendrogramWidget(
            self.grid_widget, orientation=DendrogramWidget.Left,
            selectionMode=DendrogramWidget.NoSelection,
            hoverHighlightEnabled=False
        )
        self.left_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.left_dendrogram.setAcceptHoverEvents(False)

        self.top_dendrogram = DendrogramWidget(
            self.grid_widget, orientation=DendrogramWidget.Top,
            selectionMode=DendrogramWidget.NoSelection,
            hoverHighlightEnabled=False
        )
        self.top_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.top_dendrogram.setAcceptHoverEvents(False)

        self.grid.addItem(self.left_dendrogram, 1, 0)
        self.grid.addItem(self.top_dendrogram, 0, 1)

        self.right_labels = TextList(
            alignment=Qt.AlignLeft)

        self.bottom_labels = TextList(
            orientation=Qt.Horizontal, alignment=Qt.AlignRight)

        self.grid.addItem(self.right_labels, 1, 2)
        self.grid.addItem(self.bottom_labels, 2, 1)

        self.view.setCentralItem(self.grid_widget)

        self.left_dendrogram.hide()
        self.top_dendrogram.hide()
        self.right_labels.hide()
        self.bottom_labels.hide()

        self.matrix_item = None
        self.dendrogram = None

        self.grid_widget.scene().installEventFilter(self)
        self.graphButton.clicked.connect(self.save_graph)

    def set_distances(self, matrix):
        self.clear()
        self.error(0)
        if matrix is not None:
            N, _ = matrix.shape
            if N < 2:
                self.error(0, "Empty distance matrix.")
                matrix = None

        self.matrix = matrix
        if matrix is not None:
            self.set_items(matrix.row_items, matrix.axis)
        else:
            self.set_items(None)

        if matrix is not None:
            N, _ = matrix.shape
        else:
            N = 0

        model = self.sorting_cb.model()
        item = model.item(2)

        msg = None
        if N > OWDistanceMap._MaxOrderedClustering:
            item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
            if self.sorting == OWDistanceMap.OrderedClustering:
                self.sorting = OWDistanceMap.Clustering
                msg = "Cluster ordering was disabled due to the input " \
                      "matrix being to big"
        else:
            item.setFlags(item.flags() | Qt.ItemIsEnabled)

        item = model.item(1)
        if N > OWDistanceMap._MaxClustering:
            item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
            if self.sorting == OWDistanceMap.Clustering:
                self.sorting = OWDistanceMap.NoOrdering
            msg = "Clustering was disabled due to the input " \
                  "matrix being to big"
        else:
            item.setFlags(item.flags() | Qt.ItemIsEnabled)

        self.information(1, msg)

    def set_items(self, items, axis=1):
        self.items = items
        model = self.annot_combo.model()
        if items is None:
            model[:] = ["None", "Enumeration"]
        elif not axis:
            model[:] = ["None", "Enumeration", "Attribute names"]
            self.annotation_idx = 2
        elif isinstance(items, Orange.data.Table):
            model[:] = (["None", "Enumeration"] +
                        list(items.domain) + list(items.domain.metas))
        elif isinstance(items, list) and \
                all(isinstance(item, Orange.data.Variable) for item in items):
            model[:] = ["None", "Enumeration", "Name"]
        else:
            model[:] = ["None", "Enumeration"]
        self.annotation_idx = min(self.annotation_idx, len(model) - 1)

    def clear(self):
        self.matrix = None
        self.cluster = None
        self._tree = None
        self._ordered_tree = None
        self._sorted_matrix = None
        self._selection = []
        self._clear_plot()

    def handleNewSignals(self):
        if self.matrix is not None:
            self._update_ordering()
            self._setup_scene()
            self._update_labels()
        self.unconditional_commit()

    def _clear_plot(self):
        def remove(item):
            item.setParentItem(None)
            item.scene().removeItem(item)

        if self.matrix_item is not None:
            self.matrix_item.selectionChanged.disconnect(
                self._invalidate_selection)
            remove(self.matrix_item)
            self.matrix_item = None

        self._set_displayed_dendrogram(None)
        self._set_labels(None)

    def _cluster_tree(self):
        if self._tree is None:
            self._tree = hierarchical.dist_matrix_clustering(self.matrix)
        return self._tree

    def _ordered_cluster_tree(self):
        if self._ordered_tree is None:
            tree = self._cluster_tree()
            self._ordered_tree = \
                hierarchical.optimal_leaf_ordering(tree, self.matrix)
        return self._ordered_tree

    def _setup_scene(self):
        self._clear_plot()
        self.matrix_item = DistanceMapItem(self._sorted_matrix)
        # Scale the y axis to compensate for pg.ViewBox's y axis invert
        self.matrix_item.scale(1, -1)
        self.viewbox.addItem(self.matrix_item)
        # Set fixed view box range.
        h, w = self._sorted_matrix.shape
        self.viewbox.setRange(QRectF(0, -h, w, h), padding=0)

        self.matrix_item.selectionChanged.connect(self._invalidate_selection)

        if self.sorting == OWDistanceMap.NoOrdering:
            tree = None
        elif self.sorting == OWDistanceMap.Clustering:
            tree = self._cluster_tree()
        elif self.sorting == OWDistanceMap.OrderedClustering:
            tree = self._ordered_cluster_tree()

        self._set_displayed_dendrogram(tree)

        self._update_color()

    def _set_displayed_dendrogram(self, root):
        self.left_dendrogram.set_root(root)
        self.top_dendrogram.set_root(root)
        self.left_dendrogram.setVisible(root is not None)
        self.top_dendrogram.setVisible(root is not None)

        constraint = 0 if root is None else -1  # 150
        self.left_dendrogram.setMaximumWidth(constraint)
        self.top_dendrogram.setMaximumHeight(constraint)

    def _invalidate_ordering(self):
        self._sorted_matrix = None
        if self.matrix is not None:
            self._update_ordering()
            self._setup_scene()

    def _update_ordering(self):
        if self.sorting == OWDistanceMap.NoOrdering:
            self._sorted_matrix = self.matrix
            self._sort_indices = None
        else:
            if self.sorting == OWDistanceMap.Clustering:
                tree = self._cluster_tree()
            elif self.sorting == OWDistanceMap.OrderedClustering:
                tree = self._ordered_cluster_tree()

            leaves = hierarchical.leaves(tree)
            indices = numpy.array([leaf.value.index for leaf in leaves])
            X = self.matrix
            self._sorted_matrix = X[indices[:, numpy.newaxis],
                                    indices[numpy.newaxis, :]]
            self._sort_indices = indices

    def _invalidate_annotations(self):
        if self.matrix is not None:
            self._update_labels()

    def _update_labels(self, ):
        if self.annotation_idx == 0:
            labels = None
        elif self.annotation_idx == 1:
            labels = [str(i + 1) for i in range(self.matrix.shape[0])]
        elif self.annot_combo.model()[self.annotation_idx] == "Attribute names":
                attr = self.matrix.row_items.domain.attributes
                labels = [str(attr[i]) for i in range(self.matrix.shape[0])]
        elif self.annotation_idx == 2 and \
                isinstance(self.items, widget.AttributeList):
            labels = [v.name for v in self.items]
        elif isinstance(self.items, Orange.data.Table):
            var = self.annot_combo.model()[self.annotation_idx]
            column, _ = self.items.get_column_view(var)
            labels = [var.repr_val(value) for value in column]

        self._set_labels(labels)

    def _set_labels(self, labels):
        self._labels = labels

        if labels and self.sorting != OWDistanceMap.NoOrdering:
            sortind = self._sort_indices
            labels = [labels[i] for i in sortind]

        for textlist in [self.right_labels, self.bottom_labels]:
            textlist.set_labels(labels or [])
            textlist.setVisible(bool(labels))

        constraint = -1 if labels else 0
        self.right_labels.setMaximumWidth(constraint)
        self.bottom_labels.setMaximumHeight(constraint)

    def _update_color(self):
        if self.matrix_item:
            name, colors = self.palettes[self.colormap]
            n, colors = max(colors.items())
            colors = numpy.array(colors, dtype=numpy.ubyte)
            low, high = self.color_low * 255, self.color_high * 255
            points = numpy.linspace(low, high, n)
            space = numpy.linspace(0, 255, 255)

            r = numpy.interp(space, points, colors[:, 0], left=255, right=0)
            g = numpy.interp(space, points, colors[:, 1], left=255, right=0)
            b = numpy.interp(space, points, colors[:, 2], left=255, right=0)
            colortable = numpy.c_[r, g, b]
            self.matrix_item.setLookupTable(colortable)

    def _invalidate_selection(self):
        ranges = self.matrix_item.selections()
        ranges = reduce(iadd, ranges, [])
        indices = reduce(iadd, ranges, [])
        if self.sorting != OWDistanceMap.NoOrdering:
            sortind = self._sort_indices
            indices = [sortind[i] for i in indices]
        self._selection = list(sorted(set(indices)))
        self.commit()

    def commit(self):
        datasubset = None
        featuresubset = None

        if not self._selection:
            pass
        elif isinstance(self.items, Orange.data.Table):
            indices = self._selection
            if self.matrix.axis == 1:
                datasubset = self.items.from_table_rows(self.items, indices)
            elif self.matrix.axis == 0:
                domain = Orange.data.Domain(
                    [self.items.domain[i] for i in indices],
                    self.items.domain.class_vars,
                    self.items.domain.metas)
                datasubset = Orange.data.Table.from_table(domain, self.items)
        elif isinstance(self.items, widget.AttributeList):
            subset = [self.items[i] for i in self._selection]
            featuresubset = widget.AttributeList(subset)

        self.send("Data", datasubset)
        self.send("Features", featuresubset)

    def save_graph(self):
        from Orange.widgets.data.owsave import OWSave

        save_img = OWSave(data=self.grid_widget,
                          file_formats=FileFormat.img_writers)
        save_img.exec_()

    def onDeleteWidget(self):
        super().onDeleteWidget()
        self.clear()

    def send_report(self):
        annot = self.annot_combo.currentText()
        if self.annotation_idx <= 1:
            annot = annot.lower()
        self.report_items((
            ("Sorting", self.sorting_cb.currentText().lower()),
            ("Annotations", annot)
        ))
        if self.matrix is not None:
            self.report_plot(self.grid_widget)
Exemple #18
0
class TaskCoachApplet(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)

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

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

        self.layout = QGraphicsGridLayout(self.applet)
        self.layout.setColumnSpacing(0,5.0)
        
        # using the predefined KGuiItem objects save us a lot of work
        self.btnOpen = Plasma.PushButton(self.applet)
        self.btnOpen.nativeWidget().setGuiItem(KStandardGuiItem.Open)
        
        self.btnReset = Plasma.PushButton(self.applet)
        self.btnReset.nativeWidget().setGuiItem(KStandardGuiItem.Reset)
        
        self.btnSave = Plasma.PushButton(self.applet)
        self.btnSave.nativeWidget().setGuiItem(KStandardGuiItem.Save)

        self.btnSaveAs = Plasma.PushButton(self.applet)
        self.btnSaveAs.nativeWidget().setGuiItem(KStandardGuiItem.SaveAs)


        self.layout.addItem(self.btnOpen,0,0)
        self.layout.addItem(self.btnReset,0,1)
        self.layout.addItem(self.btnSave,2,1)
        self.layout.addItem(self.btnSaveAs,2,0)
        
        self.model = None
        self.filePath = None
  
        self.treeView = Plasma.TreeView(self.applet)
        self.treeView.setVisible(False)
        
        header = self.treeView.nativeWidget().header()
        header.setDefaultAlignment(Qt.AlignCenter)
        
        fontColor = self.theme.theme().color(Plasma.Theme.TextColor)
        
        header.setStyleSheet("""
            QHeaderView {
                color: %s; 
                font: bold italic;
            };
            """ % fontColor.name() )
        self.treeView.setStyleSheet("""
            QTreeView { background-color: transparent; color: %s;}; 
            """ % fontColor.name() )
        
                                                                                 
        self.treeView.setModel(self.model)
        self.layout.addItem(self.treeView,1,0,1,2)

        self.setLayout(self.layout)
        self.resize(350,500)
        
        self.btnOpen.clicked.connect(self.openFile)
        self.btnReset.clicked.connect(self.resetFile)
        self.btnSave.clicked.connect(self.saveFile)
        self.btnSaveAs.clicked.connect(self.saveFileAs)
        
        # FIXME: doesn't work
        QObject.connect(self.treeView.nativeWidget(),
            SIGNAL("dataChanged(QModelIndex,QModelIndex)"),
            self.onDataChanged)
        
        self.treeView.nativeWidget().setItemDelegate(
                                            ProgressDelegate(
                                                self.treeView.nativeWidget()))
        self.treeView.nativeWidget().header().setResizeMode(
                                                        QHeaderView.Interactive)
        self.treeView.nativeWidget().setEditTriggers(QTreeView.AllEditTriggers)	
        
    def _open(self,filePath):
        if not filePath.isEmpty():
            self.model = TaskListModel(str(filePath))
            self.treeView.setModel(self.model)
            self.treeView.nativeWidget().expandAll()
            self.treeView.nativeWidget().header().resizeSection(0,
                                    self.treeView.nativeWidget().width() * 0.8)
            self.treeView.nativeWidget().header().resizeSection(1,
                                    self.treeView.nativeWidget().width() * 0.1)
            self.filePath = filePath
            self.treeView.setVisible(True)
        
        
    @pyqtSlot()
    def openFile(self,*args):
        fPath = QFileDialog.getOpenFileName(None,
            "Select TaskCoach file",
            expanduser("~"),
            "TaskCoach files (*.tsk);;All Files(*.*)")
        self._open(fPath)
        
    @pyqtSlot()        
    def resetFile(self,*args):
        if self.filePath is not None:
            self.model = TaskListModel(str(self.filePath))
            self.treeView.setModel(self.model)
            self.treeView.nativeWidget().expandAll()
            
    @pyqtSlot()        
    def saveFileAs(self,*args):
        savePath = QFileDialog.getSaveFileName ( None,
                "Save As",
                self.filePath,
                "TaskCoach files (*.tsk);;All Files(*.*)")
        if savePath.isEmpty(): return # user cancelled action
        tmpPath = QString(self.filePath)
        self.filePath = savePath
        done = self.saveFile()
        # if anything went wrong, go back to original
        if not done: self.filePath = tmpPath

    @pyqtSlot()
    def saveFile(self,*args):
        try:
            f = codecs.open(str(self.filePath),"w","utf-8")
            f.write(self.model.domDocument.toString())
            f.close()
            return True
        except Exception, e:
            QMessageBox.critical(None, "Failure while saving", e.msg)
            return False
        except Error, e:
            QMessageBox.critical(None, "Failure while saving", e.msg)
            return False
Exemple #19
0
class OWDistanceMap(widget.OWWidget):
    name = "Distance Map"

    description = "Visualize a distance matrix"
    icon = "icons/DistanceMatrix.svg"
    priority = 1200

    inputs = [("Distances", Orange.misc.DistMatrix, "set_distances")]
    outputs = [("Data", Orange.data.Table), ("Features", widget.AttributeList)]

    display_grid = settings.Setting(False)
    sorting = settings.Setting(0)

    colormap = settings.Setting(0)
    color_gamma = settings.Setting(0.0)
    color_low = settings.Setting(0.0)
    color_high = settings.Setting(1.0)

    annotation_idx = settings.Setting(0)

    autocommit = settings.Setting(True)

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

        self.matrix = None
        self._tree = None
        self._ordered_tree = None
        self._sorted_matrix = None
        self._sort_indices = None
        self._selection = None

        self._output_invalidated = False

        box = gui.widgetBox(self.controlArea, "Element sorting", margin=0)
        gui.comboBox(
            box,
            self,
            "sorting",
            items=["None", "Clustering", "Clustering with ordered leaves"],
            callback=self._invalidate_ordering)

        box = gui.widgetBox(self.controlArea, "Colors")

        self.colormap_cb = gui.comboBox(box,
                                        self,
                                        "colormap",
                                        callback=self._update_color)
        self.colormap_cb.setIconSize(QSize(64, 16))
        self.palettes = list(sorted(load_default_palettes()))
        init_color_combo(self.colormap_cb, self.palettes, QSize(64, 16))
        self.colormap_cb.setCurrentIndex(self.colormap)

        form = QFormLayout(formAlignment=Qt.AlignLeft,
                           labelAlignment=Qt.AlignLeft,
                           fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        #         form.addRow(
        #             "Gamma",
        #             gui.hSlider(box, self, "color_gamma", minValue=0.0, maxValue=1.0,
        #                         step=0.05, ticks=True, intOnly=False,
        #                         createLabel=False, callback=self._update_color)
        #         )
        form.addRow(
            "Low",
            gui.hSlider(box,
                        self,
                        "color_low",
                        minValue=0.0,
                        maxValue=1.0,
                        step=0.05,
                        ticks=True,
                        intOnly=False,
                        createLabel=False,
                        callback=self._update_color))
        form.addRow(
            "High",
            gui.hSlider(box,
                        self,
                        "color_high",
                        minValue=0.0,
                        maxValue=1.0,
                        step=0.05,
                        ticks=True,
                        intOnly=False,
                        createLabel=False,
                        callback=self._update_color))
        box.layout().addLayout(form)

        box = gui.widgetBox(self.controlArea, "Annotations")
        self.annot_combo = gui.comboBox(box,
                                        self,
                                        "annotation_idx",
                                        callback=self._invalidate_annotations)
        self.annot_combo.setModel(itemmodels.VariableListModel())
        self.annot_combo.model()[:] = ["None", "Enumeration"]
        self.controlArea.layout().addStretch()

        box = gui.widgetBox(self.controlArea, "Output")
        cb = gui.checkBox(box, self, "autocommit", "Commit on any change")
        b = gui.button(box, self, "Commit", callback=self.commit)
        gui.setStopper(self,
                       b,
                       cb,
                       "_output_invalidated",
                       callback=self.commit)

        self.view = pg.GraphicsView(background="w")
        self.mainArea.layout().addWidget(self.view)

        self.grid_widget = pg.GraphicsWidget()
        self.grid = QGraphicsGridLayout()
        self.grid_widget.setLayout(self.grid)

        self.viewbox = pg.ViewBox(enableMouse=False)
        self.viewbox.setAcceptedMouseButtons(Qt.NoButton)
        self.viewbox.setAcceptHoverEvents(False)
        self.grid.addItem(self.viewbox, 1, 1)

        self.left_dendrogram = DendrogramWidget(
            self.grid_widget, orientation=DendrogramWidget.Left)
        self.left_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.left_dendrogram.setAcceptHoverEvents(False)

        self.top_dendrogram = DendrogramWidget(
            self.grid_widget, orientation=DendrogramWidget.Top)
        self.top_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.top_dendrogram.setAcceptHoverEvents(False)

        self.grid.addItem(self.left_dendrogram, 1, 0)
        self.grid.addItem(self.top_dendrogram, 0, 1)

        self.right_labels = TextList(alignment=Qt.AlignLeft)

        self.bottom_labels = TextList(orientation=Qt.Horizontal,
                                      alignment=Qt.AlignRight)

        self.grid.addItem(self.right_labels, 1, 2)
        self.grid.addItem(self.bottom_labels, 2, 1)

        self.view.setCentralItem(self.grid_widget)

        self.left_dendrogram.hide()
        self.top_dendrogram.hide()
        self.right_labels.hide()
        self.bottom_labels.hide()

        self.matrix_item = None
        self.dendrogram = None

        self.grid_widget.scene().installEventFilter(self)

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

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

    def clear(self):
        self.matrix = None
        self.cluster = None
        self._tree = None
        self._ordered_tree = None
        self._sorted_matrix = None
        self._selection = []
        self._clear_plot()

    def handleNewSignals(self):
        if self.matrix is not None:
            self._update_ordering()
            self._setup_scene()
            self._update_labels()
        self.commit()

    def _clear_plot(self):
        def remove(item):
            item.setParentItem(None)
            item.scene().removeItem(item)

        if self.matrix_item:
            remove(self.matrix_item)
            self.matrix_item = None

        self.top_dendrogram.hide()
        self.left_dendrogram.hide()

        self._set_labels(None)

    def _cluster_tree(self):
        if self._tree is None:
            self._tree = hierarchical.dist_matrix_clustering(self.matrix)
        return self._tree

    def _ordered_cluster_tree(self):
        if self._ordered_tree is None:
            tree = self._cluster_tree()
            self._ordered_tree = \
                hierarchical.optimal_leaf_ordering(tree, self.matrix)
        return self._ordered_tree

    def _setup_scene(self):
        self.matrix_item = DistanceMapItem(self._sorted_matrix[:, ::-1])

        self.viewbox.addItem(self.matrix_item)
        self.viewbox.setRange(QRectF(0, 0, *self._sorted_matrix.shape),
                              padding=0)

        self.matrix_item.selectionChanged.connect(self._invalidate_selection)

        if self.sorting == 0:
            tree = None
        elif self.sorting == 1:
            tree = self._cluster_tree()
        else:
            tree = self._ordered_cluster_tree()

        self._set_displayed_dendrogram(tree)

        self._update_color()

    def _set_displayed_dendrogram(self, root):
        self.left_dendrogram.set_root(root)
        self.top_dendrogram.set_root(root)
        self.left_dendrogram.setVisible(root is not None)
        self.top_dendrogram.setVisible(root is not None)

        constraint = 0 if root is None else -1  # 150
        self.left_dendrogram.setMaximumWidth(constraint)
        self.top_dendrogram.setMaximumHeight(constraint)

    def _invalidate_ordering(self):
        self._sorted_matrix = None
        if self.matrix is not None:
            self._update_ordering()
            self._setup_scene()

    def _update_ordering(self):
        if self.sorting == 0:
            self._sorted_matrix = self.matrix.X
            self._sort_indices = None
        else:
            if self.sorting == 1:
                tree = self._cluster_tree()
            elif self.sorting == 2:
                tree = self._ordered_cluster_tree()

            leaves = hierarchical.leaves(tree)
            indices = numpy.array([leaf.value.index for leaf in leaves])
            X = self.matrix.X
            self._sorted_matrix = X[indices[:, numpy.newaxis],
                                    indices[numpy.newaxis, :]]
            self._sort_indices = indices

    def _invalidate_annotations(self):
        if self.matrix is not None:
            self._update_labels()

    def _update_labels(self, ):
        if self.annotation_idx == 0:
            labels = None
        elif self.annotation_idx == 1:
            labels = [str(i + 1) for i in range(self.matrix.dim[0])]
        elif self.annotation_idx == 2 and \
                isinstance(self.items, widget.AttributeList):
            labels = [v.name for v in self.items]
        elif isinstance(self.items, Orange.data.Table):
            var = self.annot_combo.model()[self.annotation_idx]
            column, _ = self.items.get_column_view(var)
            labels = [var.repr_val(value) for value in column]

        self._set_labels(labels)

    def _set_labels(self, labels):
        self._labels = labels

        if labels and self.sorting:
            sortind = self._sort_indices
            labels = [labels[i] for i in sortind]

        for textlist in [self.right_labels, self.bottom_labels]:
            textlist.set_labels(labels or [])
            textlist.setVisible(bool(labels))

        constraint = -1 if labels else 0
        self.right_labels.setMaximumWidth(constraint)
        self.bottom_labels.setMaximumHeight(constraint)

    def _update_color(self):
        if self.matrix_item:
            name, colors = self.palettes[self.colormap]
            n, colors = max(colors.items())
            colors = numpy.array(colors, dtype=numpy.ubyte)
            low, high = self.color_low * 255, self.color_high * 255
            points = numpy.linspace(low, high, n)
            space = numpy.linspace(0, 255, 255)

            r = numpy.interp(space, points, colors[:, 0], left=255, right=0)
            g = numpy.interp(space, points, colors[:, 1], left=255, right=0)
            b = numpy.interp(space, points, colors[:, 2], left=255, right=0)
            colortable = numpy.c_[r, g, b]
            self.matrix_item.setLookupTable(colortable)

    def _invalidate_selection(self):
        ranges = self.matrix_item.selections()
        ranges = reduce(iadd, ranges, [])
        indices = reduce(iadd, ranges, [])

        if self.sorting:
            sortind = self._sort_indices
            indices = [sortind[i] for i in indices]

        self._selection = list(sorted(set(indices)))

        if self.autocommit:
            self.commit()
        else:
            self._output_invalidated = True

    def commit(self):
        datasubset = None
        featuresubset = None

        if not self._selection:
            pass
        elif isinstance(self.items, Orange.data.Table):
            indices = self._selection
            datasubset = self.items.from_table_rows(self.items, indices)
        elif isinstance(self.items, widget.AttributeList):
            subset = [self.items[i] for i in self._selection]
            featuresubset = widget.AttributeList(subset)

        self.send("Data", datasubset)
        self.send("Features", featuresubset)
        self._output_invalidated = False
Exemple #20
0
class GSBApplet(plasmascript.Applet):
    def __init__(self,parent,args=None):
        plasmascript.Applet.__init__(self,parent)


    def init(self):

        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)

        self.settings = self.config()

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

        self.layout = QGraphicsGridLayout(self.applet)
        self.layout.setColumnSpacing(0,5.0)

        self.lblTitle = Plasma.Label(self.applet)
        self.lblTitle.nativeWidget().setText(
                                        ki18n("Stuff to get back").toString())
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setStyleSheet("""QLabel {
                                                text-align:center;
                                                font-style: italic;
                                                font-weight: bold;}""")
        self.layout.addItem(self.lblTitle,0,0,1,3)

        self.btnAdd = Plasma.PushButton(self.applet)
        self.btnAdd.nativeWidget().setGuiItem(KStandardGuiItem.Add)
        self.layout.addItem(self.btnAdd,1,0)

        self.btnRemove = Plasma.PushButton(self.applet)
        self.btnRemove.nativeWidget().setGuiItem(KStandardGuiItem.Remove)
        self.layout.addItem(self.btnRemove,1,2)

        self.db = GSBDbModel()

        self.view = Plasma.TreeView(self.applet)
        self.view.setModel(self.db)
        self.view.nativeWidget().setColumnHidden(self.db.IDCOL,True)
        self.view.nativeWidget().setRootIsDecorated(False)
        self.view.nativeWidget().setExpandsOnDoubleClick(False)
        self.view.nativeWidget().setItemsExpandable(False)
        self.view.setStyleSheet("""
            QTreeView {
                background-color: transparent;
                }
                QTreeView::item { padding-top:10px; padding-bottom: 10px; }
            """)
        self.view.nativeWidget().header().resizeSections(
                                                QHeaderView.ResizeToContents)
        self.view.nativeWidget().setItemDelegate(
                                            LoanDelegate(
                                                    self.applet,
                                                    self.view.nativeWidget()))


        self.layout.addItem(self.view,2,0,1,3)

        self.setLayout(self.layout)

        self.btnAdd.clicked.connect(self.add_loan)
        self.btnRemove.clicked.connect(self.remove_loan)

    def createConfigurationInterface(self, parent):
        self.configDlg = ConfigDlg(parent, self.applet)
        page = parent.addPage(self.configDlg,
                                ki18n("GetStuffBack Options").toString())
        page.setIcon(KIcon("user-desktop"))

        parent.okClicked.connect(self.configAccepted)

    def showConfigurationInterface(self):
        dialog = KPageDialog()
        dialog.setFaceType(KPageDialog.List)
        dialog.setButtons( KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel) )
        self.createConfigurationInterface(dialog)
        dialog.exec_()

    @pyqtSlot()
    def configAccepted(self):
        grace_period = self.configDlg.spinGrace.value()
        colour = self.configDlg.btnColour.color()

        options = self.settings.group("general")
        options.writeEntry("grace",grace_period)
        options.writeEntry("overdue_colour",colour.name())

    @pyqtSlot()
    def add_loan(self,*args):
        addDlg = AddDlg(self)
        result = addDlg.exec_()
        if result == False: return False
        ln = Loan()
        ln.item_description = unicode(addDlg.lineItemDescription.toPlainText())
        ln.person = unicode(addDlg.linePerson.text())
        ln.date = addDlg.dteDate.dateTime().toPyDateTime()
        ln.expected_date = addDlg.dteExpectedDate.dateTime().toPyDateTime()
        ln.item_type = unicode(addDlg.comboItemType.currentText())
        self.db.add_loan(ln)
        self.db.dataChanged.emit(QModelIndex(),QModelIndex())
        self.db.reset()

    @pyqtSlot()
    def remove_loan(self,*args):
        deleteList = self.view.nativeWidget().selectionModel().selectedIndexes()
        rows = set()
        for index in deleteList:
            row = index.row()
            if row not in rows:
                rows.add(row)
                self.db.removeRow(row)
Exemple #21
0
    def init(self):
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        
        self.settings = self.config()

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

        self.layout = QGraphicsGridLayout(self.applet)
        self.layout.setColumnSpacing(0,5.0)
        
        # using the predefined KGuiItem objects save us a lot of work
        self.btnOpen = Plasma.PushButton(self.applet)
        self.btnOpen.nativeWidget().setGuiItem(KStandardGuiItem.Open)
        
        self.btnReset = Plasma.PushButton(self.applet)
        self.btnReset.nativeWidget().setGuiItem(KStandardGuiItem.Reset)
        
        self.btnSave = Plasma.PushButton(self.applet)
        self.btnSave.nativeWidget().setGuiItem(KStandardGuiItem.Save)

        self.btnSaveAs = Plasma.PushButton(self.applet)
        self.btnSaveAs.nativeWidget().setGuiItem(KStandardGuiItem.SaveAs)


        self.layout.addItem(self.btnOpen,0,0)
        self.layout.addItem(self.btnReset,0,1)
        self.layout.addItem(self.btnSave,2,1)
        self.layout.addItem(self.btnSaveAs,2,0)
        
        self.model = None
        self.filePath = None
  
        self.treeView = Plasma.TreeView(self.applet)
        self.treeView.setVisible(False)
        
        header = self.treeView.nativeWidget().header()
        header.setDefaultAlignment(Qt.AlignCenter)
        
        fontColor = self.theme.theme().color(Plasma.Theme.TextColor)
        
        header.setStyleSheet("""
            QHeaderView {
                color: %s; 
                font: bold italic;
            };
            """ % fontColor.name() )
        self.treeView.setStyleSheet("""
            QTreeView { background-color: transparent; color: %s;}; 
            """ % fontColor.name() )
        
                                                                                 
        self.treeView.setModel(self.model)
        self.layout.addItem(self.treeView,1,0,1,2)

        self.setLayout(self.layout)
        self.resize(350,500)
        
        self.btnOpen.clicked.connect(self.openFile)
        self.btnReset.clicked.connect(self.resetFile)
        self.btnSave.clicked.connect(self.saveFile)
        self.btnSaveAs.clicked.connect(self.saveFileAs)
        
        # FIXME: doesn't work
        QObject.connect(self.treeView.nativeWidget(),
            SIGNAL("dataChanged(QModelIndex,QModelIndex)"),
            self.onDataChanged)
        
        self.treeView.nativeWidget().setItemDelegate(
                                            ProgressDelegate(
                                                self.treeView.nativeWidget()))
        self.treeView.nativeWidget().header().setResizeMode(
                                                        QHeaderView.Interactive)
        self.treeView.nativeWidget().setEditTriggers(QTreeView.AllEditTriggers)	
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
Exemple #23
0
    def __init__(self):
        super().__init__()

        self.matrix = None
        self._tree = None
        self._ordered_tree = None
        self._sorted_matrix = None
        self._sort_indices = None
        self._selection = None

        box = gui.widgetBox(self.controlArea, "Element sorting", margin=0)
        self.sorting_cb = gui.comboBox(
            box, self, "sorting",
            items=["None", "Clustering", "Clustering with ordered leaves"],
            callback=self._invalidate_ordering)

        box = gui.widgetBox(self.controlArea, "Colors")

        self.colormap_cb = gui.comboBox(
            box, self, "colormap", callback=self._update_color
        )
        self.colormap_cb.setIconSize(QSize(64, 16))
        self.palettes = list(_color_palettes)

        init_color_combo(self.colormap_cb, self.palettes, QSize(64, 16))
        self.colormap_cb.setCurrentIndex(self.colormap)

        form = QFormLayout(
            formAlignment=Qt.AlignLeft,
            labelAlignment=Qt.AlignLeft,
            fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow
        )
#         form.addRow(
#             "Gamma",
#             gui.hSlider(box, self, "color_gamma", minValue=0.0, maxValue=1.0,
#                         step=0.05, ticks=True, intOnly=False,
#                         createLabel=False, callback=self._update_color)
#         )
        form.addRow(
            "Low",
            gui.hSlider(box, self, "color_low", minValue=0.0, maxValue=1.0,
                        step=0.05, ticks=True, intOnly=False,
                        createLabel=False, callback=self._update_color)
        )
        form.addRow(
            "High",
            gui.hSlider(box, self, "color_high", minValue=0.0, maxValue=1.0,
                        step=0.05, ticks=True, intOnly=False,
                        createLabel=False, callback=self._update_color)
        )
        box.layout().addLayout(form)

        box = gui.widgetBox(self.controlArea, "Annotations")
        self.annot_combo = gui.comboBox(box, self, "annotation_idx",
                                        callback=self._invalidate_annotations,
                                        contentsLength=12)
        self.annot_combo.setModel(itemmodels.VariableListModel())
        self.annot_combo.model()[:] = ["None", "Enumeration"]
        self.controlArea.layout().addStretch()

        gui.auto_commit(self.controlArea, self, "autocommit",
                        "Send data", "Auto send is on")
        self.inline_graph_report()

        self.view = pg.GraphicsView(background="w")
        self.mainArea.layout().addWidget(self.view)

        self.grid_widget = pg.GraphicsWidget()
        self.grid = QGraphicsGridLayout()
        self.grid_widget.setLayout(self.grid)

        self.viewbox = pg.ViewBox(enableMouse=False, enableMenu=False)
        self.viewbox.setAcceptedMouseButtons(Qt.NoButton)
        self.viewbox.setAcceptHoverEvents(False)
        self.grid.addItem(self.viewbox, 1, 1)

        self.left_dendrogram = DendrogramWidget(
            self.grid_widget, orientation=DendrogramWidget.Left,
            selectionMode=DendrogramWidget.NoSelection,
            hoverHighlightEnabled=False
        )
        self.left_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.left_dendrogram.setAcceptHoverEvents(False)

        self.top_dendrogram = DendrogramWidget(
            self.grid_widget, orientation=DendrogramWidget.Top,
            selectionMode=DendrogramWidget.NoSelection,
            hoverHighlightEnabled=False
        )
        self.top_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.top_dendrogram.setAcceptHoverEvents(False)

        self.grid.addItem(self.left_dendrogram, 1, 0)
        self.grid.addItem(self.top_dendrogram, 0, 1)

        self.right_labels = TextList(
            alignment=Qt.AlignLeft)

        self.bottom_labels = TextList(
            orientation=Qt.Horizontal, alignment=Qt.AlignRight)

        self.grid.addItem(self.right_labels, 1, 2)
        self.grid.addItem(self.bottom_labels, 2, 1)

        self.view.setCentralItem(self.grid_widget)

        self.left_dendrogram.hide()
        self.top_dendrogram.hide()
        self.right_labels.hide()
        self.bottom_labels.hide()

        self.matrix_item = None
        self.dendrogram = None

        self.grid_widget.scene().installEventFilter(self)
        self.graphButton.clicked.connect(self.save_graph)
Exemple #24
0
class OWDistanceMap(widget.OWWidget):
    name = "Distance Map"

    description = "Visualize a distance matrix"
    icon = "icons/DistanceMatrix.svg"
    priority = 1200

    inputs = [("Distances", Orange.misc.DistMatrix, "set_distances")]
    outputs = [("Data", Orange.data.Table), ("Features", widget.AttributeList)]

    display_grid = settings.Setting(False)
    sorting = settings.Setting(0)

    colormap = settings.Setting(0)
    color_gamma = settings.Setting(0.0)
    color_low = settings.Setting(0.0)
    color_high = settings.Setting(1.0)

    annotation_idx = settings.Setting(0)

    autocommit = settings.Setting(True)

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

        self.matrix = None
        self._tree = None
        self._ordered_tree = None
        self._sorted_matrix = None
        self._sort_indices = None
        self._selection = None

        box = gui.widgetBox(self.controlArea, "Element sorting", margin=0)
        gui.comboBox(box, self, "sorting",
                     items=["None", "Clustering",
                            "Clustering with ordered leaves"
                            ],
                     callback=self._invalidate_ordering)

        box = gui.widgetBox(self.controlArea, "Colors")

        self.colormap_cb = gui.comboBox(
            box, self, "colormap", callback=self._update_color
        )
        self.colormap_cb.setIconSize(QSize(64, 16))
        self.palettes = list(sorted(load_default_palettes()))
        init_color_combo(self.colormap_cb, self.palettes, QSize(64, 16))
        self.colormap_cb.setCurrentIndex(self.colormap)

        form = QFormLayout(
            formAlignment=Qt.AlignLeft,
            labelAlignment=Qt.AlignLeft,
            fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow
        )
#         form.addRow(
#             "Gamma",
#             gui.hSlider(box, self, "color_gamma", minValue=0.0, maxValue=1.0,
#                         step=0.05, ticks=True, intOnly=False,
#                         createLabel=False, callback=self._update_color)
#         )
        form.addRow(
            "Low",
            gui.hSlider(box, self, "color_low", minValue=0.0, maxValue=1.0,
                        step=0.05, ticks=True, intOnly=False,
                        createLabel=False, callback=self._update_color)
        )
        form.addRow(
            "High",
            gui.hSlider(box, self, "color_high", minValue=0.0, maxValue=1.0,
                        step=0.05, ticks=True, intOnly=False,
                        createLabel=False, callback=self._update_color)
        )
        box.layout().addLayout(form)

        box = gui.widgetBox(self.controlArea, "Annotations")
        self.annot_combo = gui.comboBox(box, self, "annotation_idx",
                                        callback=self._invalidate_annotations)
        self.annot_combo.setModel(itemmodels.VariableListModel())
        self.annot_combo.model()[:] = ["None", "Enumeration"]
        self.controlArea.layout().addStretch()

        gui.auto_commit(self.controlArea, self, "autocommit",
                        "Send data", "Auto send is on")

        self.view = pg.GraphicsView(background="w")
        self.mainArea.layout().addWidget(self.view)

        self.grid_widget = pg.GraphicsWidget()
        self.grid = QGraphicsGridLayout()
        self.grid_widget.setLayout(self.grid)

        self.viewbox = pg.ViewBox(enableMouse=False)
        self.viewbox.setAcceptedMouseButtons(Qt.NoButton)
        self.viewbox.setAcceptHoverEvents(False)
        self.grid.addItem(self.viewbox, 1, 1)

        self.left_dendrogram = DendrogramWidget(
            self.grid_widget, orientation=DendrogramWidget.Left)
        self.left_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.left_dendrogram.setAcceptHoverEvents(False)

        self.top_dendrogram = DendrogramWidget(
            self.grid_widget, orientation=DendrogramWidget.Top)
        self.top_dendrogram.setAcceptedMouseButtons(Qt.NoButton)
        self.top_dendrogram.setAcceptHoverEvents(False)

        self.grid.addItem(self.left_dendrogram, 1, 0)
        self.grid.addItem(self.top_dendrogram, 0, 1)

        self.right_labels = TextList(
            alignment=Qt.AlignLeft)

        self.bottom_labels = TextList(
            orientation=Qt.Horizontal, alignment=Qt.AlignRight)

        self.grid.addItem(self.right_labels, 1, 2)
        self.grid.addItem(self.bottom_labels, 2, 1)

        self.view.setCentralItem(self.grid_widget)

        self.left_dendrogram.hide()
        self.top_dendrogram.hide()
        self.right_labels.hide()
        self.bottom_labels.hide()

        self.matrix_item = None
        self.dendrogram = None

        self.grid_widget.scene().installEventFilter(self)

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

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

    def clear(self):
        self.matrix = None
        self.cluster = None
        self._tree = None
        self._ordered_tree = None
        self._sorted_matrix = None
        self._selection = []
        self._clear_plot()

    def handleNewSignals(self):
        if self.matrix is not None:
            self._update_ordering()
            self._setup_scene()
            self._update_labels()
        self.unconditional_commit()

    def _clear_plot(self):
        def remove(item):
            item.setParentItem(None)
            item.scene().removeItem(item)

        if self.matrix_item:
            remove(self.matrix_item)
            self.matrix_item = None

        self.top_dendrogram.hide()
        self.left_dendrogram.hide()

        self._set_labels(None)

    def _cluster_tree(self):
        if self._tree is None:
            self._tree = hierarchical.dist_matrix_clustering(self.matrix)
        return self._tree

    def _ordered_cluster_tree(self):
        if self._ordered_tree is None:
            tree = self._cluster_tree()
            self._ordered_tree = \
                hierarchical.optimal_leaf_ordering(tree, self.matrix)
        return self._ordered_tree

    def _setup_scene(self):
        self.matrix_item = DistanceMapItem(self._sorted_matrix[:, ::-1])

        self.viewbox.addItem(self.matrix_item)
        self.viewbox.setRange(QRectF(0, 0, *self._sorted_matrix.shape),
                              padding=0)

        self.matrix_item.selectionChanged.connect(self._invalidate_selection)

        if self.sorting == 0:
            tree = None
        elif self.sorting == 1:
            tree = self._cluster_tree()
        else:
            tree = self._ordered_cluster_tree()

        self._set_displayed_dendrogram(tree)

        self._update_color()

    def _set_displayed_dendrogram(self, root):
        self.left_dendrogram.set_root(root)
        self.top_dendrogram.set_root(root)
        self.left_dendrogram.setVisible(root is not None)
        self.top_dendrogram.setVisible(root is not None)

        constraint = 0 if root is None else -1  # 150
        self.left_dendrogram.setMaximumWidth(constraint)
        self.top_dendrogram.setMaximumHeight(constraint)

    def _invalidate_ordering(self):
        self._sorted_matrix = None
        if self.matrix is not None:
            self._update_ordering()
            self._setup_scene()

    def _update_ordering(self):
        if self.sorting == 0:
            self._sorted_matrix = self.matrix.X
            self._sort_indices = None
        else:
            if self.sorting == 1:
                tree = self._cluster_tree()
            elif self.sorting == 2:
                tree = self._ordered_cluster_tree()

            leaves = hierarchical.leaves(tree)
            indices = numpy.array([leaf.value.index for leaf in leaves])
            X = self.matrix.X
            self._sorted_matrix = X[indices[:, numpy.newaxis],
                                    indices[numpy.newaxis, :]]
            self._sort_indices = indices

    def _invalidate_annotations(self):
        if self.matrix is not None:
            self._update_labels()

    def _update_labels(self, ):
        if self.annotation_idx == 0:
            labels = None
        elif self.annotation_idx == 1:
            labels = [str(i + 1) for i in range(self.matrix.dim[0])]
        elif self.annotation_idx == 2 and \
                isinstance(self.items, widget.AttributeList):
            labels = [v.name for v in self.items]
        elif isinstance(self.items, Orange.data.Table):
            var = self.annot_combo.model()[self.annotation_idx]
            column, _ = self.items.get_column_view(var)
            labels = [var.repr_val(value) for value in column]

        self._set_labels(labels)

    def _set_labels(self, labels):
        self._labels = labels

        if labels and self.sorting:
            sortind = self._sort_indices
            labels = [labels[i] for i in sortind]

        for textlist in [self.right_labels, self.bottom_labels]:
            textlist.set_labels(labels or [])
            textlist.setVisible(bool(labels))

        constraint = -1 if labels else 0
        self.right_labels.setMaximumWidth(constraint)
        self.bottom_labels.setMaximumHeight(constraint)

    def _update_color(self):
        if self.matrix_item:
            name, colors = self.palettes[self.colormap]
            n, colors = max(colors.items())
            colors = numpy.array(colors, dtype=numpy.ubyte)
            low, high = self.color_low * 255, self.color_high * 255
            points = numpy.linspace(low, high, n)
            space = numpy.linspace(0, 255, 255)

            r = numpy.interp(space, points, colors[:, 0], left=255, right=0)
            g = numpy.interp(space, points, colors[:, 1], left=255, right=0)
            b = numpy.interp(space, points, colors[:, 2], left=255, right=0)
            colortable = numpy.c_[r, g, b]
            self.matrix_item.setLookupTable(colortable)

    def _invalidate_selection(self):
        ranges = self.matrix_item.selections()
        ranges = reduce(iadd, ranges, [])
        indices = reduce(iadd, ranges, [])
        if self.sorting:
            sortind = self._sort_indices
            indices = [sortind[i] for i in indices]
        self._selection = list(sorted(set(indices)))
        self.commit()

    def commit(self):
        datasubset = None
        featuresubset = None

        if not self._selection:
            pass
        elif isinstance(self.items, Orange.data.Table):
            indices = self._selection
            datasubset = self.items.from_table_rows(self.items, indices)
        elif isinstance(self.items, widget.AttributeList):
            subset = [self.items[i] for i in self._selection]
            featuresubset = widget.AttributeList(subset)

        self.send("Data", datasubset)
        self.send("Features", featuresubset)
Exemple #25
0
    def init(self):
        """init method for the plasmoid. GUI stuff is located here."""

        self.moduller = self.link.Network.Firewall[dbus.String(
            "iptables")].listModules()

        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.Square)
        self.resize(450, 250)

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

        label = Plasma.Label(self.applet)
        label.setText("<h1>Firewall Plasmoid</h1>")
        self.kilit = Plasma.IconWidget(self.applet)
        self.bilgi_label = Plasma.Label(self.applet)

        self.baslat_pb = Plasma.PushButton(self.applet)
        self.baslat_pb.setText("Start")
        self.durdur_pb = Plasma.PushButton(self.applet)
        self.durdur_pb.setText("Stop")
        print "osman"
        if self.link.Network.Firewall[dbus.String(
                "iptables")].getState() == dbus.String(u"on"):
            self.bilgi_label.setText(
                "<p style='color:green'>Firewall is working now.</p>")
            self.kilit.setIcon("object-locked")
            self.kilit.setMaximumSize(32, 32)
            self.kilit.setMinimumSize(32, 32)
            self.baslat_pb.setEnabled(False)

        else:
            self.bilgi_label.setText(
                "<p style='color:red'>Firewall is stopped now.</p>")
            self.kilit.setMaximumSize(32, 32)
            self.kilit.setMinimumSize(32, 32)
            self.kilit.setIcon("object-unlocked")
            self.durdur_pb.setEnabled(False)

        self.bilgilendirme_baslik = Plasma.Label(self.applet)
        self.bilgilendirme_baslik.setText("Latest news:")

        self.bilgilendirme = Plasma.Label(self.applet)
        self.bilgilendirme.setText("Firewall Plasmoid has been started.")

        gelen_simge = Plasma.IconWidget(self.applet)
        gelen_simge.setIcon("application-x-smb-workgroup")
        paylasim_simge = Plasma.IconWidget(self.applet)
        paylasim_simge.setIcon("application-x-smb-server")
        giden_simge = Plasma.IconWidget(self.applet)
        giden_simge.setIcon("security-medium")

        self.kutular = []
        sayi = 0
        for i in self.moduller:
            self.kutular.append(Plasma.CheckBox(self.applet))
            self.kutular[sayi].setText(self.link.Network.Firewall[dbus.String(
                "iptables")].moduleInfo(i)[0])
            sayi += 1

        self.layout.addItem(label, 0, 0, 1, 4)
        self.layout.addItem(self.kilit, 1, 0)
        self.layout.addItem(self.bilgi_label, 1, 1)
        self.layout.addItem(self.baslat_pb, 1, 2)
        self.layout.addItem(self.durdur_pb, 1, 3)
        self.layout.addItem(gelen_simge, 2, 0, 1, 1)
        self.layout.addItem(paylasim_simge, 3, 0, 1, 1)
        self.layout.addItem(giden_simge, 4, 0, 1, 1)
        self.layout.addItem(self.bilgilendirme_baslik, 5, 0, 1, 1)
        self.layout.addItem(self.bilgilendirme, 5, 1, 1, 4)
        m = 0
        for i in range(0, len(self.moduller)):
            self.layout.addItem(self.kutular[m], m + 2, 1, 1, 4)
            m += 1
        self.applet.setLayout(self.layout)

        QObject.connect(self.baslat_pb, SIGNAL("clicked()"), self.baslat)
        QObject.connect(self.durdur_pb, SIGNAL("clicked()"), self.durdur)

        fonksiyonlar = [self.blockGelen, self.paylasim, self.blockGiden]
        for i in range(0, len(self.moduller)):
            QObject.connect(self.kutular[i], SIGNAL("toggled(bool)"),
                            fonksiyonlar[i])

        self.bilgilendirme_iletileri = [
            "Incoming connections was blocked successfully.",
            "Sharing internet is successful.",
            "Outgoing connections was blocked successfully."
        ]

        self.link.listenSignals("Network.Firewall", self.handler)
Exemple #26
0
class GraphicsThumbnailGrid(QGraphicsWidget):

    class LayoutMode(enum.Enum):
        FixedColumnCount, AutoReflow = 0, 1
    FixedColumnCount, AutoReflow = LayoutMode

    #: Signal emitted when the current (thumbnail) changes
    currentThumbnailChanged = Signal(object)

    def __init__(self, parent=None, **kwargs):
        super().__init__(parent, **kwargs)
        self.__layoutMode = GraphicsThumbnailGrid.AutoReflow
        self.__columnCount = -1
        self.__thumbnails = []  # type: List[GraphicsThumbnailWidget]
        #: The current 'focused' thumbnail item. This is the item that last
        #: received the keyboard focus (though it does not necessarily have
        #: it now)
        self.__current = None  # type: Optional[GraphicsThumbnailWidget]
        self.__reflowPending = False

        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.setContentsMargins(10, 10, 10, 10)
        # NOTE: Keeping a reference to the layout. self.layout()
        # returns a QGraphicsLayout wrapper (i.e. strips the
        # QGraphicsGridLayout-nes of the object).
        self.__layout = QGraphicsGridLayout()
        self.__layout.setContentsMargins(0, 0, 0, 0)
        self.__layout.setSpacing(10)
        self.setLayout(self.__layout)

    def resizeEvent(self, event):
        super().resizeEvent(event)

        if event.newSize().width() != event.oldSize().width() and \
                self.__layoutMode == GraphicsThumbnailGrid.AutoReflow:
            self.__reflow()

    def setGeometry(self, rect):
        self.prepareGeometryChange()
        super().setGeometry(rect)

    def count(self):
        """
        Returns
        -------
        count: int
            Number of thumbnails in the widget
        """
        return len(self.__thumbnails)

    def addThumbnail(self, thumbnail):
        """
        Add/append a thumbnail to the widget

        Parameters
        ----------
        thumbnail: Union[GraphicsThumbnailWidget, QPixmap]
            The thumbnail to insert
        """
        self.insertThumbnail(self.count(), thumbnail)

    def insertThumbnail(self, index, thumbnail):
        """
        Insert a new thumbnail into a widget.

        Raise a ValueError if thumbnail is already in the view.

        Parameters
        ----------
        index : int
            Index where to insert
        thumbnail : Union[GraphicsThumbnailWidget, QPixmap]
            The thumbnail to insert. GraphicsThumbnailGrid takes ownership
            of the item.
        """
        if isinstance(thumbnail, QPixmap):
            thumbnail = GraphicsThumbnailWidget(thumbnail, parentItem=self)
        elif thumbnail in self.__thumbnails:
            raise ValueError("{!r} is already inserted".format(thumbnail))
        elif not isinstance(thumbnail, GraphicsThumbnailWidget):
            raise TypeError

        index = max(min(index, self.count()), 0)

        moved = self.__takeItemsFrom(index)
        assert moved == self.__thumbnails[index:]
        self.__thumbnails.insert(index, thumbnail)
        self.__appendItems([thumbnail] + moved)
        thumbnail.setParentItem(self)
        thumbnail.installEventFilter(self)
        assert self.count() == self.layout().count()

        self.__scheduleLayout()

    def removeThumbnail(self, thumbnail):
        """
        Remove a single thumbnail from the grid.

        Raise a ValueError if thumbnail is not in the grid.

        Parameters
        ----------
        thumbnail : GraphicsThumbnailWidget
            Thumbnail to remove. Items ownership is transferred to the caller.
        """
        index = self.__thumbnails.index(thumbnail)
        moved = self.__takeItemsFrom(index)

        del self.__thumbnails[index]
        assert moved[0] is thumbnail and self.__thumbnails[index:] == moved[1:]
        self.__appendItems(moved[1:])

        thumbnail.removeEventFilter(self)
        if thumbnail.parentItem() is self:
            thumbnail.setParentItem(None)

        if self.__current is thumbnail:
            self.__current = None
            self.currentThumbnailChanged.emit(None)

        assert self.count() == self.layout().count()

    def thumbnailAt(self, index):
        """
        Return the thumbnail widget at `index`

        Parameters
        ----------
        index : int

        Returns
        -------
        thumbnail : GraphicsThumbnailWidget

        """
        return self.__thumbnails[index]

    def clear(self):
        """
        Remove all thumbnails from the grid.
        """
        removed = self.__takeItemsFrom(0)
        assert removed == self.__thumbnails
        self.__thumbnails = []
        for thumb in removed:
            thumb.removeEventFilter(self)
            if thumb.parentItem() is self:
                thumb.setParentItem(None)
        if self.__current is not None:
            self.__current = None
            self.currentThumbnailChanged.emit(None)

    def __takeItemsFrom(self, fromindex):
        # remove all items starting at fromindex from the layout and
        # return them
        # NOTE: Operate on layout only
        layout = self.__layout
        taken = []
        for i in reversed(range(fromindex, layout.count())):
            item = layout.itemAt(i)
            layout.removeAt(i)
            taken.append(item)
        return list(reversed(taken))

    def __appendItems(self, items):
        # Append/insert items into the layout at the end
        # NOTE: Operate on layout only
        layout = self.__layout
        columns = max(layout.columnCount(), 1)
        for i, item in enumerate(items, layout.count()):
            layout.addItem(item, i // columns, i % columns)

    def __scheduleLayout(self):
        if not self.__reflowPending:
            self.__reflowPending = True
            QApplication.postEvent(self, QEvent(QEvent.LayoutRequest),
                                   Qt.HighEventPriority)

    def event(self, event):
        if event.type() == QEvent.LayoutRequest:
            if self.__layoutMode == GraphicsThumbnailGrid.AutoReflow:
                self.__reflow()
            else:
                self.__gridlayout()

            if self.parentLayoutItem() is None:
                sh = self.effectiveSizeHint(Qt.PreferredSize)
                self.resize(sh)

            if self.layout():
                self.layout().activate()

        return super().event(event)

    def setFixedColumnCount(self, count):
        if count < 0:
            if self.__layoutMode != GraphicsThumbnailGrid.AutoReflow:
                self.__layoutMode = GraphicsThumbnailGrid.AutoReflow
                self.__reflow()
        else:
            if self.__layoutMode != GraphicsThumbnailGrid.FixedColumnCount:
                self.__layoutMode = GraphicsThumbnailGrid.FixedColumnCount

            if self.__columnCount != count:
                self.__columnCount = count
                self.__gridlayout()

    def __reflow(self):
        self.__reflowPending = False
        layout = self.__layout
        width = self.contentsRect().width()
        hints = [item.effectiveSizeHint(Qt.PreferredSize)
                 for item in self.__thumbnails]

        widths = [max(24, h.width()) for h in hints]
        ncol = self._fitncols(widths, layout.horizontalSpacing(), width)

        self.__relayoutGrid(ncol)

    def __gridlayout(self):
        assert self.__layoutMode == GraphicsThumbnailGrid.FixedColumnCount
        self.__relayoutGrid(self.__columnCount)

    def __relayoutGrid(self, columnCount):
        layout = self.__layout
        if columnCount == layout.columnCount():
            return

        # remove all items from the layout, then re-add them back in
        # updated positions
        items = self.__takeItemsFrom(0)
        for i, item in enumerate(items):
            layout.addItem(item, i // columnCount, i % columnCount)

    def items(self):
        """
        Return all thumbnail items.

        Returns
        -------
        thumbnails : List[GraphicsThumbnailWidget]
        """
        return list(self.__thumbnails)

    def currentItem(self):
        """
        Return the current (last focused) thumbnail item.
        """
        return self.__current

    def _fitncols(self, widths, spacing, constraint):
        def sliced(seq, ncol):
            return [seq[i:i + ncol] for i in range(0, len(seq), ncol)]

        def flow_width(widths, spacing, ncol):
            W = sliced(widths, ncol)
            col_widths = map(max, zip_longest(*W, fillvalue=0))
            return sum(col_widths) + (ncol - 1) * spacing

        ncol_best = 1
        for ncol in range(2, len(widths) + 1):
            w = flow_width(widths, spacing, ncol)
            if w <= constraint:
                ncol_best = ncol
            else:
                break

        return ncol_best

    def keyPressEvent(self, event):
        if event.key() in [Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down]:
            self._moveCurrent(event.key(), event.modifiers())
            event.accept()
            return
        super().keyPressEvent(event)

    def eventFilter(self, receiver, event):
        if isinstance(receiver, GraphicsThumbnailWidget) and \
                event.type() == QEvent.FocusIn and \
                receiver in self.__thumbnails:
            self.__current = receiver
            self.currentThumbnailChanged.emit(receiver)

        return super().eventFilter(receiver, event)

    def _moveCurrent(self, key, modifiers=Qt.NoModifier):
        """
        Move the current thumbnail focus (`currentItem`) based on a key press
        (Qt.Key{Up,Down,Left,Right})

        Parameters
        ----------
        key : Qt.Key
        modifiers : Qt.Modifiers
        """
        current = self.__current
        layout = self.__layout
        columns = layout.columnCount()
        rows = layout.rowCount()
        itempos = {}
        for i, j in itertools.product(range(rows), range(columns)):
            if i * columns + j >= layout.count():
                break
            item = layout.itemAt(i, j)
            if item is not None:
                itempos[item] = (i, j)
        pos = itempos.get(current, None)

        if pos is None:
            return False

        i, j = pos
        index = i * columns + j
        if key == Qt.Key_Left:
            index = index - 1
        elif key == Qt.Key_Right:
            index = index + 1
        elif key == Qt.Key_Down:
            index = index + columns
        elif key == Qt.Key_Up:
            index = index - columns

        index = min(max(index, 0), layout.count() - 1)
        i = index // columns
        j = index % columns
        newcurrent = layout.itemAt(i, j)
        assert newcurrent is self.__thumbnails[index]

        if newcurrent is not None:
            if not modifiers & (Qt.ShiftModifier | Qt.ControlModifier):
                for item in self.__thumbnails:
                    if item is not newcurrent:
                        item.setSelected(False)
                # self.scene().clearSelection()

            newcurrent.setSelected(True)
            newcurrent.setFocus(Qt.TabFocusReason)
            newcurrent.ensureVisible()

        if self.__current is not newcurrent:
            self.__current = newcurrent
            self.currentThumbnailChanged.emit(newcurrent)
Exemple #27
0
    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 replot_experiments(self):
        """Replot the whole quality plot.
        """
        self.scene.clear()
        labels = []

        max_dist = numpy.nanmax(list(filter(None, self.distances)))
        rug_widgets = []

        group_pen = QPen(Qt.black)
        group_pen.setWidth(2)
        group_pen.setCapStyle(Qt.RoundCap)
        background_pen = QPen(QColor(0, 0, 250, 150))
        background_pen.setWidth(1)
        background_pen.setCapStyle(Qt.RoundCap)

        main_widget = QGraphicsWidget()
        layout = QGraphicsGridLayout()
        attributes = self.data.domain.attributes
        if self.data is not None:
            for (group, indices), dist_vec in zip(self.groups, self.distances):
                indices_set = set(indices)
                rug_items = []
                if dist_vec is not None:
                    for i, attr in enumerate(attributes):
                        # Is this a within group distance or background
                        in_group = i in indices_set
                        if in_group:
                            rug_item = ClickableRugItem(
                                dist_vec[i] / max_dist, 1.0,
                                self.on_rug_item_clicked)
                            rug_item.setPen(group_pen)
                            tooltip = experiment_description(attr)
                            rug_item.setToolTip(tooltip)
                            rug_item.group_index = indices.index(i)
                            rug_item.setZValue(rug_item.zValue() + 1)
                        else:
                            rug_item = ClickableRugItem(
                                dist_vec[i] / max_dist, 0.85,
                                self.on_rug_item_clicked)
                            rug_item.setPen(background_pen)
                            tooltip = experiment_description(attr)
                            rug_item.setToolTip(tooltip)

                        rug_item.group = group
                        rug_item.index = i
                        rug_item.in_group = in_group

                        rug_items.append(rug_item)

                rug_widget = RugGraphicsWidget(parent=main_widget)
                rug_widget.set_rug(rug_items)

                rug_widgets.append(rug_widget)

                label = group_label(self.selected_split_by_labels(), group)
                label_item = QGraphicsSimpleTextItem(label, main_widget)
                label_item = GraphicsSimpleTextLayoutItem(label_item,
                                                          parent=layout)
                label_item.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                labels.append(label_item)

        for i, (label, rug_w) in enumerate(zip(labels, rug_widgets)):
            layout.addItem(label, i, 0, Qt.AlignVCenter)
            layout.addItem(rug_w, i, 1)
            layout.setRowMaximumHeight(i, 30)

        main_widget.setLayout(layout)
        self.scene.addItem(main_widget)
        self.main_widget = main_widget
        self.rug_widgets = rug_widgets
        self.labels = labels
        self.on_view_resize(self.scene_view.size())