示例#1
0
文件: tray.py 项目: herlang/iosshy
class Tray(QObject):
    activated = pyqtSignal()

    def __init__(self, parent, title, icon):
        QObject.__init__(self)

        # Setup contextual menu
        if kde:
            self.menu = KMenu(parent)
            self.tray = KStatusNotifierItem(parent)
            self.tray.setStatus(KStatusNotifierItem.Passive)
            self.tray.setCategory(KStatusNotifierItem.ApplicationStatus)
            self.tray.setAssociatedWidget(parent)
            self.tray.setStandardActionsEnabled(False)
            self.tray.activateRequested.connect(self._activateRequested)
        else:
            self.menu = QMenu()
            self.tray = QSystemTrayIcon()
            self.tray.activated.connect(self._activated)
        self.setIcon(icon)
        self.setTitle(title)
        if not kde:
            self.tray.show()
        self.tray.setContextMenu(self.menu)

    def setActive(self, active=True):
        if kde:
            self.tray.setStatus(KStatusNotifierItem.Active if active else KStatusNotifierItem.Passive)

    def setTitle(self, title):
        if kde:
            self.tray.setTitle(title)
            self.tray.setToolTipTitle(title)
        else:
            self.tray.setToolTip(title)
        self.menu.setTitle(title)

    def setToolTipSubTitle(self, subtitle):
        if kde:
            self.tray.setToolTipSubTitle(subtitle)

    def setIcon(self, icon):
        if kde:
            self.tray.setIconByPixmap(icon)
            self.tray.setToolTipIconByPixmap(icon)
        else:
            self.tray.setIcon(icon)

    def showMessage(self, title, message, icon=None):
        if kde:
            self.tray.showMessage(title, message, "network-server")
        else:
            self.tray.showMessage(title, message, QSystemTrayIcon.Information if icon is None else icon)

    def _activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.activated.emit()

    def _activateRequested(self, active, pos):
        self.activated.emit()
示例#2
0
class WingedBox(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle('WingedBox')
        pixmap = QPixmap(config.images['icon'])
        self.setWindowIcon(QIcon(pixmap))

        self.user = ''
        self.password = ''

        self._vbox = QVBoxLayout(self)
        self._login = Login(self, HOME_WINGED_PATH)
        self._vbox.addWidget(self._login)
        self._winged = Winged(self, pref)
        self._winged.setVisible(False)
        self._vbox.addWidget(self._winged)

        #SystemTray Menu
        self._menu = QMenu('WingedBox')
        self._myfiles = self._menu.addAction(QIcon(config.images['icon']), 'Files')
        self._myfiles.setEnabled(False)
        self._init = self._menu.addAction(self.style().standardIcon(QStyle.SP_DialogOkButton), 'Init Session')
        self._close = self._menu.addAction(self.style().standardIcon(QStyle.SP_DialogCloseButton), 'Close Session')
        self._close.setVisible(False)
        self._menu.addSeparator()
        self._properties = self._menu.addAction('Preferences')
        self._menu.addSeparator()
        exit = self._menu.addAction(self.style().standardIcon(QStyle.SP_TitleBarCloseButton), 'Exit')

        #SystemTray
        self._tray = QSystemTrayIcon(QIcon(pixmap), self)
        self._tray.setToolTip('WingedBox')
        self._tray.setVisible(True)
        self._tray.setContextMenu(self._menu)

        #Signal -> Slot
        self.connect(exit, SIGNAL("triggered()"), sys.exit)
        self.connect(self._myfiles, SIGNAL("triggered()"), self.show)
        self.connect(self._init, SIGNAL("triggered()"), self.show)
        self.connect(self._properties, SIGNAL("triggered()"), self.show_properties)
        self.connect(self._close, SIGNAL("triggered()"), self.disconnect)

    def show_properties(self):
        self.prop = preferences.Preferences(self, pref)
        self.prop.show()

    def disconnect(self):
        self.user = ''
        self.password = ''
        self._myfiles.setEnabled(False)
        self._init.setVisible(True)
        self._close.setVisible(False)
        self._winged.hide()
        self._login.show()

    def closeEvent(self, event):
        event.ignore()
        self.hide()
示例#3
0
class StartQT4(Windows):
	
	def keyPressEvent(self, event):
		k = event.key() 
		if k == QtCore.Qt.Key_Escape:
			sys.exit()
		elif k == QtCore.Qt.Key_Enter-1:
			self.ui.btnSend.clicked.emit(True)
			
	def __init__(self, parent=None):
		QtGui.QWidget.__init__(self, parent)
		self.ui = Ui_winMain()
		self.ui.setupUi(self)
		QtCore.QObject.connect(self.ui.btnSend, QtCore.SIGNAL("clicked()"), self.SendQuery)
		self.setMouseTracking(True)
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint|QtCore.Qt.WindowStaysOnTopHint| Qt.Popup | Qt.Tool)
		
		# 创建托盘
		self.icon = QIcon("img.png")
		self.trayIcon = QSystemTrayIcon(self)
		self.trayIcon.setIcon(self.icon)
		self.trayIcon.setToolTip(u"simple有道")
		self.trayIcon.show()
		# 托盘气泡消息
		self.trayIcon.showMessage(u"simple有道", u"simple有道已经启动,随时待命!")
		# 托盘菜单
		self.action = QAction(u"退出simple有道", self, triggered = sys.exit) # 触发点击后调用sys.exit()命令,即退出
		self.menu = QMenu(self)
		self.menu.addAction(self.action)
		self.trayIcon.setContextMenu(self.menu)
		self.move(1100,50)
		#开启监听线程
		system("xclip -f /dev/null")           #清空剪切板
		listener = Thread(target=listenMouse, args=(self.ui,))
		listener.setDaemon(True)
		listener.start()
        
	def SendQuery(self):
		querystring = "http://fanyi.youdao.com/openapi.do?keyfrom=hustbg&key=1205943053&type=data&doctype=json&version=1.1&q="+unicode(self.ui.txtSend.text())
		response = json.loads(requests.get(querystring).text)
		try:
			result = u"   音标:"+response["basic"].get("phonetic","")+u"\n   翻译:"+u','.join(response["translation"])+u"\n   解释:\n   "+'\n   '.join(response["basic"]["explains"][0:2])
			self.ui.labresult.setText(result)
		except:
			self.ui.labresult.setText(u"没有查到相关记录")
示例#4
0
文件: tray.py 项目: Kenishi/DroidNavi
class Tray():

    def __init__(self, parent):
        
        icon = AppIcon.getAppIcon()
        if icon:
            self.tray = QSystemTrayIcon(icon)
        else:
            self.tray = QSystemTrayIcon()
        self.parent = parent
        
        self.tray.setToolTip("Droid Navi")
        
        # Menu
        self.menu = QMenu()
        self.menu.addAction("Show Connected List", partial(self.maximize))
        self.menu.addAction("Options", partial(self.parent.openSettings))
        self.menu.addAction("Exit", partial(self.parent.close))
        self.tray.setContextMenu(self.menu)
        
        # Connect handlers
        self.tray.activated.connect(self.activated)
    
    def getTray(self):
        return self.tray
     
    def display(self, show):
        ''' Toggle showing the tray '''
        
        if show:
            self.tray.show()
        else:
            self.tray.hide()
    
    @pyqtSlot()
    def maximize(self):
        ''' Show the main window and hide tray icon '''
        
        self.display(False)
        self.parent.maximizeFromTray()
    
    @pyqtSlot()
    def activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.maximize()
示例#5
0
class Tray():
    def __init__(self, parent):

        icon = AppIcon.getAppIcon()
        if icon:
            self.tray = QSystemTrayIcon(icon)
        else:
            self.tray = QSystemTrayIcon()
        self.parent = parent

        self.tray.setToolTip("Droid Navi")

        # Menu
        self.menu = QMenu()
        self.menu.addAction("Show Connected List", partial(self.maximize))
        self.menu.addAction("Options", partial(self.parent.openSettings))
        self.menu.addAction("Exit", partial(self.parent.close))
        self.tray.setContextMenu(self.menu)

        # Connect handlers
        self.tray.activated.connect(self.activated)

    def getTray(self):
        return self.tray

    def display(self, show):
        ''' Toggle showing the tray '''

        if show:
            self.tray.show()
        else:
            self.tray.hide()

    @pyqtSlot()
    def maximize(self):
        ''' Show the main window and hide tray icon '''

        self.display(False)
        self.parent.maximizeFromTray()

    @pyqtSlot()
    def activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.maximize()
class Example(QtGui.QMainWindow):

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


self.path=sys.path[0]
f=open('%s/ACCESS_KEY'% self.path,'r')
f1=open('%s/ACCESS_SECRET'% self.path,'r')
f2=open('%s/user_info'% self.path)
self.user_name=f2.readline().strip('\n')
self.user_id=f2.readline().strip('\n')
self.a=f.readline().strip('\n')
self.b=f1.readline().strip('\n')
f.close()
f1.close()
f2.close()
self.initUI()

def initUI(self):

self.icon=QSystemTrayIcon()
self.icon.isSystemTrayAvailable()
self.icon.setIcon( QtGui.QIcon('%s/web.png'% self.path) )
self.icon.setToolTip ( 'dubbleclick to maximize')
self.icon.show()
self.icon.activated.connect(self.activate)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
                self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setGeometry(300, 300, 1500, 1000)
frame = QtGui.QFrame(parent=self)
                frame.setStyleSheet("QFrame {background: rgba(0,0,0,50%)}")
box=QtGui.QHBoxLayout()

self.edit = QtGui.QLineEdit()
         self.edit.setStyleSheet("background: rgba(0,0,0,100%); "" font-weight : bold;" "color: rgb(250,250,250);""border:5px solid ")
示例#7
0
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)
        uic.loadUi("./MainWindow/form.ui", self)
        self.setWindowTitle("NFS-List")
        self.setLayout(self.gridLayout)
        self.setGeometry(100, 100, 640, 480)
        self.listWidget.setViewMode(QtGui.QListView.IconMode)
        self.listWidget.setMovement(QtGui.QListWidget.Static)
        self.ipv6_enable = True  # False
        self.addr_ipv4 = None
        self.addr_ipv6 = None
        self.addr_ipv4_array = []
        self.addr_ipv6_array = []
        self.time = 1

        self.hosts = []
        self.icon = QtGui.QIcon("./MainWindow/NAS-icon.png")
        self.setWindowIcon(self.icon)

        #Tray
        tray_menu = QtGui.QMenu(self)

        show_hide_action = QAction("Show/Hide", self)
        quitAction = QAction("Quit", self)

        tray_menu.addAction(show_hide_action)
        tray_menu.addAction(quitAction)

        tray = QSystemTrayIcon(self)
        tray.setIcon(self.icon)
        tray.setContextMenu(tray_menu)
        tray.setToolTip(self.windowTitle())
        tray.show()
        #
        show_hide_action.triggered.connect(self.showHideWindow)
        quitAction.triggered.connect(QtGui.qApp.quit)

        #end tray

        # self.ico.addPixmap(self.pixmap)
        ifaces = QtNetwork.QNetworkInterface.allInterfaces()
        for iface in ifaces:
            for addr_iface in iface.addressEntries():
                if addr_iface.ip() != QtNetwork.QHostAddress(QtNetwork.QHostAddress.LocalHost) and \
                                addr_iface.ip() != QtNetwork.QHostAddress(QtNetwork.QHostAddress.LocalHostIPv6):
                    if addr_iface.ip().toIPv4Address():
                        self.addr_ipv4_array.append(addr_iface)
                    if self.ipv6_enable:
                        if addr_iface.ip().toIPv6Address():
                            self.addr_ipv6_array.append(addr_iface)

        if len(self.addr_ipv4_array) >= 1:
            self.addr_ipv4 = self.addr_ipv4_array[0].ip().toString()

        #ip data#

        addr_mask = self.addr_ipv4_array[0].netmask().toString()
        #addr_mask = '255.255.255.192'

        __list_aprefix = addr_mask.split('.')
        cidr_ipv4 = 0
        bn = '0b'
        baddr = '0b'
        for i in __list_aprefix:
            cidr_ipv4 += rpclib.bit_count(int(i))
            bn += bin(int(i))[2:]

        print("cidr:", cidr_ipv4)
        print(bn)
        #
        total_ip_count = (2 ** (32 - cidr_ipv4)) - 2
        print('total_ip_count:', total_ip_count)
        print(self.addr_ipv4)
        int_net_ipv4 = rpclib.ip2int(self.addr_ipv4) & rpclib.ip2int(addr_mask)
        net_ipv4 = rpclib.int2ip(int_net_ipv4)


        #abc = ClockThread(self.time, self.add_new_item)
        #abc.start()
        #self.add_new_item('t34', 't32')

        self.scan_network = ThreadScanNetwork(10, net_ipv4, cidr_ipv4, self, 1.2)
        self.scan_network.start()

        self.check_host = ThreadCheckHost(self.hosts, self)
        self.check_host.start()

        #self.add_host({"host":"100.64.0.1","structures":[{'groups': [b'*'], 'dir': b'/srv/NFS'}]})
        """
        self.listWidget.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)

        self.actionInfo = QAction("Info", self.listWidget)
        self.actionMount = QAction("Mount", self.listWidget)
        self.listWidget.addAction(self.actionMount)
        self.listWidget.addAction(self.actionInfo)

        self.actionInfo.triggered.connect(self.showInfo)
        self.actionMount.triggered.connect(self.my_method)
        """
        self.listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.listWidget.customContextMenuRequested.connect(self.showRightMenu)
示例#8
0
class Qt4SysTrayIcon:
    def __init__(self):
        self.snapshots = snapshots.Snapshots()
        self.config = self.snapshots.config

        if len(sys.argv) > 1:
            if not self.config.set_current_profile(sys.argv[1]):
                logger.warning("Failed to change Profile_ID %s" % sys.argv[1],
                               self)

        self.qapp = qt4tools.create_qapplication(self.config.APP_NAME)

        import icon
        self.icon = icon
        self.qapp.setWindowIcon(icon.BIT_LOGO)

        self.status_icon = QSystemTrayIcon(icon.BIT_LOGO)
        #self.status_icon.actionCollection().clear()
        self.contextMenu = QMenu()

        self.menuProfileName = self.contextMenu.addAction(
            _('Profile: "%s"') % self.config.get_profile_name())
        qt4tools.set_font_bold(self.menuProfileName)
        self.contextMenu.addSeparator()

        self.menuStatusMessage = self.contextMenu.addAction(_('Done'))
        self.menuProgress = self.contextMenu.addAction('')
        self.menuProgress.setVisible(False)
        self.contextMenu.addSeparator()
        self.startBIT = self.contextMenu.addAction(icon.BIT_LOGO,
                                                   _('Start BackInTime'))
        QObject.connect(self.startBIT, SIGNAL('triggered()'), self.onStartBIT)
        self.status_icon.setContextMenu(self.contextMenu)

        self.pixmap = icon.BIT_LOGO.pixmap(24)
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)
        self.progressBar.setTextVisible(False)
        self.progressBar.resize(24, 6)
        self.progressBar.render(self.pixmap,
                                sourceRegion=QRegion(0, -14, 24, 6),
                                flags=QWidget.RenderFlags(
                                    QWidget.DrawChildren))

        self.first_error = self.config.is_notify_enabled()
        self.popup = None
        self.last_message = None

        self.timer = QTimer()
        QObject.connect(self.timer, SIGNAL('timeout()'), self.update_info)

        self.ppid = os.getppid()

    def prepare_exit(self):
        self.timer.stop()

        if not self.status_icon is None:
            self.status_icon.hide()
            self.status_icon = None

        if not self.popup is None:
            self.popup.deleteLater()
            self.popup = None

        self.qapp.processEvents()

    def run(self):
        self.status_icon.show()
        self.timer.start(500)

        logger.info("[qt4systrayicon] begin loop", self)

        self.qapp.exec_()

        logger.info("[qt4systrayicon] end loop", self)

        self.prepare_exit()

    def update_info(self):
        if not tools.is_process_alive(self.ppid):
            self.prepare_exit()
            self.qapp.exit(0)
            return

        message = self.snapshots.get_take_snapshot_message()
        if message is None and self.last_message is None:
            message = (0, _('Working...'))

        if not message is None:
            if message != self.last_message:
                self.last_message = message
                self.menuStatusMessage.setText('\n'.join(tools.wrap_line(self.last_message[1],\
                                                                         size = 80,\
                                                                         delimiters = '',\
                                                                         new_line_indicator = '') \
                                                                        ))
                self.status_icon.setToolTip(self.last_message[1])

        pg = progress.ProgressFile(self.config)
        if pg.isFileReadable():
            pg.load()
            percent = pg.get_int_value('percent')
            if percent != self.progressBar.value():
                self.progressBar.setValue(percent)
                self.progressBar.render(self.pixmap,
                                        sourceRegion=QRegion(0, -14, 24, 6),
                                        flags=QWidget.RenderFlags(
                                            QWidget.DrawChildren))
                self.status_icon.setIcon(QIcon(self.pixmap))

            self.menuProgress.setText(' | '.join(self.getMenuProgress(pg)))
            self.menuProgress.setVisible(True)
        else:
            self.status_icon.setIcon(self.icon.BIT_LOGO)
            self.menuProgress.setVisible(False)

    def getMenuProgress(self, pg):
        d = (('sent',   _('Sent:')), \
             ('speed',  _('Speed:')),\
             ('eta',    _('ETA:')) )
        for key, txt in d:
            value = pg.get_str_value(key, '')
            if not value:
                continue
            yield txt + ' ' + value

    def onStartBIT(self):
        profileID = self.config.get_current_profile()
        cmd = [
            'backintime-qt4',
        ]
        if not profileID == '1':
            cmd += ['--profile-id', profileID]
        proc = subprocess.Popen(cmd)
示例#9
0
class GlobalSysTray(object):
    def __init__(self, parent, name, icon):
        object.__init__(self)

        self._app    = None
        self._parent = parent
        self._gtk_running = False
        self._quit_added  = False

        self.act_indexes  = []
        self.sep_indexes  = []
        self.menu_indexes = []

        if TrayEngine == "KDE":
            self.menu = KMenu(parent)
            self.menu.setTitle(name)
            self.tray = KStatusNotifierItem()
            self.tray.setAssociatedWidget(parent)
            self.tray.setCategory(KStatusNotifierItem.ApplicationStatus)
            self.tray.setContextMenu(self.menu)
            self.tray.setIconByPixmap(getIcon(icon))
            self.tray.setTitle(name)
            self.tray.setToolTipTitle(" ")
            self.tray.setToolTipIconByPixmap(getIcon(icon))
            # Double-click is managed by KDE

        elif TrayEngine == "AppIndicator":
            self.menu = Gtk.Menu()
            self.tray = AppIndicator.Indicator.new(name, icon, AppIndicator.IndicatorCategory.APPLICATION_STATUS)
            self.tray.set_menu(self.menu)
            # Double-click is not possible with App-Indicators

        elif TrayEngine == "Qt":
            self.menu = QMenu(parent)
            self.tray = QSystemTrayIcon(getIcon(icon))
            self.tray.setContextMenu(self.menu)
            self.tray.setParent(parent)
            self.tray.connect(self.tray, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.qt_systray_clicked)

    # -------------------------------------------------------------------------------------------

    def addAction(self, act_name_id, act_name_string, is_check=False):
        if TrayEngine == "KDE":
            act_widget = KAction(act_name_string, self.menu)
            act_widget.setCheckable(is_check)
            self.menu.addAction(act_widget)

        elif TrayEngine == "AppIndicator":
            if is_check:
                act_widget = Gtk.CheckMenuItem(act_name_string)
            else:
                act_widget = Gtk.ImageMenuItem(act_name_string)
                act_widget.set_image(None)
            act_widget.show()
            self.menu.append(act_widget)

        elif TrayEngine == "Qt":
            act_widget = QAction(act_name_string, self.menu)
            act_widget.setCheckable(is_check)
            self.menu.addAction(act_widget)

        else:
            act_widget = None

        act_obj = [None, None, None, None]
        act_obj[iActNameId] = act_name_id
        act_obj[iActWidget] = act_widget

        self.act_indexes.append(act_obj)

    def addSeparator(self, sep_name_id):
        if TrayEngine == "KDE":
            sep_widget = self.menu.addSeparator()

        elif TrayEngine == "AppIndicator":
            sep_widget = Gtk.SeparatorMenuItem()
            sep_widget.show()
            self.menu.append(sep_widget)

        elif TrayEngine == "Qt":
            sep_widget = self.menu.addSeparator()

        else:
            sep_widget = None

        sep_obj = [None, None, None]
        sep_obj[iSepNameId] = sep_name_id
        sep_obj[iSepWidget] = sep_widget

        self.sep_indexes.append(sep_obj)

    def addMenu(self, menu_name_id, menu_name_string):
        if TrayEngine == "KDE":
            menu_widget = KMenu(menu_name_string, self.menu)
            self.menu.addMenu(menu_widget)

        elif TrayEngine == "AppIndicator":
            menu_widget = Gtk.MenuItem(menu_name_string)
            menu_parent = Gtk.Menu()
            menu_widget.set_submenu(menu_parent)
            menu_widget.show()
            self.menu.append(menu_widget)

        elif TrayEngine == "Qt":
            menu_widget = QMenu(menu_name_string, self.menu)
            self.menu.addMenu(menu_widget)

        else:
            menu_widget = None

        menu_obj = [None, None, None]
        menu_obj[iMenuNameId] = menu_name_id
        menu_obj[iMenuWidget] = menu_widget

        self.menu_indexes.append(menu_obj)

    # -------------------------------------------------------------------------------------------

    def addMenuAction(self, menu_name_id, act_name_id, act_name_string, is_check=False):
        i = self.get_menu_index(menu_name_id)
        if i < 0: return

        menu_widget = self.menu_indexes[i][iMenuWidget]

        if TrayEngine == "KDE":
            act_widget = KAction(act_name_string, menu_widget)
            act_widget.setCheckable(is_check)
            menu_widget.addAction(act_widget)

        elif TrayEngine == "AppIndicator":
            menu_widget = menu_widget.get_submenu()
            if is_check:
                act_widget = Gtk.CheckMenuItem(act_name_string)
            else:
                act_widget = Gtk.ImageMenuItem(act_name_string)
                act_widget.set_image(None)
            act_widget.show()
            menu_widget.append(act_widget)

        elif TrayEngine == "Qt":
            act_widget = QAction(act_name_string, menu_widget)
            act_widget.setCheckable(is_check)
            menu_widget.addAction(act_widget)

        else:
            act_widget = None

        act_obj = [None, None, None, None]
        act_obj[iActNameId] = act_name_id
        act_obj[iActWidget] = act_widget
        act_obj[iActParentMenuId] = menu_name_id

        self.act_indexes.append(act_obj)

    def addMenuSeparator(self, menu_name_id, sep_name_id):
        i = self.get_menu_index(menu_name_id)
        if i < 0: return

        menu_widget = self.menu_indexes[i][iMenuWidget]

        if TrayEngine == "KDE":
            sep_widget = menu_widget.addSeparator()

        elif TrayEngine == "AppIndicator":
            menu_widget = menu_widget.get_submenu()
            sep_widget = Gtk.SeparatorMenuItem()
            sep_widget.show()
            menu_widget.append(sep_widget)

        elif TrayEngine == "Qt":
            sep_widget = menu_widget.addSeparator()

        else:
            sep_widget = None

        sep_obj = [None, None, None]
        sep_obj[iSepNameId] = sep_name_id
        sep_obj[iSepWidget] = sep_widget
        sep_obj[iSepParentMenuId] = menu_name_id

        self.sep_indexes.append(sep_obj)

    #def addSubMenu(self, menu_name_id, new_menu_name_id, new_menu_name_string):
        #menu_index = self.get_menu_index(menu_name_id)
        #if menu_index < 0: return
        #menu_widget = self.menu_indexes[menu_index][1]
        ##if TrayEngine == "KDE":
            ##new_menu_widget = KMenu(new_menu_name_string, self.menu)
            ##menu_widget.addMenu(new_menu_widget)
        ##elif TrayEngine == "AppIndicator":
            ##new_menu_widget = Gtk.MenuItem(new_menu_name_string)
            ##new_menu_widget.show()
            ##menu_widget.get_submenu().append(new_menu_widget)
            ##parent_menu_widget = Gtk.Menu()
            ##new_menu_widget.set_submenu(parent_menu_widget)
        ##else:
        #if (1):
            #new_menu_widget = QMenu(new_menu_name_string, self.menu)
            #menu_widget.addMenu(new_menu_widget)
        #self.menu_indexes.append([new_menu_name_id, new_menu_widget, menu_name_id])

    # -------------------------------------------------------------------------------------------

    def connect(self, act_name_id, act_func):
        i = self.get_act_index(act_name_id)
        if i < 0: return

        act_widget = self.act_indexes[i][iActWidget]

        if TrayEngine == "KDE":
            self.tray.connect(act_widget, SIGNAL("triggered()"), act_func)

        elif TrayEngine == "AppIndicator":
            act_widget.connect("activate", self.gtk_call_func, act_name_id)

        elif TrayEngine == "Qt":
            self.tray.connect(act_widget, SIGNAL("triggered()"), act_func)

        self.act_indexes[i][iActFunc] = act_func

    # -------------------------------------------------------------------------------------------

    #def setActionChecked(self, act_name_id, yesno):
        #index = self.get_act_index(act_name_id)
        #if index < 0: return
        #act_widget = self.act_indexes[index][1]
        ##if TrayEngine == "KDE":
            ##act_widget.setChecked(yesno)
        ##elif TrayEngine == "AppIndicator":
            ##if type(act_widget) != Gtk.CheckMenuItem:
                ##return # Cannot continue
            ##act_widget.set_active(yesno)
        ##else:
        #if (1):
            #act_widget.setChecked(yesno)

    def setActionEnabled(self, act_name_id, yesno):
        i = self.get_act_index(act_name_id)
        if i < 0: return

        act_widget = self.act_indexes[i][iActWidget]

        if TrayEngine == "KDE":
            act_widget.setEnabled(yesno)

        elif TrayEngine == "AppIndicator":
            act_widget.set_sensitive(yesno)

        elif TrayEngine == "Qt":
            act_widget.setEnabled(yesno)

    def setActionIcon(self, act_name_id, icon):
        i = self.get_act_index(act_name_id)
        if i < 0: return

        act_widget = self.act_indexes[i][iActWidget]

        if TrayEngine == "KDE":
            act_widget.setIcon(KIcon(icon))

        elif TrayEngine == "AppIndicator":
            if not isinstance(act_widget, Gtk.ImageMenuItem):
                # Cannot use icons here
                return

            act_widget.set_image(Gtk.Image.new_from_icon_name(icon, Gtk.IconSize.MENU))
            #act_widget.set_always_show_image(True)

        elif TrayEngine == "Qt":
            act_widget.setIcon(getIcon(icon))

    def setActionText(self, act_name_id, text):
        i = self.get_act_index(act_name_id)
        if i < 0: return

        act_widget = self.act_indexes[i][iActWidget]

        if TrayEngine == "KDE":
            act_widget.setText(text)

        elif TrayEngine == "AppIndicator":
            if isinstance(act_widget, Gtk.ImageMenuItem):
                # Fix icon reset
                last_icon = act_widget.get_image()
                act_widget.set_label(text)
                act_widget.set_image(last_icon)
            else:
                act_widget.set_label(text)

        elif TrayEngine == "Qt":
            act_widget.setText(text)

    def setIcon(self, icon):
        if TrayEngine == "KDE":
            self.tray.setIconByPixmap(getIcon(icon))
            #self.tray.setToolTipIconByPixmap(getIcon(icon))

        elif TrayEngine == "AppIndicator":
            self.tray.set_icon(icon)

        elif TrayEngine == "Qt":
            self.tray.setIcon(getIcon(icon))

    def setToolTip(self, text):
        if TrayEngine == "KDE":
            self.tray.setToolTipSubTitle(text)

        elif TrayEngine == "AppIndicator":
            # ToolTips are disabled in App-Indicators by design
            pass

        elif TrayEngine == "Qt":
            self.tray.setToolTip(text)

    # -------------------------------------------------------------------------------------------

    #def removeAction(self, act_name_id):
        #index = self.get_act_index(act_name_id)
        #if index < 0: return
        #act_widget = self.act_indexes[index][1]
        #parent_menu_widget = self.get_parent_menu_widget(self.act_indexes[index][2])
        ##if TrayEngine == "KDE":
            ##parent_menu_widget.removeAction(act_widget)
        ##elif TrayEngine == "AppIndicator":
            ##act_widget.hide()
            ##parent_menu_widget.remove(act_widget)
        ##else:
        #if (1):
            #parent_menu_widget.removeAction(act_widget)
        #self.act_indexes.pop(index)

    #def removeSeparator(self, sep_name_id):
        #index = self.get_sep_index(sep_name_id)
        #if index < 0: return
        #sep_widget = self.sep_indexes[index][1]
        #parent_menu_widget = self.get_parent_menu_widget(self.sep_indexes[index][2])
        ##if TrayEngine == "KDE":
            ##parent_menu_widget.removeAction(sep_widget)
        ##elif TrayEngine == "AppIndicator":
            ##sep_widget.hide()
            ##parent_menu_widget.remove(sep_widget)
        ##else:
        #if (1):
            #parent_menu_widget.removeAction(sep_widget)
        #self.sep_indexes.pop(index)

    #def removeMenu(self, menu_name_id):
        #index = self.get_menu_index(menu_name_id)
        #if index < 0: return
        #menu_widget = self.menu_indexes[index][1]
        #parent_menu_widget = self.get_parent_menu_widget(self.menu_indexes[index][2])
        ##if TrayEngine == "KDE":
            ##parent_menu_widget.removeAction(menu_widget.menuAction())
        ##elif TrayEngine == "AppIndicator":
            ##menu_widget.hide()
            ##parent_menu_widget.remove(menu_widget.get_submenu())
        ##else:
        #if (1):
            #parent_menu_widget.removeAction(menu_widget.menuAction())
        #self.remove_actions_by_menu_name_id(menu_name_id)
        #self.remove_separators_by_menu_name_id(menu_name_id)
        #self.remove_submenus_by_menu_name_id(menu_name_id)

    # -------------------------------------------------------------------------------------------

    #def clearAll(self):
        ##if TrayEngine == "KDE":
            ##self.menu.clear()
        ##elif TrayEngine == "AppIndicator":
            ##for child in self.menu.get_children():
                ##self.menu.remove(child)
        ##else:
        #if (1):
            #self.menu.clear()

        #self.act_indexes = []
        #self.sep_indexes = []
        #self.menu_indexes = []

    #def clearMenu(self, menu_name_id):
        #menu_index = self.get_menu_index(menu_name_id)
        #if menu_index < 0: return
        #menu_widget = self.menu_indexes[menu_index][1]
        ##if TrayEngine == "KDE":
            ##menu_widget.clear()
        ##elif TrayEngine == "AppIndicator":
            ##for child in menu_widget.get_submenu().get_children():
                ##menu_widget.get_submenu().remove(child)
        ##else:
        #if (1):
            #menu_widget.clear()
        #list_of_submenus = [menu_name_id]
        #for x in range(0, 10): # 10x level deep, should cover all cases...
            #for this_menu_name_id, menu_widget, parent_menu_id in self.menu_indexes:
                #if parent_menu_id in list_of_submenus and this_menu_name_id not in list_of_submenus:
                    #list_of_submenus.append(this_menu_name_id)
        #for this_menu_name_id in list_of_submenus:
            #self.remove_actions_by_menu_name_id(this_menu_name_id)
            #self.remove_separators_by_menu_name_id(this_menu_name_id)
            #self.remove_submenus_by_menu_name_id(this_menu_name_id)

    # -------------------------------------------------------------------------------------------

    def getTrayEngine(self):
        return TrayEngine

    def isTrayAvailable(self):
        if TrayEngine in ("KDE", "Qt"):
            return QSystemTrayIcon.isSystemTrayAvailable()
        elif TrayEngine == "AppIndicator":
            # Ubuntu/Unity always has a systray
            return True
        else:
            return False

    def handleQtCloseEvent(self, event):
        if self.isTrayAvailable() and self._parent.isVisible():
            event.accept()
            self.__hideShowCall()
            return

        self.close()
        QMainWindow.closeEvent(self._parent, event)

    # -------------------------------------------------------------------------------------------

    def show(self):
        if not self._quit_added:
            self._quit_added = True

            if TrayEngine != "KDE":
                self.addSeparator("_quit")
                self.addAction("show", self._parent.tr("Minimize"))
                self.addAction("quit", self._parent.tr("Quit"))
                self.setActionIcon("quit", "application-exit")
                self.connect("show", self.__hideShowCall)
                self.connect("quit", self.__quitCall)

        if TrayEngine == "KDE":
            self.tray.setStatus(KStatusNotifierItem.Active)
        elif TrayEngine == "AppIndicator":
            self.tray.set_status(AppIndicator.IndicatorStatus.ACTIVE)
        elif TrayEngine == "Qt":
            self.tray.show()

    def hide(self):
        if TrayEngine == "KDE":
            self.tray.setStatus(KStatusNotifierItem.Passive)
        elif TrayEngine == "AppIndicator":
            self.tray.set_status(AppIndicator.IndicatorStatus.PASSIVE)
        elif TrayEngine == "Qt":
            self.tray.hide()

    def close(self):
        if TrayEngine == "KDE":
            self.menu.close()
        elif TrayEngine == "AppIndicator":
            if self._gtk_running:
                self._gtk_running = False
                Gtk.main_quit()
        elif TrayEngine == "Qt":
            self.menu.close()

    def exec_(self, app):
        self._app = app
        if TrayEngine == "AppIndicator":
            self._gtk_running = True
            return Gtk.main()
        else:
            return app.exec_()

    # -------------------------------------------------------------------------------------------

    def get_act_index(self, act_name_id):
        for i in range(len(self.act_indexes)):
            if self.act_indexes[i][iActNameId] == act_name_id:
                return i
        else:
            print("systray.py - Failed to get action index for %s" % act_name_id)
            return -1

    def get_sep_index(self, sep_name_id):
        for i in range(len(self.sep_indexes)):
            if self.sep_indexes[i][iSepNameId] == sep_name_id:
                return i
        else:
            print("systray.py - Failed to get separator index for %s" % sep_name_id)
            return -1

    def get_menu_index(self, menu_name_id):
        for i in range(len(self.menu_indexes)):
            if self.menu_indexes[i][iMenuNameId] == menu_name_id:
                return i
        else:
            print("systray.py - Failed to get menu index for %s" % menu_name_id)
            return -1

    #def get_parent_menu_widget(self, parent_menu_id):
        #if parent_menu_id != None:
            #menu_index = self.get_menu_index(parent_menu_id)
            #if menu_index >= 0:
                #return self.menu_indexes[menu_index][1]
            #else:
                #print("systray.py::Failed to get parent Menu widget for", parent_menu_id)
                #return None
        #else:
            #return self.menu

    #def remove_actions_by_menu_name_id(self, menu_name_id):
        #h = 0
        #for i in range(len(self.act_indexes)):
            #act_name_id, act_widget, parent_menu_id, act_func = self.act_indexes[i - h]
            #if parent_menu_id == menu_name_id:
                #self.act_indexes.pop(i - h)
                #h += 1

    #def remove_separators_by_menu_name_id(self, menu_name_id):
        #h = 0
        #for i in range(len(self.sep_indexes)):
            #sep_name_id, sep_widget, parent_menu_id = self.sep_indexes[i - h]
            #if parent_menu_id == menu_name_id:
                #self.sep_indexes.pop(i - h)
                #h += 1

    #def remove_submenus_by_menu_name_id(self, submenu_name_id):
        #h = 0
        #for i in range(len(self.menu_indexes)):
            #menu_name_id, menu_widget, parent_menu_id = self.menu_indexes[i - h]
            #if parent_menu_id == submenu_name_id:
                #self.menu_indexes.pop(i - h)
                #h += 1

    # -------------------------------------------------------------------------------------------

    def gtk_call_func(self, gtkmenu, act_name_id):
        i = self.get_act_index(act_name_id)
        if i < 0: return None

        return self.act_indexes[i][iActFunc]

    def qt_systray_clicked(self, reason):
        if reason in (QSystemTrayIcon.DoubleClick, QSystemTrayIcon.Trigger):
            self.__hideShowCall()

    # -------------------------------------------------------------------------------------------

    def __hideShowCall(self):
        if self._parent.isVisible():
            self.setActionText("show", self._parent.tr("Restore"))
            self._parent.hide()

            if self._app:
                self._app.setQuitOnLastWindowClosed(False)

        else:
            self.setActionText("show", self._parent.tr("Minimize"))

            if self._parent.isMaximized():
                self._parent.showMaximized()
            else:
                self._parent.showNormal()

            if self._app:
                self._app.setQuitOnLastWindowClosed(True)

            QTimer.singleShot(500, self.__raiseWindow)

    def __quitCall(self):
        if self._app:
            self._app.setQuitOnLastWindowClosed(True)

        self._parent.hide()
        self._parent.close()

    def __raiseWindow(self):
        self._parent.activateWindow()
        self._parent.raise_()
示例#10
0
class Example(QtGui.QMainWindow):

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

		self.path=sys.path[0]
		f=open('%s/ACCESS_KEY'% self.path,'r')
		f1=open('%s/ACCESS_SECRET'% self.path,'r')
		f2=open('%s/user_info'% self.path)
		self.user_name=f2.readline().strip('\n')
		self.user_id=f2.readline().strip('\n')
		self.a=f.readline().strip('\n')
		self.b=f1.readline().strip('\n')
		f.close()
		f1.close()
		f2.close()
		self.initUI()
		
	def initUI(self):   
		
		self.icon=QSystemTrayIcon()
		self.icon.isSystemTrayAvailable() 
		self.icon.setIcon( QtGui.QIcon('%s/web.png'% self.path) )
		self.icon.setToolTip ( 'dubbleclick to maximize')
		self.icon.show()
		self.icon.activated.connect(self.activate)
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
                self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
		self.setGeometry(300, 300, 1500, 1000)
		frame = QtGui.QFrame(parent=self)
                frame.setStyleSheet("QFrame {background: rgba(0,0,0,50%)}")
		box=QtGui.QHBoxLayout()
		
		self.edit = QtGui.QLineEdit()
        	self.edit.setStyleSheet("background: rgba(0,0,0,100%); "" font-weight : bold;" "color:  rgb(250,250,250);""border:5px solid ")
		self.edit.setToolTip('please  <b>Enter your tweet here </b> ')
		self.edit.returnPressed.connect(self.returnPressed)
                box.addWidget(self.edit)	
		
		frame.setLayout(box)
	

		qbtn1 = QtGui.QPushButton('quit', self)
	        qbtn1.clicked.connect(self.close)
		qbtn1.setStyleSheet( "background: rgba(0,0,0,100%); "" font-weight : bold;" "color:  rgb(250,250,250);""border:5px solid ")
	        box.addWidget(qbtn1)
		self.statusBar().setStyleSheet("background: rgba(0,0,0,100%);"" font-weight : bold;" "color:  rgb(250,250,250)")
		self.statusBar().showMessage('Press Enter to send Tweet and press ESC to minimize to tray ')

		
		self.setCentralWidget(frame)  
		self.setWindowIcon(QtGui.QIcon('%s/web.png' % self. path)) 
		

	        self.setWindowTitle('Tweet Fast ')
		self.center()    
	        self.show()
		self.twitter_auth()
		
	def twitter_auth(self):
		
		CONSUMER_KEY = 'VQLDtkDTlbAmT95m5cMsYQ'
		CONSUMER_SECRET = 'bAC0BF69qiEVARJlfFJZZCDQ9mrcqofq16ilQ4OjU'      
		ACCESS_KEY=self.a
		ACCESS_SECRET=self.b
		self.auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
		self.auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
	        

	def keyPressEvent(self, e):
		if e.key() == QtCore.Qt.Key_Escape:
			print 'Escape wass pressed '
			self.icon.show()
			
                        self.hide()
	def activate(self,reason ):
			print reason 
			if reason==2:
				self.show()
	
	def center(self):
        
	        qr = self.frameGeometry()
	        cp = QtGui.QDesktopWidget().availableGeometry().center()
	        qr.moveCenter(cp)
	        self.move(qr.topLeft())

	def returnPressed(self):
		path=sys.path[0]
		tweet = self.edit.text()
		api = tweepy.API(self.auth)
		self.statusBar().showMessage('Sending... ')
		api.update_status(tweet) 
		self.statusBar().showMessage('Your Tweet was send ')
		n = pynotify.Notification(" @ %s "% self.user_name , "your tweet was send ","%s/%s.jpg" % (path,self.user_id))
                n.set_hint('x', 200)
                n.set_hint('y', 400)
                pynotify.init('n')		
                n.show()
		self.statusBar().showMessage('Press Enter to send Tweet and press ESC to minimize to tray ')
		self.edit.clear()
class PigeonFeather(QMainWindow):
    """Main class for the application, inherits class genrated from pyuic"""

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

        # Check that environment supports systemtray
        if not QSystemTrayIcon.isSystemTrayAvailable():
            print('FATAL: There is no system tray')
            sys.exit(1)

        # Make sure that we can load an icon list
        try:
            with open('code2iconlist.pkl', 'rb') as iconList:
                self.codeToIconList = pickle.load(iconList)
        except (IOError, pickle.PickleError):
            print('FATAL: Could not not load code2iconlist')
            sys.exit(1)

        # See if balloon messages are supported
        #print('Desktop support balloon messages = ' + \
        #    str(QSystemTrayIcon.supportsMessages()))

        # Set the user config fle
        self.USER_CONFIG = os.path.expanduser('~/.pigeonfeather')

        # Load preferences
        self.loadConfig()

        # Class properties
        self.trayIcon = QSystemTrayIcon(self)

        # Weather Dialog and Configure Dialog
        self.weatherDialog = WeatherDialog(self)
        self.configureDialog = ConfigureDialog(self)

        # Set up the application
        self.setup()

    def setup(self):
        """Setup and start the application"""
        # Connect some slots

        # Icon is clicked
        self.connect(self.trayIcon, \
            SIGNAL('activated(QSystemTrayIcon::ActivationReason)'), \
            self.trayIconClicked)

        # Connnect slot emitted from CnfigureDialog to update preferences
        self.connect(self.configureDialog, SIGNAL('ConfigureDialogOk'), \
            self.saveConfig)

        # Set an initial icon for tray and weather dialog
        self.setTrayIcon(QIcon('images/22/dunno.png'))
        self.weatherDialog.labelIcon.setPixmap(QPixmap('images/64/dunno.png'))

        # Set the menu
        self.trayIcon.setContextMenu(self.createMenu())

        # Setup the config dialog with values loaded from config
        woeid = self.config.get('main', 'woeid')

        # If woeid is not valid set a default and use that
        try:
            self.configureDialog.setWoeid(woeid)
        except ValueError as ve:
            self.config.set('main', 'woeid', '2408842')
            self.configureDialog.setWoeid('2408842')

        # Set temperature units
        if self.config.get('units', 'temperature') == 'fahrenheit':
            self.configureDialog.setTemperature('fahrenheit')
        else:
            self.configureDialog.setTemperature('celcius')

        # Set distance units
        if self.config.get('units', 'distance') == 'km':
            self.configureDialog.setDistance('km')
        else:
            self.configureDialog.setDistance('mi')

        # Set wind units
        if self.config.get('units', 'wind') == 'kph':
            self.configureDialog.setWind('kph')
        else:
            self.configureDialog.setWind('mph')

        # Set pressure units
        if self.config.get('units', 'pressure') == 'mb':
            self.configureDialog.setPressure('mb')
        else:
            self.configureDialog.setPressure('in')

        # Start getWeather thread with Id from config
        # Connect two slots for the two signals emitted from thread
        self.getWeatherThread = GetWeatherQThread(self.config.get( \
            'main', 'woeid'))
        self.getWeatherThread.start()

        self.connect(self.getWeatherThread, SIGNAL('WeatherUpdate'), \
            self.processWeather)
        self.connect(self.getWeatherThread, SIGNAL('WeatherReadError'), \
            self.showErrorMessage)

    def loadConfig(self):
        """Load preferences from defaults then self.USER_CONFIG if exists"""
        # Load a default set first
        defaultConfig = io.StringIO("""\
[main]
Woeid=2408842
[units]
temperature=celcius
wind=mph
pressure=mb
distance=mi
""")

        self.config = ConfigParser()

        # Load defaults
        self.config.readfp(defaultConfig)

        # Load config if it exists
        self.config.read(self.USER_CONFIG)

    def createMenu(self):
        """Create and return the applications menu"""
        menu = QMenu(self)
        menu.addAction(QIcon('images/22/sunny.png'), '&Show Weather Report', \
            self.showWeatherDialog)
        menu.addAction(QIcon('images/22/configure.png'), '&Configure', \
            self.showConfigureDialog)
        menu.addAction(QIcon('images/22/help.png'), '&About', \
            self.showAboutDialog)
        menu.addAction(QIcon('images/22/exit.png'), '&Exit', self.quitApp)
        return menu

    def saveConfig(self, config):
        """Save the recieved config back to the config file and update the
        local copy in the object

        Keyword arguments:
        config -- A dict. of config recieved from the configuration dialog
        """
        # Set the local config object and try and save it
        self.config.set('main', 'woeid', config['woeid'])
        self.config.set('units', 'temperature', config['temperature'])
        self.config.set('units', 'wind', config['wind'])
        self.config.set('units', 'pressure', config['pressure'])
        self.config.set('units', 'distance', config['distance'])

        # Update the Weoid in the get weather thread
        self.getWeatherThread.setWoeid(config['woeid'])

        # Try and save the config
        try:
            with open(self.USER_CONFIG, 'wb') as configfile:
                self.config.write(configfile)
        except IOError as ioe:
            self.showErrorMessage('Could not save configuration settings' + \
                'to disk')

    def showErrorMessage(self, message):
        """Show a error as a tray balloon message

        Keyword arguments:
        message -- Error message to display
        """
        self.trayIcon.showMessage('Application Error', message, \
            QSystemTrayIcon.Critical)

    def trayIconClicked(self, reason):
        """If the tray icon is left clicked, show/hide the weather dialog
        If this is called on a Darwin(mac) machine do not pop up.  This follows
        better mac convention

        Keyword arguments:
        reason -- A QSystemTrayIcon.ActivationReason enum
        """
        # If mac then ignore click
        if platform.system() == 'Darwin':
            return

        # Test for left click
        if reason == 3:
            if self.weatherDialog.isVisible():
                self.weatherDialog.hide()
            else:
                self.weatherDialog.show()

    def showWeatherDialog(self):
        """Show the weather report dialog"""
        self.weatherDialog.show()

    def showConfigureDialog(self):
        """Show the configure dialog"""
        self.configureDialog.show()

    def showAboutDialog(self):
        """Show the about pyqtweather dialog"""
        QMessageBox.about(None, 'About Pigeon Feather', 'Pigeon Feather\n \
            (c) 2010 Ben Sampson\nPigeon Feather uses the Yahoo! Weather API\n\
            License: GNU General Public License Version 3')

    def processWeather(self, weather):
        """Slot that is called by the weather thread, responsible for updating
        the GUI with the new weather data, this includes the trayicon and
        tooltip and the weather report dialog

        Keyword arguments:
        weather -- map of weather data
        """
        # TODO These should really call setter methods on weather dialog

        # Copy weather to local vars basd on preferences
        fetched = weather['fetched']

        code = weather['code']
        if self.config.get('units', 'temperature') == 'celcius':
            temp = weather['tempC']
            chill = weather['chillC']
            tempUnit = 'C'
        else:
            temp = weather['tempF']
            chill = weather['chillF']
            tempUnit = 'F'

        text = weather['text']
        city = weather['city']
        region = weather['region']
        country = weather['country']

        sunrise = weather['sunrise']
        sunset = weather['sunset']

        if self.config.get('units', 'wind') == 'mph':
            windSpeed = weather['windSpeedMph']
            speedUnit = 'mph'
        else:
            windSpeed = weather['windSpeedKph']
            speedUnit = 'kph'

        if self.config.get('units', 'pressure') == 'mb':
            pressure = weather['pressureMb']
            pressureUnit = 'mb'
        else:
            pressure = weather['pressureIn']
            pressureUnit = 'in'

        directionTextual = weather['directionTextual']
        pressureTendancy = weather['pressureTendancy']
        humidity = weather['humidity']

        if self.config.get('units', 'distance') == 'mi':
            visibility = weather['visibilityMi']
            distanceUnit = 'mi'
        else:
            visibility = weather['visibilityKm']
            distanceUnit = 'km'

        # Get the filename for the icon to disply from the icon list map
        # Generate the system tray icon and set it
        iconFileName = self.codeToIconList[int(code)][1]
        icon = self.createWeatherIcon('images/22/' + iconFileName, str(temp))
        self.setTrayIcon(icon)

        # Set the tool tip
        tempString = str(temp) + '°' + tempUnit + ' ' + text
        self.trayIcon.setToolTip(tempString)

        # Update the weather report dialog
        self.weatherDialog.labelLastUpdate.setText( \
            fetched.strftime('%H:%M:%S'))
        self.weatherDialog.setWindowTitle('Weather report for ' + city + \
            ', ' + region + ' ' + country)
        self.weatherDialog.labelTemp.setText(tempString)
        self.weatherDialog.labelSunrise.setText(sunrise)
        self.weatherDialog.labelSunset.setText(sunset)
        self.weatherDialog.labelWindChill.setText(str(chill) + \
            '°' + tempUnit)
        self.weatherDialog.labelWindSpeed.setText(str(windSpeed) + ' ' + \
            speedUnit)
        self.weatherDialog.labelWindDirection.setText(directionTextual)
        self.weatherDialog.labelHumidity.setText(str(humidity) + '%')
        self.weatherDialog.labelVisibility.setText(str(visibility) + ' ' + \
            distanceUnit)
        self.weatherDialog.labelPressure.setText(str(pressure) + ' ' + \
            pressureUnit)
        self.weatherDialog.labelRising.setText(pressureTendancy)

        # Set the image
        self.weatherDialog.labelIcon.setPixmap(QPixmap('images/64/' + \
          iconFileName))

    # TODO - this should really be in another class
    def createWeatherIcon(self, iconFileName, temp):
        """Create the icon to display in the tray"""
        # Create a map of what image to use based on code
        # Start by creating a transparent image to paint on
        print(('Using' + iconFileName))
        icon = QPixmap(22, 22)
        icon.fill(Qt.transparent)

        # Create a painter to paint on to the icon and draw on the text
        painter = QPainter(icon)
        painter.setOpacity(0.5)

        # Draw text of temperature
        font = QFont('Times', 10, QFont.Black)
        painter.setFont(font)
        painter.setPen(QColor('red'))
        painter.drawPixmap(QPoint(0, 0), QPixmap(iconFileName))
        painter.setOpacity(1)
        painter.drawText(5, 15, temp)
        painter.end()

        # Return the icon
        return QIcon(icon)

    def setTrayIcon(self, icon):
        """Set the tray icon"""
        self.trayIcon.setIcon(icon)
        self.trayIcon.show()

    def quitApp(self):
        """Exit the application"""
        sys.exit(0)
示例#12
0
文件: run.py 项目: dmzkrsk/wol-tray
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, VENDOR, APP)

        self.setup = ConfigDialog(None, Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
        self.setup.setModal(True)
        centerOnScreen(self.setup)
        self.setup.wake.connect(self.wake)
        self.setup.serversChanged.connect(self.updateMenu)

        self.menuServers = []

        self.trayIcon = QSystemTrayIcon(QIcon("res/power.png"), self)
        self.trayIcon.activated.connect(self.activated)

        menu = QMenu()

        self.populateMenuFromSettings(menu)

        menu.addSeparator()

        self.setupAction = menu.addAction(QIcon('res/setup.png'), "Configure")
        self.setupAction.triggered.connect(self.setup.show)

        menu.addSeparator()

        exitAction = menu.addAction("Exit")
        exitAction.triggered.connect(self.close)

        self.trayIcon.setContextMenu(menu)

        self.trayIcon.setToolTip("Wake on LAN")

        self.trayIcon.show()

        servers = self.settings.beginReadArray("servers")
        self.settings.endArray()

        if not servers:
            self.setup.show()

    def populateMenuFromSettings(self, menu):
        """
        :type menu: QMenu
        """
        actions = menu.actions()
        before = actions[0] if actions else None

        title = QWidgetAction(menu)
        label = QLabel("Hosts")
        font = label.font()
        px = font.pointSize()
        font.setBold(True)
        font.setPointSize(px * 1.5)
        label.setFont(font)
        label.setMargin(4)
        label.setIndent(10)
        #        label.setStyleSheet("font-weight: bold; margin: 4px 2px; border-bottom: 2px solid black")
        title.setDefaultWidget(label)

        menu.insertAction(before, title)
        self.menuServers.append(title)

        servers = self.settings.beginReadArray("servers")
        for d in range(servers):
            self.settings.setArrayIndex(d)
            server = Server.fromSettings(self.settings)
            action = QAction(QIcon("res/server.png"), server.alias, menu)
            menu.insertAction(before, action)
            action.setData(server)
            action.triggered.connect(self.wakeFromMenu)
            self.menuServers.append(action)
        self.settings.endArray()

    def activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.setup()
        elif reason == QSystemTrayIcon.Trigger:
            menu = QMenu()
            self.populateMenuFromSettings(menu)
            menu.exec_(QCursor.pos())

    def updateMenu(self):
        menu = self.trayIcon.contextMenu()
        for action in self.menuServers:
            action.setData(None)
            menu.removeAction(action)

        self.populateMenuFromSettings(menu)

    def wakeFromMenu(self):
        action = self.sender()
        server = action.data().toPyObject()
        self.wake(server)

    def wake(self, server):
        if QMessageBox.Yes == QMessageBox.question(self, "Wake on LAN", "Wake %s?" % server.alias, QMessageBox.Yes|QMessageBox.No):
            magic = '\xFF' * 6
            bits = str(server.mac).split(':')
            machex = ''.join([struct.pack('B', (int(x, 16))) for x in bits])
            magic += machex * 16

            sock = socket(type=SOCK_DGRAM)
            if server.broadcast:
                sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
            sock.sendto(magic, ('<broadcast>', server.port))
            sock.close()

            self.trayIcon.showMessage("Wake on LAN", "Magic packet was sent to %s" % server.alias, msecs=3000)

    def close(self):
        QApplication.quit()
示例#13
0
        class GuiApplicationLinux(GuiApplicationBase):
            def __init__(self, executable, iconPath, parent=None):
                super(GuiApplicationLinux, self).__init__(iconPath)

                self.eventLoop = "qt"
                self.app = QApplication(sys.argv)  # this should be done before anything else
                self.executable = executable

                if QIcon.hasThemeIcon(iconPath):
                    icon = QIcon.fromTheme(iconPath)
                else:
                    icon = QIcon(iconPath)

                self.statusIcon = QSystemTrayIcon(icon, parent)
                self.menu = QMenu(parent)

                exitAction = self.menu.addAction("Exit")
                exitAction.triggered.connect(self.quit)

                self.statusIcon.setContextMenu(self.menu)

                def activate(reason):
                    if reason == QSystemTrayIcon.Trigger:
                        return self.launchExecutable()

                QObject.connect(self.statusIcon, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), activate)

                self.statusIcon.show()

            # A portable icon wrapper. Notify2 demands icon class to be compatible with GdkPixbuf so we
            # provide a compatibility layer
            class IconWrapper(object):
                def __init__(self, iconName):
                    if QIcon.hasThemeIcon(iconName):
                        icon = QIcon.fromTheme(iconName)
                    else:
                        icon = QIcon(iconName)
                    size = icon.availableSizes()[0]
                    self.image = icon.pixmap(size).toImage().convertToFormat(QImage.Format_ARGB32)
                    self.image = self.image.rgbSwapped()  # otherwise colors are weird :/

                def get_width(self):
                    return self.image.width()

                def get_height(self):
                    return self.image.height()

                def get_rowstride(self):
                    return self.image.bytesPerLine()

                def get_has_alpha(self):
                    return self.image.hasAlphaChannel()

                def get_bits_per_sample(self):
                    return self.image.depth() // self.get_n_channels()

                def get_n_channels(self):
                    if self.image.isGrayscale():
                        return 1
                    elif self.image.hasAlphaChannel():
                        return 4
                    else:
                        return 3

                def get_pixels(self):
                    return self.image.bits().asstring(self.image.numBytes())

            # end of wrapper class

            def getNotificationIcon(self):
                try:
                    return self.IconWrapper(self.iconPath)
                except:
                    logging.error("Failed to get notification icon")
                    return None

            def refreshToolTip(self, players):
                self.statusIcon.setToolTip(self.formTooltip(players))

            def launchExecutable(self, *args):
                try:
                    subprocess.Popen(self.executable, shell=True)
                except:
                    logging.error("Unable to run {0}".format(self.cmd))

            def run(self):
                sys.exit(self.app.exec_())

            def quit(self):
                self.timer.cancel()
                sys.exit(0)
示例#14
0
class Tray(QObject):
    activated = pyqtSignal()

    def __init__(self, parent, title, icon):
        QObject.__init__(self)

        # Setup contextual menu
        if kde:
            self.menu = KMenu(parent)
            self.tray = KStatusNotifierItem(parent)
            self.tray.setStatus(KStatusNotifierItem.Passive)
            self.tray.setCategory(KStatusNotifierItem.ApplicationStatus)
            self.tray.setAssociatedWidget(parent)
            self.tray.setStandardActionsEnabled(False)
            self.tray.activateRequested.connect(self._activateRequested)
        else:
            self.menu = QMenu()
            self.tray = QSystemTrayIcon()
            self.tray.activated.connect(self._activated)
        self.setIcon(icon)
        self.setTitle(title)
        if not kde:
            self.tray.show()
        self.tray.setContextMenu(self.menu)

    def setActive(self, active=True):
        if kde:
            self.tray.setStatus(KStatusNotifierItem.Active
                                if active else KStatusNotifierItem.Passive)

    def setTitle(self, title):
        if kde:
            self.tray.setTitle(title)
            self.tray.setToolTipTitle(title)
        else:
            self.tray.setToolTip(title)
        self.menu.setTitle(title)

    def setToolTipSubTitle(self, subtitle):
        if kde:
            self.tray.setToolTipSubTitle(subtitle)

    def setIcon(self, icon):
        if kde:
            self.tray.setIconByPixmap(icon)
            self.tray.setToolTipIconByPixmap(icon)
        else:
            self.tray.setIcon(icon)

    def showMessage(self, title, message, icon=None):
        if kde:
            self.tray.showMessage(title, message, "network-server")
        else:
            self.tray.showMessage(
                title, message,
                QSystemTrayIcon.Information if icon is None else icon)

    def _activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.activated.emit()

    def _activateRequested(self, active, pos):
        self.activated.emit()
    def __init__(self, parent=None):
        " Initialize QWidget inside MyMainWindow "
        super(MyMainWindow, self).__init__(parent)
        QWidget.__init__(self)
        self.statusBar().showMessage("               {}".format(__doc__))
        self.setStyleSheet("QStatusBar{color:grey;}")
        self.setWindowTitle(__doc__)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setFont(QFont("Ubuntu Light", 10))
        self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height())

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get("http_proxy", ""))
        QNetworkProxy.setApplicationProxy(
            QNetworkProxy(
                QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith("http") else QNetworkProxy.Socks5Proxy,
                proxy_url.host(),
                proxy_url.port(),
                proxy_url.userName(),
                proxy_url.password(),
            )
        ) if "http_proxy" in environ else None
        print((" INFO: Proxy Auto-Config as " + str(proxy_url)))

        # basic widgets layouts and set up
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.mainwidget.tabCloseRequested.connect(lambda: self.mainwidget.setTabPosition(randint(0, 3)))
        # if self.mainwidget.tabPosition() == 0
        # else self.mainwidget.setTabPosition(0))
        self.mainwidget.setStyleSheet("QTabBar{color:white;font-weight:bold;}")
        self.mainwidget.setTabBar(TabBar(self))
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabsClosable(True)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.setCentralWidget(self.mainwidget)
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        self.dock3 = QDockWidget()
        for a in (self.dock1, self.dock2, self.dock3):
            a.setWindowModality(Qt.NonModal)
            a.setWindowOpacity(0.9)
            a.setWindowTitle(__doc__ if a.windowTitle() == "" else a.windowTitle())
            a.setStyleSheet(" QDockWidget::title{text-align:center;}")
            self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"), "Double Click Me")

        # Paleta de colores para pintar transparente
        self.palette().setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(self.palette())
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

        # toolbar and basic actions
        self.toolbar = QToolBar(self)
        self.toolbar.setIconSize(QSize(24, 24))
        # spacer widget for left
        self.left_spacer = QWidget(self)
        self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        # spacer widget for right
        self.right_spacer = QWidget(self)
        self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        qaqq = QAction(QIcon.fromTheme("application-exit"), "Quit", self)
        qaqq.setShortcut("Ctrl+Q")
        qaqq.triggered.connect(exit)
        qamin = QAction(QIcon.fromTheme("go-down"), "Minimize", self)
        qamin.triggered.connect(lambda: self.showMinimized())
        qamax = QAction(QIcon.fromTheme("go-up"), "Maximize", self)
        qanor = QAction(QIcon.fromTheme("view-fullscreen"), "AutoCenter AutoResize", self)
        qanor.triggered.connect(self.center)
        qatim = QAction(QIcon.fromTheme("mail-signed-verified"), "View Date and Time", self)
        qatim.triggered.connect(self.timedate)
        qabug = QAction(QIcon.fromTheme("help-about"), "Report a Problem", self)
        qabug.triggered.connect(
            lambda: qabug.setDisabled(True)
            if not call("xdg-open mailto:" + "*****@*****.**".decode("rot13"), shell=True)
            else " ERROR "
        )
        qamax.triggered.connect(lambda: self.showMaximized())
        qaqt = QAction(QIcon.fromTheme("help-about"), "About Qt", self)
        qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self))
        qakde = QAction(QIcon.fromTheme("help-about"), "About KDE", self)
        if KDE:
            qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE)
        qaslf = QAction(QIcon.fromTheme("help-about"), "About Self", self)
        if KDE:
            qaslf.triggered.connect(KAboutApplicationDialog(aboutData, self).exec_)
        else:
            qaslf.triggered.connect(
                lambda: QMessageBox.about(
                    self.mainwidget,
                    __doc__,
                    "".join(
                        (
                            __doc__,
                            linesep,
                            "version ",
                            __version__,
                            ", (",
                            __license__,
                            "), by ",
                            __author__,
                            ", ( ",
                            __email__,
                            " )",
                            linesep,
                        )
                    ),
                )
            )
        qafnt = QAction(QIcon.fromTheme("tools-check-spelling"), "Set GUI Font", self)
        if KDE:
            font = QFont()
            qafnt.triggered.connect(
                lambda: self.setStyleSheet(
                    "".join(("*{font-family:", str(font.toString()), "}"))
                    if KFontDialog.getFont(font)[0] == QDialog.Accepted
                    else ""
                )
            )
        else:
            qafnt.triggered.connect(
                lambda: self.setStyleSheet("".join(("*{font-family:", str(QFontDialog.getFont()[0].toString()), "}")))
            )
        qasrc = QAction(QIcon.fromTheme("applications-development"), "View Source Code", self)
        qasrc.triggered.connect(lambda: call("xdg-open {}".format(__file__), 1))
        qakb = QAction(QIcon.fromTheme("input-keyboard"), "Keyboard Shortcuts", self)
        qakb.triggered.connect(
            lambda: QMessageBox.information(self.mainwidget, "Keyboard Shortcuts", " Ctrl+Q = Quit ")
        )
        qapic = QAction(QIcon.fromTheme("camera-photo"), "Take a Screenshot", self)
        qapic.triggered.connect(
            lambda: QPixmap.grabWindow(QApplication.desktop().winId()).save(
                QFileDialog.getSaveFileName(
                    self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ";;(*.png) PNG", "png"
                )
            )
        )
        qatb = QAction(QIcon.fromTheme("go-top"), "Toggle ToolBar", self)
        qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show())
        qati = QAction(QIcon.fromTheme("help-browser"), "Switch ToolBar Icon Size", self)
        qati.triggered.connect(
            lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4)
            if self.toolbar.iconSize().width() * 4 == 24
            else self.toolbar.setIconSize(self.toolbar.iconSize() / 4)
        )
        qasb = QAction(QIcon.fromTheme("zoom-in"), "Toggle Tabs Bar", self)
        qasb.triggered.connect(
            lambda: self.mainwidget.tabBar().hide()
            if self.mainwidget.tabBar().isVisible() is True
            else self.mainwidget.tabBar().show()
        )
        qadoc = QAction(QIcon.fromTheme("help-browser"), "On-line Docs", self)
        qadoc.triggered.connect(lambda: open_new_tab(__url__))
        qapy = QAction(QIcon.fromTheme("help-about"), "About Python", self)
        qapy.triggered.connect(lambda: open_new_tab("http://python.org/about"))
        qali = QAction(QIcon.fromTheme("help-browser"), "Read Licence", self)
        qali.triggered.connect(lambda: open_new_tab(__full_licence__))
        qacol = QAction(QIcon.fromTheme("preferences-system"), "Set GUI Colors", self)
        if KDE:
            color = QColor()
            qacol.triggered.connect(
                lambda: self.setStyleSheet("".join(("* { background-color: ", str(color.name()), "}")))
                if KColorDialog.getColor(color, self)
                else ""
            )
        else:
            qacol.triggered.connect(
                lambda: self.setStyleSheet(
                    "".join((" * { background-color: ", str(QColorDialog.getColor().name()), " } "))
                )
            )
        qatit = QAction(QIcon.fromTheme("preferences-system"), "Set the App Window Title", self)
        qatit.triggered.connect(self.seTitle)
        self.toolbar.addWidget(self.left_spacer)
        self.toolbar.addSeparator()
        for b in (
            qaqq,
            qamin,
            qanor,
            qamax,
            qasrc,
            qakb,
            qacol,
            qatim,
            qatb,
            qafnt,
            qati,
            qasb,
            qatit,
            qapic,
            qadoc,
            qali,
            qaslf,
            qaqt,
            qakde,
            qapy,
            qabug,
        ):
            self.toolbar.addAction(b)
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.right_spacer)
        # define the menu
        menu = self.menuBar()
        # File menu items
        menu.addMenu("&File").addActions((qaqq,))
        menu.addMenu("&Window").addActions((qamax, qanor, qamin))
        # Settings menu
        menu.addMenu("&Settings").addActions((qasrc, qacol, qafnt, qatim, qatb, qati, qasb, qapic))
        # Help menu items
        menu.addMenu("&Help").addActions((qadoc, qakb, qabug, qali, qaqt, qakde, qapy, qaslf))
        # Tray Icon
        tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self)
        tray.setToolTip(__doc__)
        traymenu = QMenu()
        traymenu.addActions((qamax, qanor, qamin, qaqq))
        tray.setContextMenu(traymenu)
        tray.show()

        def contextMenuRequested(point):
            " quick and dirty custom context menu "
            menu = QMenu()
            menu.addActions(
                (
                    qaqq,
                    qamin,
                    qanor,
                    qamax,
                    qasrc,
                    qakb,
                    qacol,
                    qafnt,
                    qati,
                    qasb,
                    qatb,
                    qatim,
                    qatit,
                    qapic,
                    qadoc,
                    qali,
                    qaslf,
                    qaqt,
                    qakde,
                    qapy,
                    qabug,
                )
            )
            menu.exec_(self.mapToGlobal(point))

        self.mainwidget.customContextMenuRequested.connect(contextMenuRequested)

        def must_be_checked(widget_list):
            " widget tuple passed as argument should be checked as ON "
            for each_widget in widget_list:
                try:
                    each_widget.setChecked(True)
                except:
                    pass

        def must_have_tooltip(widget_list):
            " widget tuple passed as argument should have tooltips "
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_autofillbackground(widget_list):
            " widget tuple passed as argument should have filled background "
            for each_widget in widget_list:
                try:
                    each_widget.setAutoFillBackground(True)
                except:
                    pass

        def must_glow(widget_list):
            " apply an glow effect to the widget "
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(
                                lambda: each_widget.graphicsEffect().setEnabled(True)
                                if each_widget.graphicsEffect().isEnabled() is False
                                else each_widget.graphicsEffect().setEnabled(False)
                            )
                        except:
                            each_widget.sliderPressed.connect(
                                lambda: each_widget.graphicsEffect().setEnabled(True)
                                if each_widget.graphicsEffect().isEnabled() is False
                                else each_widget.graphicsEffect().setEnabled(False)
                            )
                except:
                    pass

        #######################################################################

        self.group1 = QGroupBox()
        self.group1.setTitle(__doc__)
        self.frmt = QComboBox(self.group1)
        self.frmt.addItems(["blah ", "blah blah", "blah blah blah"])
        self.file1 = QLineEdit()
        self.file1.setPlaceholderText("/full/path/to/one_file.py")
        self.file1.setCompleter(self.completer)
        self.borig = QPushButton(QIcon.fromTheme("folder-open"), "Open")
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b style="color:white;">some comment'),
            self.file1,
            self.borig,
            QLabel('<b style="color:white;">Lorem Impsum'),
            self.frmt,
        ):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(__doc__)
        self.nwfl = QCheckBox("Be Awesome")
        self.smll = QCheckBox("Solve the Squaring of the Circle")
        self.lrgf = QCheckBox("Im just a QCheckBox")
        self.case = QCheckBox("Use Quantum Processing")
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (self.nwfl, self.smll, self.lrgf, self.case):
            vboxg2.addWidget(each_widget)

        group3 = QGroupBox()
        group3.setTitle(__doc__)
        self.plai = QCheckBox("May the Force be with You")
        self.nocr = QCheckBox("Im just a Place Holder")
        self.ridt = QCheckBox("Lorem Impsum")
        self.nocm = QCheckBox("Divide by Zero")
        vboxg3 = QVBoxLayout(group3)
        for each_widget in (self.plai, self.nocr, self.ridt, self.nocm):
            vboxg3.addWidget(each_widget)
        container = QWidget()
        hbox = QHBoxLayout(container)
        for each_widget in (self.group2, self.group1, group3):
            hbox.addWidget(each_widget)
        self.dock1.setWidget(container)

        # dock 2
        self.dock2.setWidget(QPlainTextEdit())

        # dock 3
        self.dock3.setWidget(QCalendarWidget())

        # configure some widget settings
        must_be_checked((self.nwfl, self.smll, self.lrgf, self.plai))
        must_have_tooltip((self.plai, self.nocr, self.ridt, self.nocm, self.nwfl, self.smll, self.lrgf, self.case))
        must_autofillbackground(
            (self.plai, self.nocr, self.ridt, self.nocm, self.nwfl, self.smll, self.lrgf, self.case)
        )
        must_glow((self.plai, self.nocr, self.ridt, self.nocm, self.nwfl))
示例#16
0
class Qt4SysTrayIcon:
    def __init__( self ):
        self.snapshots = snapshots.Snapshots()
        self.config = self.snapshots.config
        self.decode = None

        if len( sys.argv ) > 1:
            if not self.config.set_current_profile(sys.argv[1]):
                logger.warning("Failed to change Profile_ID %s"
                               %sys.argv[1], self)

        self.qapp = qt4tools.create_qapplication(self.config.APP_NAME)
        translator = qt4tools.get_translator()
        self.qapp.installTranslator(translator)
        self.qapp.setQuitOnLastWindowClosed(False)

        import icon
        self.icon = icon
        self.qapp.setWindowIcon(icon.BIT_LOGO)

        self.status_icon = QSystemTrayIcon(icon.BIT_LOGO)
        #self.status_icon.actionCollection().clear()
        self.contextMenu = QMenu()

        self.menuProfileName = self.contextMenu.addAction(_('Profile: "%s"') % self.config.get_profile_name())
        qt4tools.set_font_bold(self.menuProfileName)
        self.contextMenu.addSeparator()

        self.menuStatusMessage = self.contextMenu.addAction(_('Done'))
        self.menuProgress = self.contextMenu.addAction('')
        self.menuProgress.setVisible(False)
        self.contextMenu.addSeparator()

        self.btnDecode = self.contextMenu.addAction(icon.VIEW_SNAPSHOT_LOG, _('decode paths'))
        self.btnDecode.setCheckable(True)
        self.btnDecode.setVisible(self.config.get_snapshots_mode() == 'ssh_encfs')
        QObject.connect(self.btnDecode, SIGNAL('toggled(bool)'), self.onBtnDecode)

        self.openLog = self.contextMenu.addAction(icon.VIEW_LAST_LOG, _('View Last Log'))
        QObject.connect(self.openLog, SIGNAL('triggered()'), self.onOpenLog)
        self.startBIT = self.contextMenu.addAction(icon.BIT_LOGO, _('Start BackInTime'))
        QObject.connect(self.startBIT, SIGNAL('triggered()'), self.onStartBIT)
        self.status_icon.setContextMenu(self.contextMenu)

        self.pixmap = icon.BIT_LOGO.pixmap(24)
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)
        self.progressBar.setTextVisible(False)
        self.progressBar.resize(24, 6)
        self.progressBar.render(self.pixmap, sourceRegion = QRegion(0, -14, 24, 6), flags = QWidget.RenderFlags(QWidget.DrawChildren))

        self.first_error = self.config.is_notify_enabled()
        self.popup = None
        self.last_message = None

        self.timer = QTimer()
        QObject.connect( self.timer, SIGNAL('timeout()'), self.update_info )

        self.ppid = os.getppid()

    def prepare_exit( self ):
        self.timer.stop()

        if not self.status_icon is None:
            self.status_icon.hide()
            self.status_icon = None

        if not self.popup is None:
            self.popup.deleteLater()
            self.popup = None

        self.qapp.processEvents()

    def run( self ):
        self.status_icon.show()
        self.timer.start( 500 )

        logger.info("[qt4systrayicon] begin loop", self)

        self.qapp.exec_()

        logger.info("[qt4systrayicon] end loop", self)

        self.prepare_exit()

    def update_info( self ):
        if not tools.is_process_alive( self.ppid ):
            self.prepare_exit()
            self.qapp.exit(0)
            return

        message = self.snapshots.get_take_snapshot_message()
        if message is None and self.last_message is None:
            message = ( 0, _('Working...') )

        if not message is None:
            if message != self.last_message:
                self.last_message = message
                if self.decode:
                    message = (message[0], self.decode.log(message[1]))
                self.menuStatusMessage.setText('\n'.join(tools.wrap_line(message[1],\
                                                                         size = 80,\
                                                                         delimiters = '',\
                                                                         new_line_indicator = '') \
                                                                        ))
                self.status_icon.setToolTip(message[1])

        pg = progress.ProgressFile(self.config)
        if pg.isFileReadable():
            pg.load()
            percent = pg.get_int_value('percent')
            if percent != self.progressBar.value():
                self.progressBar.setValue(percent)
                self.progressBar.render(self.pixmap, sourceRegion = QRegion(0, -14, 24, 6), flags = QWidget.RenderFlags(QWidget.DrawChildren))
                self.status_icon.setIcon(QIcon(self.pixmap))

            self.menuProgress.setText(' | '.join(self.getMenuProgress(pg)) )
            self.menuProgress.setVisible(True)
        else:
            self.status_icon.setIcon(self.icon.BIT_LOGO)
            self.menuProgress.setVisible(False)


    def getMenuProgress(self, pg):
        d = (('sent',   _('Sent:')), \
             ('speed',  _('Speed:')),\
             ('eta',    _('ETA:')) )
        for key, txt in d:
            value = pg.get_str_value(key, '')
            if not value:
                continue
            yield txt + ' ' + value

    def onStartBIT(self):
        profileID = self.config.get_current_profile()
        cmd = ['backintime-qt4',]
        if not profileID == '1':
            cmd += ['--profile-id', profileID]
        proc = subprocess.Popen(cmd)

    def onOpenLog(self):
        dlg = logviewdialog.LogViewDialog(self, systray = True)
        dlg.decode = self.decode
        dlg.cb_decode.setChecked(self.btnDecode.isChecked())
        dlg.exec_()

    def onBtnDecode(self, checked):
        if checked:
            self.decode = encfstools.Decode(self.config)
            self.last_message = None
            self.update_info()
        else:
            self.decode = None
    def __init__(self, AUTO):
        ' Initialize QWidget inside MyMainWindow '
        super(MyMainWindow, self).__init__()
        QWidget.__init__(self)
        self.auto = AUTO
        self.statusBar().showMessage('               {}'.format(__doc__))
        self.setStyleSheet('QStatusBar{color:grey;}')
        self.setWindowTitle(__doc__)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setFont(QFont('Ubuntu Light', 10))
        self.setMaximumSize(QDesktopWidget().screenGeometry().width(),
                            QDesktopWidget().screenGeometry().height())

        self.base = path.abspath(path.join(getcwd(), str(datetime.now().year)))

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # process
        self.process1 = None
        self.process2 = None
        self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw'
        self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}'
        self.process3 = QProcess(self)
        #self.process3.finished.connect(self.on_process3_finished)
        #self.process3.error.connect(self.on_process3_error)

        self.cmd3 = ('nice -n 20 ' +
          'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"')
        self.actual_file = ''

        # re starting timers, one stops, one starts
        self.timerFirst = QTimer(self)
        self.timerFirst.timeout.connect(self.end)
        self.timerSecond = QTimer(self)
        self.timerSecond.timeout.connect(self.run)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get('http_proxy', ''))
        QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy
            if str(proxy_url.scheme()).startswith('http')
            else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(),
                 proxy_url.userName(), proxy_url.password())) \
            if 'http_proxy' in environ else None
        print((' INFO: Proxy Auto-Config as ' + str(proxy_url)))

        # basic widgets layouts and set up
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}')
        self.mainwidget.setTabBar(TabBar(self))
        self.mainwidget.setTabsClosable(False)
        self.setCentralWidget(self.mainwidget)
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        self.dock3 = QDockWidget()
        self.dock4 = QDockWidget()
        self.dock5 = QDockWidget()
        for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5):
            a.setWindowModality(Qt.NonModal)
            # a.setWindowOpacity(0.9)
            a.setWindowTitle(__doc__
                             if a.windowTitle() == '' else a.windowTitle())
            a.setStyleSheet('QDockWidget::title{text-align:center;}')
            self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"),
                                   'Double Click Me')

        # Paleta de colores para pintar transparente
        self.palette().setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(self.palette())
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

        # toolbar and basic actions
        self.toolbar = QToolBar(self)
        self.toolbar.setIconSize(QSize(24, 24))
        # spacer widget for left
        self.left_spacer = QWidget(self)
        self.left_spacer.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        # spacer widget for right
        self.right_spacer = QWidget(self)
        self.right_spacer.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
        qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self)
        qaqq.setShortcut('Ctrl+Q')
        qaqq.triggered.connect(exit)
        qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self)
        qamin.triggered.connect(lambda: self.showMinimized())
        qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self)
        qanor = QAction(QIcon.fromTheme("view-fullscreen"),
                        'AutoCenter AutoResize', self)
        qanor.triggered.connect(self.center)
        qatim = QAction(QIcon.fromTheme("mail-signed-verified"),
                        'View Date and Time', self)
        qatim.triggered.connect(self.timedate)
        qabug = QAction(QIcon.fromTheme("help-about"), 'Report a Problem', self)
        qabug.triggered.connect(lambda: qabug.setDisabled(True) if not call(
            'xdg-open mailto:' + '*****@*****.**'.decode('rot13'),
            shell=True) else ' ERROR ')
        qamax.triggered.connect(lambda: self.showMaximized())
        qaqt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self)
        qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self))
        qakde = QAction(QIcon.fromTheme("help-about"), 'About KDE', self)
        if KDE:
            qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE)
        qaslf = QAction(QIcon.fromTheme("help-about"), 'About Self', self)
        if KDE:
            qaslf.triggered.connect(
                                KAboutApplicationDialog(aboutData, self).exec_)
        else:
            qaslf.triggered.connect(lambda: QMessageBox.about(self.mainwidget,
            __doc__, ''.join((__doc__, linesep, 'version ', __version__, ', (',
            __license__, '), by ', __author__, ', ( ', __email__, ' )', linesep
            ))))
        qafnt = QAction(QIcon.fromTheme("tools-check-spelling"),
                        'Set GUI Font', self)
        if KDE:
            font = QFont()
            qafnt.triggered.connect(lambda:
            self.setStyleSheet(''.join((
                '*{font-family:', str(font.toString()), '}'))
                if KFontDialog.getFont(font)[0] == QDialog.Accepted else ''))
        else:
            qafnt.triggered.connect(lambda:
                self.setStyleSheet(''.join(('*{font-family:',
                            str(QFontDialog.getFont()[0].toString()), '}'))))
        qasrc = QAction(QIcon.fromTheme("applications-development"),
                        'View Source Code', self)
        qasrc.triggered.connect(lambda:
                            call('xdg-open {}'.format(__file__), shell=True))
        qakb = QAction(QIcon.fromTheme("input-keyboard"),
                       'Keyboard Shortcuts', self)
        qakb.triggered.connect(lambda: QMessageBox.information(self.mainwidget,
                               'Keyboard Shortcuts', ' Ctrl+Q = Quit '))
        qapic = QAction(QIcon.fromTheme("camera-photo"),
                        'Take a Screenshot', self)
        qapic.triggered.connect(lambda: QPixmap.grabWindow(
            QApplication.desktop().winId()).save(QFileDialog.getSaveFileName(
            self.mainwidget, " Save Screenshot As ...", path.expanduser("~"),
            ';;(*.png) PNG', 'png')))
        qatb = QAction(QIcon.fromTheme("go-top"), 'Toggle ToolBar', self)
        qatb.triggered.connect(lambda: self.toolbar.hide()
                if self.toolbar.isVisible() is True else self.toolbar.show())
        qati = QAction(QIcon.fromTheme("zoom-in"),
                       'Switch ToolBar Icon Size', self)
        qati.triggered.connect(lambda:
            self.toolbar.setIconSize(self.toolbar.iconSize() * 4)
            if self.toolbar.iconSize().width() * 4 == 24
            else self.toolbar.setIconSize(self.toolbar.iconSize() / 4))
        qasb = QAction(QIcon.fromTheme("preferences-other"),
                       'Toggle Tabs Bar', self)
        qasb.triggered.connect(lambda: self.mainwidget.tabBar().hide()
                               if self.mainwidget.tabBar().isVisible() is True
                               else self.mainwidget.tabBar().show())
        qadoc = QAction(QIcon.fromTheme("help-browser"), 'On-line Docs', self)
        qadoc.triggered.connect(lambda: open_new_tab(str(__url__).strip()))
        qapy = QAction(QIcon.fromTheme("help-about"), 'About Python', self)
        qapy.triggered.connect(lambda: open_new_tab('http://python.org/about'))
        qali = QAction(QIcon.fromTheme("help-browser"), 'Read Licence', self)
        qali.triggered.connect(lambda: open_new_tab(__full_licence__))
        qacol = QAction(QIcon.fromTheme("preferences-system"), 'Set GUI Colors',
                        self)
        if KDE:
            color = QColor()
            qacol.triggered.connect(lambda:
                self.setStyleSheet(''.join(('* { background-color: ',
                                            str(color.name()), '}')))
                if KColorDialog.getColor(color, self) else '')
        else:
            qacol.triggered.connect(lambda: self.setStyleSheet(''.join((
                ' * { background-color: ', str(QColorDialog.getColor().name()),
                ' } '))))
        qatit = QAction(QIcon.fromTheme("preferences-system"),
                        'Set the App Window Title', self)
        qatit.triggered.connect(self.seTitle)
        self.toolbar.addWidget(self.left_spacer)
        self.toolbar.addSeparator()
        self.toolbar.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
            qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf,
            qaqt, qakde, qapy, qabug))
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.right_spacer)
        # define the menu
        menu = self.menuBar()
        # File menu items
        menu.addMenu('&File').addActions((qaqq, ))
        menu.addMenu('&Window').addActions((qamax, qanor, qamin))
        # Settings menu
        menu.addMenu('&Settings').addActions((qasrc, qacol, qafnt, qatim,
                                              qatb, qati, qasb, qapic))
        # Help menu items
        menu.addMenu('&Help').addActions((qadoc, qakb, qabug, qali,
                                          qaqt, qakde, qapy, qaslf))
        # Tray Icon
        tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self)
        tray.setToolTip(__doc__)
        traymenu = QMenu()
        traymenu.addActions((qamax, qanor, qamin, qaqq))
        tray.setContextMenu(traymenu)
        tray.show()

        def contextMenuRequested(point):
            ' quick and dirty custom context menu '
            menu = QMenu()
            menu.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
                qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali,
                qaslf, qaqt, qakde, qapy, qabug))
            menu.exec_(self.mapToGlobal(point))
        self.mainwidget.customContextMenuRequested.connect(contextMenuRequested)

        def must_be_checked(widget_list):
            ' widget tuple passed as argument should be checked as ON '
            for each_widget in widget_list:
                try:
                    each_widget.setChecked(True)
                except:
                    pass

        def must_have_tooltip(widget_list):
            ' widget tuple passed as argument should have tooltips '
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_autofillbackground(widget_list):
            ' widget tuple passed as argument should have filled background '
            for each_widget in widget_list:
                try:
                    each_widget.setAutoFillBackground(True)
                except:
                    pass

        def must_glow(widget_list):
            ' apply an glow effect to the widget '
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                        except:
                            each_widget.sliderPressed.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                except:
                    pass

        #######################################################################

        # dock 1
        QLabel('<h1 style="color:white;"> Record !</h1>', self.dock1).resize(
               self.dock3.size().width() / 4, 25)
        self.group1 = QGroupBox()
        self.group1.setTitle(__doc__)

        self.spec = QPushButton(self)
        self.spec.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.spec.setMinimumSize(self.spec.size().width(), 250)
        self.spec.setFlat(True)
        self.spec.clicked.connect(self.spectro)

        self.clock = QLCDNumber()
        self.clock.setSegmentStyle(QLCDNumber.Flat)
        self.clock.setMinimumSize(self.clock.size().width(), 50)
        self.clock.setNumDigits(25)
        self.timer1 = QTimer(self)
        self.timer1.timeout.connect(lambda: self.clock.display(
            datetime.now().strftime("%d-%m-%Y %H:%M:%S %p")))
        self.timer1.start(1000)
        self.clock.setToolTip(datetime.now().strftime("%c %x"))
        self.clock.setCursor(QCursor(Qt.CrossCursor))

        self.diskBar = QProgressBar()
        self.diskBar.setMinimum(0)
        self.diskBar.setMaximum(statvfs(HOME).f_blocks *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setValue(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setToolTip(str(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024) + ' Gigabytes free')

        self.feedback = QPlainTextEdit(''.join(('<center><h3>', __doc__,
            ', version', __version__, __license__, ' <br> by ', __author__,
            ' <i>(Dev)</i>, Radio Comunitaria FM Reconquista <i>(Q.A.)</i><br>',
            'FMReconquista.org.ar & GitHub.com/JuanCarlosPaco/Cinta-Testigo')))

        self.rec = QPushButton(QIcon.fromTheme("media-record"), 'Record')
        self.rec.setMinimumSize(self.rec.size().width(), 50)
        self.rec.clicked.connect(self.go)  # self.run

        self.stop = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.stop.clicked.connect(self.end)

        self.kill = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.kill.clicked.connect(self.killer)

        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b style="color:white;"> Spectro'), self.spec,
            QLabel('<b style="color:white;"> Time '), self.clock,
            QLabel('<b style="color:white;"> Disk '), self.diskBar,
            QLabel('<b style="color:white;"> STDOUT + STDIN '), self.feedback,
            QLabel('<b style="color:white;"> Record '), self.rec, self.stop,
            self.kill):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(__doc__)

        self.slider = QSlider(self)
        self.slid_l = QLabel(self.slider)
        self.slider.setCursor(QCursor(Qt.OpenHandCursor))
        self.slider.sliderPressed.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.slider.sliderReleased.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.OpenHandCursor)))
        self.slider.valueChanged.connect(lambda:
                            self.slider.setToolTip(str(self.slider.value())))
        self.slider.valueChanged.connect(lambda: self.slid_l.setText(
                    '<h2 style="color:white;">{}'.format(self.slider.value())))
        self.slider.setMinimum(10)
        self.slider.setMaximum(99)
        self.slider.setValue(30)
        self.slider.setOrientation(Qt.Vertical)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setTickInterval(2)
        self.slider.setSingleStep(10)
        self.slider.setPageStep(10)

        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('<b style="color:white;">MINUTES of recording'), self.slider,
            QLabel('<b style="color:white;"> Default: 30 Min')):
            vboxg2.addWidget(each_widget)

        group3 = QGroupBox()
        group3.setTitle(__doc__)
        try:
            self.label2 = QLabel(getoutput('sox --version', shell=True))
            self.label4 = QLabel(getoutput('arecord --version', shell=1)[:25])
            self.label6 = QLabel(str(getoutput('oggenc --version', shell=True)))
        except:
            print(''' ERROR: No SOX, OGGenc avaliable !
                  ( sudo apt-get install vorbis-tools sox alsa-utils ) ''')
            exit()

        self.button5 = QPushButton(QIcon.fromTheme("audio-x-generic"),
                                   'OGG --> ZIP')
        self.button5.clicked.connect(lambda: make_archive(
            str(QFileDialog.getSaveFileName(self, "Save OGG to ZIP file As...",
            getcwd(), ';;(*.zip)', 'zip')).replace('.zip', ''), "zip",
            path.abspath(path.join(getcwd(), str(datetime.now().year)))))

        self.button1 = QPushButton(QIcon.fromTheme("folder-open"), 'Files')
        self.button1.clicked.connect(lambda:
                                     call('xdg-open ' + getcwd(), shell=True))

        self.button0 = QPushButton(
            QIcon.fromTheme("preferences-desktop-screensaver"), 'LCD OFF')
        self.button0.clicked.connect(lambda:
            call('sleep 3 ; xset dpms force off', shell=True))

        vboxg3 = QVBoxLayout(group3)
        for each_widget in (
            QLabel('<b style="color:white;"> OGG Output Codec '), self.label6,
            QLabel('<b style="color:white;"> Raw Record Backend '), self.label4,
            QLabel('<b style="color:white;"> Helper Libs '), self.label2,
            QLabel('<b style="color:white;"> OGG ZIP '), self.button5,
            QLabel('<b style="color:white;"> Files '), self.button1,
            QLabel('<b style="color:white;"> LCD '), self.button0):
            vboxg3.addWidget(each_widget)
        container = QWidget()
        hbox = QHBoxLayout(container)
        for each_widget in (self.group2, self.group1, group3):
            hbox.addWidget(each_widget)
        self.dock1.setWidget(container)

        # dock 2
        QLabel('<h1 style="color:white;"> Hardware !</h1>', self.dock2).resize(
               self.dock2.size().width() / 4, 25)
        try:
            audioDriverStr = {Solid.AudioInterface.Alsa: "ALSA",
                Solid.AudioInterface.OpenSoundSystem: "Open Sound",
                Solid.AudioInterface.UnknownAudioDriver: "Unknown?"}
            audioInterfaceTypeStr = {
                Solid.AudioInterface.AudioControl: "Control",
                Solid.AudioInterface.UnknownAudioInterfaceType: "Unknown?",
                Solid.AudioInterface.AudioInput: "In",
                Solid.AudioInterface.AudioOutput: "Out"}
            soundcardTypeStr = {
                Solid.AudioInterface.InternalSoundcard: "Internal",
                Solid.AudioInterface.UsbSoundcard: "USB3",
                Solid.AudioInterface.FirewireSoundcard: "FireWire",
                Solid.AudioInterface.Headset: "Headsets",
                Solid.AudioInterface.Modem: "Modem"}
            display = QTreeWidget()
            display.setAlternatingRowColors(True)
            display.setHeaderLabels(["Items", "ID", "Drivers", "I / O", "Type"])
            display.setColumnWidth(0, 350)
            display.setColumnWidth(1, 350)
            display.setColumnWidth(3, 75)
            # retrieve a list of Solid.Device for this machine
            deviceList = Solid.Device.allDevices()
            # filter the list of all devices and display matching results
            # note that we never create a Solid.AudioInterface object, but
            # receive one from the 'asDeviceInterface' call
            for device in deviceList:
                if device.isDeviceInterface(
                                         Solid.DeviceInterface.AudioInterface):
                    audio = device.asDeviceInterface(
                            Solid.DeviceInterface.AudioInterface)
                    devtype = audio.deviceType()
                    devstr = []
                    for key in audioInterfaceTypeStr:
                        flag = key & devtype
                        if flag:
                            devstr.append(audioInterfaceTypeStr[key])
                    QTreeWidgetItem(display, [device.product(), audio.name(),
                        audioDriverStr[audio.driver()], "/".join(devstr),
                        soundcardTypeStr[audio.soundcardType()]])
            self.dock2.setWidget(display)
        except:
            self.dock2.setWidget(QLabel(""" <center style='color:white;'>
            <h1>:(<br>ERROR: Please, install PyKDE !</h1><br>
            <br><i> (Sorry, can not use non-Qt Libs). Thanks </i><center>"""))

        ## dock 3
        QLabel('<h1 style="color:white;"> Previews !</h1>', self.dock3).resize(
               self.dock3.size().width() / 4, 25)
        self.fileView = QColumnView()
        self.fileView.updatePreviewWidget.connect(self.play)
        self.fileView.setToolTip(' Browse and Preview Files ')
        self.media = None
        self.model = QDirModel()
        self.fileView.setModel(self.model)
        self.dock3.setWidget(self.fileView)

        # dock4
        QLabel('<h1 style="color:white;"> Setup !</h1>', self.dock4).resize(
               self.dock4.size().width() / 4, 25)
        self.group4 = QGroupBox()
        self.group4.setTitle(__doc__)

        self.combo0 = QComboBox()
        self.combo0.addItems(['S16_LE', 'S32_LE', 'S16_BE', 'U16_LE', 'U16_BE',
          'S24_LE', 'S24_BE', 'U24_LE', 'U24_BE', 'S32_BE', 'U32_LE', 'U32_BE'])

        self.combo1 = QComboBox()
        self.combo1.addItems(['1', '-1', '0', '2', '3', '4',
                              '5', '6', '7', '8', '9', '10'])

        self.combo2 = QComboBox()
        self.combo2.addItems(['128', '256', '512', '1024', '64', '32', '16'])

        self.combo3 = QComboBox(self)
        self.combo3.addItems(['MONO', 'STEREO', 'Surround'])

        self.combo4 = QComboBox()
        self.combo4.addItems(['44100', '96000', '48000', '32000',
                              '22050', '16000', '11025', '8000'])

        self.combo5 = QComboBox(self)
        self.combo5.addItems(['20', '19', '18', '17', '16', '15', '14', '13',
            '12', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0'])

        self.nepochoose = QCheckBox('Auto-Tag Files using Nepomuk Semantic')

        self.chckbx0 = QCheckBox('Disable Software based Volume Control')

        self.chckbx1 = QCheckBox('Output Sound Stereo-to-Mono Downmix')

        self.chckbx2 = QCheckBox('Add Date and Time MetaData to Sound files')

        self.chckbx3 = QCheckBox('Add Yourself as the Author Artist of Sound')

        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (
            QLabel('<b style="color:white;"> Sound OGG Quality'), self.combo1,
            QLabel('<b style="color:white;"> Sound Record Format'), self.combo0,
            QLabel('<b style="color:white;"> Sound KBps '), self.combo2,
            QLabel('<b style="color:white;"> Sound Channels '), self.combo3,
            QLabel('<b style="color:white;"> Sound Sample Rate '), self.combo4,
            QLabel('<b style="color:white;"> Sound Volume'), self.chckbx0,
            QLabel('<b style="color:white;"> Sound Mix'), self.chckbx1,
            QLabel('<b style="color:white;"> Sound Meta'), self.chckbx2,
            QLabel('<b style="color:white;"> Sound Authorship'), self.chckbx3,
            QLabel('<b style="color:white;"> CPUs Priority'), self.combo5,
            QLabel('<b style="color:white;">Nepomuk Semantic User Experience'),
            self.nepochoose):
            vboxg4.addWidget(each_widget)
        self.dock4.setWidget(self.group4)

        # dock 5
        QLabel('<h1 style="color:white;"> Voice Changer ! </h1>', self.dock5
               ).resize(self.dock5.size().width() / 3, 25)
        self.group5 = QGroupBox()
        self.group5.setTitle(__doc__)

        self.dial = QDial()
        self.dial.setCursor(QCursor(Qt.OpenHandCursor))
        self.di_l = QLabel(self.dial)
        self.di_l.resize(self.dial.size() / 8)
        self.dial.sliderPressed.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.dial.sliderReleased.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.OpenHandCursor)))
        self.dial.valueChanged.connect(lambda:
                            self.dial.setToolTip(str(self.dial.value())))
        self.dial.valueChanged.connect(lambda: self.di_l.setText(
                    '<h1 style="color:white;">{}'.format(self.dial.value())))
        self.dial.setValue(0)
        self.dial.setMinimum(-999)
        self.dial.setMaximum(999)
        self.dial.setSingleStep(100)
        self.dial.setPageStep(100)
        self.dial.setWrapping(False)
        self.dial.setNotchesVisible(True)

        self.defo = QPushButton(QIcon.fromTheme("media-playback-start"), 'Run')
        self.defo.setMinimumSize(self.defo.size().width(), 50)
        self.defo.clicked.connect(lambda: self.process3.start(
            'play -q -V0 "|rec -q -V0 -n -d -R riaa pitch {} "'
            .format(self.dial.value()) if int(self.dial.value()) != 0 else
            'play -q -V0 "|rec -q -V0 --multi-threaded -n -d -R bend {} "'
            .format(' 3,2500,3 3,-2500,3 ' * 999)))

        self.qq = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.qq.clicked.connect(self.process3.kill)

        self.die = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.die.clicked.connect(lambda: call('killall rec', shell=True))

        vboxg5 = QVBoxLayout(self.group5)
        for each_widget in (self.dial, self.defo, self.qq, self.die):
            vboxg5.addWidget(each_widget)
        self.dock5.setWidget(self.group5)

        # configure some widget settings
        must_be_checked((self.nepochoose, self.chckbx1,
                         self.chckbx2, self.chckbx3))
        must_have_tooltip((self.label2, self.label4, self.label6, self.combo0,
            self.nepochoose, self.combo1, self.combo2, self.combo3, self.combo4,
            self.combo5, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3,
            self.rec, self.stop, self.defo, self.qq, self.die, self.kill,
            self.button0, self.button1, self.button5))
        must_autofillbackground((self.clock, self.label2, self.label4,
            self.label6, self.nepochoose, self.chckbx0, self.chckbx1,
            self.chckbx2, self.chckbx3))
        must_glow((self.rec, self.dial, self.combo1))
        self.nepomuk_get('testigo')
        if self.auto is True:
            self.go()
示例#18
0
class TrayController():
    """Display and control context menu."""

    setings_win = None

    def __init__(self):
        """Create TrayController."""
        self._tray_ico = QSystemTrayIcon()

    def set_menu(self, quit_callable, app_icon):
        """Show tray icon and sets its context menu items.

        :param quit_callable: function to call when user choose Exit menu item
        :type quit_callable: function
        :param app_icon: QIcon object - tray icon image
        :type app_icon: QIcon
        """
        tray_menu = QMenu()

        self._delay_menu = tray_menu.addAction(
            QIcon(
                os.path.join(PROGRAMM_RESOURCE_PATH, 'k-timer-icon.png')
            ),
            QtCore.QCoreApplication.translate('TrayController', 'Delay')
        )
        delay_sub_menu = QMenu()
        delay_sub_menu.addAction(
            QtCore.QCoreApplication.translate('TrayController', '15 minutes'),
            self.action_delay15
        )
        delay_sub_menu.addAction(
            QtCore.QCoreApplication.translate('TrayController', '30 minutes'),
            self.action_delay30
        )
        delay_sub_menu.addAction(
            QtCore.QCoreApplication.translate('TrayController', '1 hour'),
            self.action_delay60
        )
        delay_sub_menu.addAction(
            QtCore.QCoreApplication.translate('TrayController', '2 hours'),
            self.action_delay120
        )
        self._delay_menu.setMenu(delay_sub_menu)

        self._resume_menu = tray_menu.addAction(
            QIcon(
                os.path.join(PROGRAMM_RESOURCE_PATH,
                             'App-Quick-restart-icon.png')
            ),
            QtCore.QCoreApplication.translate('TrayController', 'Resume'),
            self.action_resume
        )
        self._resume_menu.setVisible(False)

        tray_menu.addAction(
            QIcon(
                os.path.join(PROGRAMM_RESOURCE_PATH, 'Settings-icon.png')
            ),
            QtCore.QCoreApplication.translate('TrayController', 'Settings'),
            self.show_settings
        )
        tray_menu.addSeparator()
        tray_menu.addAction(
            QIcon(
                os.path.join(PROGRAMM_RESOURCE_PATH, 'delete-icon.png')
            ),
            QtCore.QCoreApplication.translate('TrayController', 'Exit'),
            quit_callable
        )

        self._tray_ico.setContextMenu(tray_menu)
        self._tray_ico.setToolTip(PROGRAM_NAME)
        self._tray_ico.setIcon(app_icon)
        self._tray_ico.show()
        self.setings_win = SettingsManager(self, app_icon)

    def show_message(self, message):
        """Show message near tray icon.

        (alternative to show message is via module
        from PyQt4.QtGui import QMessageBox)

        :param message: message string
        :type message: str
        """
        self._tray_ico.showMessage(
            PROGRAM_NAME, message,
            msecs=5000
        )

    # Functions - menu click actions
    def toggle_delay_menu(self):
        """Toggle some context menu items.

        (depending program delay is on or off)
        """
        delay_on = self.setings_win.main_timer.delay_on
        self._resume_menu.setVisible(delay_on)
        self._delay_menu.setVisible(not delay_on)
        self.setings_win.ui.notActiveLb.setText(
            QtCore.QCoreApplication.translate('TrayController', 'Delay time')
            if delay_on else
            QtCore.QCoreApplication.translate(
                'TrayController', 'Time not active'
            )
        )

    def action_delay15(self):
        """User choose to delay program on 15 minutes."""
        self.setings_win.main_timer.set_work_delay(15)

    def action_delay30(self):
        """User choose to delay program on 30 minutes."""
        self.setings_win.main_timer.set_work_delay(30)

    def action_delay60(self):
        """User choose to delay program on 1 hour."""
        self.setings_win.main_timer.set_work_delay(60)

    def action_delay120(self):
        """User choose to delay program on 2 hours."""
        self.setings_win.main_timer.set_work_delay(120)

    def action_resume(self):
        """User cancel delay."""
        self.setings_win.main_timer.delay_on = False
        self.toggle_delay_menu()

    def show_settings(self):
        """Show settings window."""
        self.setings_win.show()
        class GuiApplicationLinux(GuiApplicationBase):
            def __init__(self, executable, iconPath, parent=None):
                super(GuiApplicationLinux, self).__init__(iconPath)

                self.eventLoop = 'qt'
                self.app = QApplication(
                    sys.argv)  # this should be done before anything else
                self.executable = executable

                if QIcon.hasThemeIcon(iconPath):
                    icon = QIcon.fromTheme(iconPath)
                else:
                    icon = QIcon(iconPath)

                self.statusIcon = QSystemTrayIcon(icon, parent)
                self.menu = QMenu(parent)

                exitAction = self.menu.addAction("Exit")
                exitAction.triggered.connect(self.quit)

                self.statusIcon.setContextMenu(self.menu)

                def activate(reason):
                    if reason == QSystemTrayIcon.Trigger:
                        return self.launchExecutable()

                QObject.connect(
                    self.statusIcon,
                    SIGNAL("activated(QSystemTrayIcon::ActivationReason)"),
                    activate)

                self.statusIcon.show()

            # A portable icon wrapper. Notify2 demands icon class to be compatible with GdkPixbuf so we
            # provide a compatibility layer
            class IconWrapper(object):
                def __init__(self, iconName):
                    if QIcon.hasThemeIcon(iconName):
                        icon = QIcon.fromTheme(iconName)
                    else:
                        icon = QIcon(iconName)
                    size = icon.availableSizes()[0]
                    self.image = icon.pixmap(size).toImage().convertToFormat(
                        QImage.Format_ARGB32)
                    self.image = self.image.rgbSwapped(
                    )  # otherwise colors are weird :/

                def get_width(self):
                    return self.image.width()

                def get_height(self):
                    return self.image.height()

                def get_rowstride(self):
                    return self.image.bytesPerLine()

                def get_has_alpha(self):
                    return self.image.hasAlphaChannel()

                def get_bits_per_sample(self):
                    return self.image.depth() // self.get_n_channels()

                def get_n_channels(self):
                    if self.image.isGrayscale():
                        return 1
                    elif self.image.hasAlphaChannel():
                        return 4
                    else:
                        return 3

                def get_pixels(self):
                    return self.image.bits().asstring(self.image.numBytes())

            # end of wrapper class

            def getNotificationIcon(self):
                try:
                    return self.IconWrapper(self.iconPath)
                except:
                    logging.error("Failed to get notification icon")
                    return None

            def refreshToolTip(self, players):
                self.statusIcon.setToolTip(self.formTooltip(players))

            def launchExecutable(self, *args):
                try:
                    subprocess.Popen(self.executable, shell=True)
                except:
                    logging.error("Unable to run {0}".format(self.cmd))

            def run(self):
                sys.exit(self.app.exec_())

            def quit(self):
                self.timer.cancel()
                sys.exit(0)
示例#20
0
class SingleApplication(QApplication):
    def __init__(self, *args):
        QApplication.__init__(self, *args)
        self._memory = QSharedMemory(self)
        self._memory.setKey("d2mp")
        if self._memory.attach():
            self._running = True
        else:
            self._running = False
            if not self._memory.create(1):
                raise RuntimeError(self._memory.errorString().toLocal8Bit().data())

    def is_running(self):
        return self._running
    
    def exec_(self):
        self._create_tray_icon()
        self._create_mod_manager()
        self._start_file_watcher()
        self._create_socket()
        Settings()
        
        return super(SingleApplication, self).exec_()
    def _create_mod_manager(self):
        self.manager = ModManager()
        self.manager.mod_game_info()
        self.manager.signals.message.connect(self.show_message_from_mod_manager)
        self.manager.signals.error.connect(self.show_error_from_mod_manager)
    
    def _create_socket(self):    
        self.socket = ConnectionManager()
        
        self.manager.signals.contact_server.connect(self.socket.send)
        
        self.socket.message.connect(self.show_message_from_socket)
        self.socket.error.connect(self.show_error_from_socket)
        
        
    @property
    def _watcher_file_name(self):
        return "d2mp.pid"
    
    def _start_file_watcher(self):
        self.watcher = QFileSystemWatcher()
        self.watcher_file_path =  join(abspath("."), self._watcher_file_name)
        log.DEBUG("creating watcher file: %s" %(self.watcher_file_path))
        write_to_file(self.watcher_file_path, "Delete this file to shutdown D2MP\n")
        self.watcher.addPath(abspath("."))
        self.watcher.directoryChanged.connect(self._watcher_changed_callback)
    
    def _watcher_changed_callback(self, val):
        if self._watcher_file_name not in os.listdir(val): 
            secs = 3
            self.show_message("Shutdown", "Watcher file was deleted. D2MP will shotdown in %d seconds." %(secs))
            sleep(secs)
            self.exit()
    
    def _create_tray_icon(self):
        self.tray = QSystemTrayIcon(self)
        self.tray.setToolTip("D2Moddin Manager")
        self.tray.setIcon(QIcon(SETTINGS['icon']))
        traymenu = QMenu()
        traymenu.addAction("Restart", self.restart)
        traymenu.addAction("Uninstall", self.uninstall)
        traymenu.addAction("Preferences", UIManager().open_preferences)
        traymenu.addAction("Show mod list", self.show_mod_list)
        traymenu.addSeparator()

        traymenu.addAction("Exit", self.exit)
    
        self.tray.setContextMenu(traymenu)
        self.tray.show()
    
    def restart(self):
        python = sys.executable
        args = set(sys.argv)
        args.add("restart")
        os.execl(python, python, *list(sys.argv))
        self.exit()
    
    def uninstall(self):
        ModManager().delete_mods()
#         ModManager().uninstall_d2mp()
        self.exit()
    
    def exit(self):
        # do some cleanup
        return super(SingleApplication, self).exit()
    
    def show_mod_list(self):
        self.show_message("Mod List", ModManager().mod_names_as_string())
    
    def show_message_from_socket(self, message):
        self.show_message("Server message", message)
        
    def show_error_from_socket(self, message):
        self.show_message("Server error", message, QSystemTrayIcon.Critical)
        
    def show_message_from_mod_manager(self, message):
        self.show_message("ModManager message", message)
        
    def show_error_from_mod_manager(self, message):
        self.show_message("ModManager error", message, QSystemTrayIcon.Critical)
        
    def show_message(self, title, message, icon = QSystemTrayIcon.Information):
        self.tray.showMessage(title, message, icon)
示例#21
0
class Example(QtGui.QMainWindow):
    def __init__(self):
        super(Example, self).__init__()

        self.path = sys.path[0]
        f = open("%s/ACCESS_KEY" % self.path, "r")
        f1 = open("%s/ACCESS_SECRET" % self.path, "r")
        f2 = open("%s/user_info" % self.path)
        self.user_name = f2.readline().strip("\n")
        self.user_id = f2.readline().strip("\n")
        self.a = f.readline().strip("\n")
        self.b = f1.readline().strip("\n")
        f.close()
        f1.close()
        f2.close()
        self.initUI()

    def initUI(self):

        self.icon = QSystemTrayIcon()
        self.icon.isSystemTrayAvailable()
        self.icon.setIcon(QtGui.QIcon("%s/me.jpg" % self.path))
        self.icon.setToolTip("dubbleclick untuk maximize")
        self.icon.show()
        self.icon.activated.connect(self.activate)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setGeometry(150, 150, 500, 200)
        frame = QtGui.QFrame(parent=self)
        frame.setStyleSheet("QFrame {background: rgba(0,0,0,50%)}")
        box = QtGui.QHBoxLayout()

        self.edit = QtGui.QLineEdit()
        self.edit.setStyleSheet(
            "background: rgba(0,0,0,100%); " " font-weight : bold;" "color:  rgb(250,250,250);" "border:5px solid "
        )
        self.edit.setToolTip("Tolong  <b>Massukan tweet Anda di sini </b> ")
        self.edit.returnPressed.connect(self.returnPressed)
        box.addWidget(self.edit)

        frame.setLayout(box)

        qbtn1 = QtGui.QPushButton("keluar", self)
        qbtn1.clicked.connect(self.close)
        qbtn1.setStyleSheet(
            "background: rgba(0,0,0,100%); " " font-weight : bold;" "color:  rgb(250,250,250);" "border:5px solid "
        )
        box.addWidget(qbtn1)
        self.statusBar().setStyleSheet(
            "background: rgba(0,0,0,100%);" " font-weight : bold;" "color:  rgb(250,250,250)"
        )
        self.statusBar().showMessage("Tekan enter untuk mengirim twitter, ESC untuk minimize")

        self.setCentralWidget(frame)
        self.setWindowIcon(QtGui.QIcon("%s/me.jpg" % self.path))

        self.setWindowTitle("Twitter Client With PyQt4")
        self.center()
        self.show()
        self.twitter_auth()

    def twitter_auth(self):

        CONSUMER_KEY = "gYMpKX6YWDP5rBwvCcriQ"
        CONSUMER_SECRET = "ulK4WA6gtB5FekyPYRrOXVCxeqvwP66leFfNq5DY"
        ACCESS_KEY = self.a
        ACCESS_SECRET = self.b
        self.auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        self.auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Escape:
            print "Escape wass pressed "
            self.icon.show()

            self.hide()

    def activate(self, reason):
        print reason
        if reason == 2:
            self.show()

    def center(self):

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

    def returnPressed(self):
        path = sys.path[0]
        tweet = self.edit.text()
        api = tweepy.API(self.auth)
        self.statusBar().showMessage("Mengirim . ..  ")
        api.update_status(tweet)
        self.statusBar().showMessage("Twitter Anda terkirim ! ")
        n = pynotify.Notification(
            " @ %s " % self.user_name, "twitter Anda terkirim ", "%s/%s.jpg" % (path, self.user_id)
        )
        n.set_hint("x", 200)
        n.set_hint("y", 400)
        pynotify.init("n")
        n.show()
        self.statusBar().showMessage("Tekan enter untuk mengirim dan tekan ESC untuk minimize ")
        self.edit.clear()
class KerberusSystray(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        icono = 'kerby-activo.ico'
        pixmap = QPixmap(icono)
        ##setear el nombre de la ventana
        self.setWindowTitle('Kerberus Control Parental')
        #colocar el icono cargado a la ventana
        self.setWindowIcon(QIcon(pixmap))
        ##creamos objeto Style para hacer uso de los iconos de Qt
	self.style = self.style()
        self.filtradoHabilitado = True

        if not os.path.isfile('dontShowMessage'):
            self.mostrarMensaje = True
            self.noMostrarMasMensaje()
        else:
            self.mostrarMensaje = False

        #Menu
        self.menu = QMenu('Kerberus')

        #accion deshabilitar filtrado
        self.deshabilitarFiltradoAction = self.menu.addAction(
                            self.style.standardIcon(QStyle.SP_DialogNoButton),
                            'Deshabilitar Filtrado'
                            )
        #accion habilitar filtrado
        self.habilitarFiltradoAction = self.menu.addAction(
                            self.style.standardIcon(QStyle.SP_DialogYesButton),
                            'Habilitar Filtrado'
                            )
        self.habilitarFiltradoAction.setVisible(False)
        #cambiar password
        self.cambiarPasswordAction = self.menu.addAction(
                self.style.standardIcon(QStyle.SP_BrowserReload),
                'Cambiar password de administrador'
                )
        #accion salir
        self.exitAction = self.menu.addAction(
                self.style.standardIcon(QStyle.SP_TitleBarCloseButton),
                'Salir')

        #SIGNAL->SLOT
        QObject.connect(
                self.exitAction,
                SIGNAL("triggered()"),
                lambda: sys.exit()
                )
        QObject.connect(
                self.menu, SIGNAL("clicked()"),
                lambda: self.menu.popup(QCursor.pos())
                )
        QObject.connect(
                self.deshabilitarFiltradoAction,
                SIGNAL("triggered()"),
                self.deshabilitarFiltradoWindow
                )
        QObject.connect(
                self.habilitarFiltradoAction,
                SIGNAL("triggered()"),
                self.habilitarFiltradoWindow
                )
        QObject.connect(
                self.cambiarPasswordAction,
                SIGNAL("triggered()"),
                self.cambiarPasswordWindow
                )

        #SystemTray
        #self.tray = QSystemTrayIcon(QIcon(pixmap), self)
        self.tray = QSystemTrayIcon(self.style.standardIcon(QStyle.SP_DialogYesButton), self)
        self.tray.setToolTip('Kerberus Control Parental - Activado')
        self.tray.setContextMenu(self.menu)
        self.tray.setVisible(True)



        QObject.connect(
                self.tray,
                SIGNAL("messageClicked()"),
                self.noMostrarMasMensaje
                )

        if self.mostrarMensaje:
            self.tray.showMessage(
                    u'Kerberus Control Parental',
                    u'Filtro de Protección para menores de edad Activado',
                    2000
                    )

    #def closeEvent(self, event):
        #event.ignore()
        #self.hide()

    def noMostrarMasMensaje(self):
        try:
            open('dontShowMessage','a').close()
        except IOError:
            print 'No se pudo crear el archivo dontShowMessage'

    def deshabilitarFiltradoWindow(self):
        webbrowser.open(
                'http://inicio.kerberus.com.ar/!DeshabilitarFiltrado!',
                new=2
                )
        self.habilitarFiltradoAction.setVisible(True)
        self.deshabilitarFiltradoAction.setVisible(False)
        self.tray.setIcon(self.style.standardIcon(QStyle.SP_DialogNoButton))
        self.tray.setToolTip('Kerberus Control Parental')

    def habilitarFiltradoWindow(self):
        webbrowser.open(
                'http://inicio.kerberus.com.ar/!HabilitarFiltrado!',
                new=2
                )
        self.habilitarFiltradoAction.setVisible(False)
        self.deshabilitarFiltradoAction.setVisible(True)
        self.tray.setIcon(self.style.standardIcon(QStyle.SP_DialogYesButton))
        self.tray.setToolTip('Kerberus Control Parental - Activado')

    def cambiarPasswordWindow(self):
        webbrowser.open(
                'http://inicio.kerberus.com.ar/!CambiarPassword!',
                new=2
                )
class KerberusSystray(QWidget):
    def __init__(self):
        self.chequeos_activos = True
        self.ultimo_estado_kerberus = True
        QWidget.__init__(self)
        #icono = 'kerby-activo.ico'
        #pixmap = QPixmap(icono)
        self.style = self.style()
        ##setear el nombre de la ventana
        self.setWindowTitle('Kerberus Control Parental')
        #colocar el icono cargado a la ventana
        self.setWindowIcon(self.style.standardIcon(
            QStyle.SP_DialogYesButton))

        self.filtradoHabilitado = True

        if not os.path.isfile('dontShowMessage'):
            self.mostrarMensaje = True
            self.noMostrarMasMensaje()
        else:
            self.mostrarMensaje = False

        #Menu
        self.menu = QMenu('Kerberus')

        #accion configurar Dominios
        self.configurarDominiosAction = self.menu.addAction(
                            'Permitir/Denegar dominios'
                            )
        #accion deshabilitar filtrado
        self.deshabilitarFiltradoAction = self.menu.addAction(
                            'Deshabilitar Filtrado'
                            )
        #accion habilitar filtrado
        self.habilitarFiltradoAction = self.menu.addAction(
                            'Habilitar Filtrado'
                            )
        self.habilitarFiltradoAction.setVisible(False)
        #cambiar password
        self.cambiarPasswordAction = self.menu.addAction(
                'Cambiar password de administrador'
                )
        #recordar password
        self.recordarPasswordAction = self.menu.addAction(
                'Recordar password del administrador'
                )

        #accion salir
        self.exitAction = self.menu.addAction(
                'Salir')

        #SIGNAL->SLOT
        QObject.connect(
                self.exitAction,
                SIGNAL("triggered()"),
                #lambda: sys.exit()
                self.salir
                )
        # esta conexion es utilizada para refrezcar el icono en caso de
        # que se desactive/active kerberus
        QObject.connect(
                self,
                SIGNAL("update()"),
                #lambda: sys.exit()
                self.setIconStatus
                )

        QObject.connect(
                self.menu, SIGNAL("clicked()"),
                lambda: self.menu.popup(QCursor.pos())
                )
        QObject.connect(
                self.deshabilitarFiltradoAction,
                SIGNAL("triggered()"),
                self.deshabilitarFiltradoWindow
                )
        QObject.connect(
                self.habilitarFiltradoAction,
                SIGNAL("triggered()"),
                self.habilitarFiltradoWindow
                )
        QObject.connect(
                self.cambiarPasswordAction,
                SIGNAL("triggered()"),
                self.cambiarPasswordWindow
                )
        QObject.connect(
                self.configurarDominiosAction,
                SIGNAL("triggered()"),
                self.configurarDominios
                )
        QObject.connect(
                self.recordarPasswordAction,
                SIGNAL("triggered()"),
                self.recordarPasswordWindow
                )
        
        #SystemTray
        #self.tray = QSystemTrayIcon(QIcon(pixmap), self)
        self.tray = QSystemTrayIcon(self.style.standardIcon(
            QStyle.SP_DialogYesButton), self)
        self.tray.setToolTip('Kerberus Control Parental - Activado')
        self.tray.setContextMenu(self.menu)
        self.tray.setVisible(True)

        QObject.connect(
                self.tray,
                SIGNAL("messageClicked()"),
                self.noMostrarMasMensaje
                )

        if self.mostrarMensaje:
            self.tray.showMessage(
                    u'Kerberus Control Parental',
                    u'Filtro de Protección para menores de edad Activado',
                    2000
                    )

        # Lanzo el thead que verifica si esta activo o no kerberus
        self.t = threading.Thread(target=self.chequeosPeriodicos)
        self.t.start()

    def chequeosPeriodicos(self):
        while self.chequeos_activos:
            time.sleep(3)
            status = self.checkKerberusStatus()
            if status != self.ultimo_estado_kerberus:
                self.ultimo_estado_kerberus = status
                self.emit(SIGNAL('update()'))

    def setIconStatus(self):
        if self.ultimo_estado_kerberus:
            self.habilitarFiltradoAction.setVisible(False)
            self.deshabilitarFiltradoAction.setVisible(True)
            self.tray.setIcon(self.style.standardIcon(
                QStyle.SP_DialogYesButton))
            self.tray.setToolTip('Kerberus Control Parental - Activado')
            self.tray.showMessage(
                    u'Kerberus Control Parental',
                    u'Filtro de Protección para menores de edad Activado',
                    2000
                    )
        else:
            self.habilitarFiltradoAction.setVisible(True)
            self.deshabilitarFiltradoAction.setVisible(False)
            self.tray.setIcon(self.style.standardIcon(
                QStyle.SP_DialogNoButton))
            self.tray.setToolTip('Kerberus Control Parental - Inactivo')
            self.tray.showMessage(
                    u'Kerberus Control Parental',
                    u'Filtro de Protección para menores de edad Desactivado',
                    2000
                    )

    def salir(self):
        self.chequeos_activos = False
        sys.exit()

    def configurarDominios(self):
        admin = adminPanel()
        admin.show()

    def noMostrarMasMensaje(self):
        try:
            open('dontShowMessage', 'a').close()
        except IOError:
            print 'No se pudo crear el archivo dontShowMessage'

    def deshabilitarFiltradoWindow(self):
        url = 'http://%s:%s/!DeshabilitarFiltrado!' % ('inicio.kerberus.com.ar',
                                                        '80')
        webbrowser.open(
                url,
                new=2
                )

    def checkKerberusStatus(self):
        try:
            url = 'http://%s:%s/' % (config.BIND_ADDRESS, config.BIND_PORT)
            con = httplib.HTTPConnection(config.BIND_ADDRESS, config.BIND_PORT)
            con.request(method='KERBERUSESTADO', url=url)
            respuesta = con.getresponse().read()
            return respuesta == 'Activo'
        except:
            return False

    def habilitarFiltradoWindow(self):
        url = "http://%s:%s/!HabilitarFiltrado!" % ('inicio.kerberus.com.ar',
                                                    '80')
        webbrowser.open(
                url,
                new=2
                )

    def cambiarPasswordWindow(self):
        url = "http://%s:%s/!CambiarPassword!" % ('inicio.kerberus.com.ar',
                                                 '80')
        webbrowser.open(
                url,
                new=2
                )

    def recordarPasswordWindow(self):
        url = "http://%s:%s/!RecordarPassword!" % ('inicio.kerberus.com.ar',
                                                 '80')
        webbrowser.open(
                url,
                new=2
                )