#coding:utf-8

import commands
import os

from PyQt4.Qt import QTimer
from PyQt4.QtCore import QPoint, QRect
from PyQt4.QtCore import Qt, SIGNAL, QString, QProcess
from PyQt4.QtGui import QComboBox, QLineEdit, QTextBrowser, QTextCursor, QPalette
from PyQt4.QtGui import QFont
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QPushButton, QDialog
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QWidget, QPixmap, QPainter

# from base.infohintdialog import InfoHintDialog
from base.tabwidget import TabWidget
from terminal.mythread import MyThread
from terminal.usblist import UsbList
from uiWindow.networkCheck import NetworkCheck
from common.info_dialog import InfoDialog


#本类创建一个NetWidget，将作为一个组件添加到tab中
class NetWidget(NetworkCheck):
    def __init__(self,parent = None):
        super(NetWidget,self).__init__(parent)
        self.auto = False
        #初始化comBox控件，并且为其添加选项
        self.comBox.insertItem(0, u"ping")
        self.comBox.insertItem(1, u"ifconfig")
        self.comBox.insertItem(2, u"xrandr")
        
        self.comBox.insertItem(4, u"top")
        self.connect(self.comBox, SIGNAL('activated(QString)'),self.onActivated)#设置combBox为活动的，与函数关联

        self.runButton.setObjectName("settingDlgBtn")
        self.connect(self.runButton, SIGNAL("clicked()"),self.runButton_clicked)
        self.pingLabel = QLabel()#初始话，之后在函数操作中会改变
        self.pingLabel.setText(u"提示：请在文本框中输入要ping的目标地址，然后点击获取结果")

        self.thread = MyThread(self)
        self.connect(self.thread,SIGNAL("getoutput"),self.appendTo)
        self._run_top_timer = QTimer()

        self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu)
        
    def appendTo(self,actionType):
        
        self.textBrowser.clear()
        self.textBrowser.append(actionType)

        self.runButton.setText(u"停止")
        
        cursor = self.textBrowser.textCursor()
        cursor.movePosition(QTextCursor.Start)
        self.textBrowser.setTextCursor(cursor)
       
    
    def onActivated(self):
        """#comBox的相应函数，随着comBox中字符串的改变，分别控制pingLabel的显示，以及lineEdit和textBrower的显示清除和可用状态
            #如果comBox当前的字符串文字为ping
            #pingLabel的文字设置为"提示：请在文本框中输入要ping的目标地址，然后点击执行获取结果"，保持当前大小
            #lineEdit中内容清除，设置为不可用
            #textBrower清空"""
        # print "test -----"
        if(self.comBox.currentText() == "ping"):
            self.pingLabel.setText(u"提示：请在文本框中输入要ping的目标地址，然后点击执行获取结果")
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setDisabled(False)

            self.lineEditSetStyGroove(False)
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为ifconfig
            #类上所说

            self.lineEdit.setStyleSheet("QLineEdit{}")
        elif(self.comBox.currentText() == "ifconfig"):
            self.pingLabel.setText(u"提示：请点击执行，获取终端的网卡和IP等信息")
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            #
            self.lineEditSetStyGroove()  # linedit  置灰
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为xrandr
        elif(self.comBox.currentText() == "xrandr"):
            self.pingLabel.setText(u"提示：执行xrandr命令")
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)

            self.lineEditSetStyGroove()  # linedit  置灰
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为tracerout
        elif(self.comBox.currentText() == "traceroute"):
            self.pingLabel.setText(u"提示：请在文本框中输入要traceroute的目标地址，然后点击执行获取结果")
            self.pingLabel.adjustSize()
            self.lineEdit.setEnabled(True)
            self.lineEdit.clear()

            self.lineEditSetStyGroove()  # linedit  置灰

            self.textBrowser.clear()
        elif(self.comBox.currentText() == "top"):
    
            self.pingLabel.setText(u"提示：执行top命令")
            self.pingLabel.adjustSize()
            self.lineEdit.setEnabled(False)

            self.lineEditSetStyGroove()  # linedit  置灰
            self.lineEdit.clear()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Enter or e.key() == Qt.Key_Return:
            self.runButton_clicked()

            #按钮的响应函数
    def runButton_clicked(self):
        """changed by wmz"""
        self.connect(self._run_top_timer,SIGNAL("timeout()"),self.thread.start)
        
        cmdstr = QString()
        center = QString()
        goal = QString()
        #comBox当前text为ping
        if (self.comBox.currentText() == "ping"):
            if (self.runButton.text() == u"执行" ) :
                center = self.lineEdit.text()
                if (center == ""):
                    InfoDialog.instance().MessageBox(u'警告',u'请输入ping地址!')
                    # InfoHintDialog(u'请输入ping地址!').exec_()

                    self.runButton.setText(u"执行")
                else:
                    self.comBox.setDisabled(True)
                    self.pro = QProcess(self)
                    self.runButton.setText(u"停止ping")
                    cmdstr = "ping " +center
                    self.textBrowser.clear()
                    self.textBrowser.append(u" ping "+center+u" 结果：")
            else:
                self.comBox.setDisabled(False)
                self.runButton.setText(u"执行")
                self.pro.close()
        elif(self.comBox.currentText() == "ifconfig"):
            self.pro = QProcess(self)
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
            cmdstr = "ifconfig"
            #如果comBox当前为traceroute
        elif(self.comBox.currentText() == "traceroute"):
                goal = self.lineEdit.text()
                if (self.runButton.text() == u"执行"):
                    if( goal.isEmpty() or goal.isNull() ):
                        InfoDialog.instance().MessageBox(u'警告',u'请输入tracer地址!')
                        # InfoHintDialog(u'请输入tracer地址：').exec_()

                    else:
                        self.proc = QProcess(self)
                      
                        cmdstrc = "traceroute -n "+ goal
                        self.proc.start(cmdstrc)
                        self.connect(self.proc, SIGNAL("readyReadStandardOutput()"),self.readR)
                        self.connect(self.proc, SIGNAL("readyReadStandardError()"),self.readErrorR)
                        if self.proc.waitForStarted(10) == True:
                            self.comBox.setDisabled(True)
                            self.runButton.setText(u"停止执行")
                else:
                    self.runButton.setText(u"执行")
                    self.comBox.setDisabled(False)
                    self.proc.close()
            #如果comBox当前为xrandr
        elif (self.comBox.currentText() == "xrandr"):
            self.pro = QProcess(self)
            cmdstr = "xrandr"
            self.textBrowser.clear()
            #如果当前命令cmdstr不为空，则
          
        #"""changed by wmz"""                     
        elif (self.comBox.currentText() == "top"):
            if self.runButton.text() == u"执行" :
                self.runButton.setText(u"停止")
                self.comBox.setEnabled(False)
                self._run_top_timer.start(2000)#create pbc 
              
            elif self.runButton.text() == u"停止":
                self.runButton.setText(u"执行")
                self.comBox.setEnabled(True)
                self.thread.auto = False
                self._run_top_timer.stop()#create pbc
            else:
                pass #
            
        if (cmdstr != ""):
                self.pro.start(cmdstr)#开启执行命令
                self.connect(self.pro, SIGNAL("readyReadStandardOutput()"),self.read)#读取执行正常输出槽函数
                self.connect(self.pro, SIGNAL("readyReadStandardError()"),self.readError)#执行异常槽函数
            
            #读取控制台输出
    def read(self):
        res = QString.fromLocal8Bit(self.pro.readAllStandardOutput())
        self.textBrowser.append(res)#添加到text框
        #读取错误
    def readError(self):
        res = QString.fromLocal8Bit(self.pro.readAllStandardError())
        self.textBrowser.append(res)
    def readR(self):
        
        res = QString.fromLocal8Bit(self.proc.readAllStandardOutput())

        self.textBrowser.append(res)

    def readErrorR(self):

        res = QString.fromLocal8Bit(self.proc.readAllStandardError())
        self.textBrowser.append(res)


#本类创建一个HardWidget，之后作为一个组件添加到tab中        
class HardWidget(QWidget):
       
    def __init__(self,parent = None):
        super(HardWidget,self).__init__(parent)
        self.setStyleSheet("QWidget{font-size:10pt;}"
                           "QLineEdit{border:1px groove rgb(170,214,252);}"
                           "QLineEdit{height:25;}"
                           "QComboBox{border: 1px groove rgb(170,214,252);}"
                           "QComboBox{height:25;}"
                           "QComboBox::drop-down{border-bottom-right-radius: 3px;}"
                           "QComboBox::drop-down{subcontrol-origin: padding;}"
                           "QComboBox::drop-down{subcontrol-position: top right;}"
                           "QComboBox::drop-down{width: 20px;}"
                           "QComboBox::drop-down{border-left-width: 1px;}"
                           "QComboBox::drop-down{border-left-color: rgb(170,214,252);}"
                           "QComboBox::drop-down{border-left-style: solid;}"
                           "QComboBox::drop-down{border-top-right-radius: 3px;}"
                           "QComboBox::down-arrow {image:url(../images/downarrow.png);}"
                           "QPushButton{background:url(../images/button.png);border:2px;}")
        #分别返回各个函数的返回值
        

        
        self.a = float()#声明一个float类型的數，之后作为本类中某个函数的参数
            #声明一个label，书写超级密码，字体，长度120
        self.passLabel = QLabel(u"超级密码:")
        self.passLabel.setFixedWidth(100)
        self.passLabel.setFont(QFont("times",11))
            #声明一个label，书写提示信息
        self.tipLabel  = QLabel(u"提示：请输入超级密码获取硬件信息")
            #声明一个文本框，用来输入密码
        self.lineEdit  = QLineEdit()
        self.lineEdit.setEchoMode(QLineEdit.Password)
        self.lineEdit.setFixedWidth(250)
            #声明一个pushbutton，立即收集
        self.runButton = QPushButton(u"立即收集")
        self.runButton.setFixedSize(75,27)
        self.runButton.setFlat(True)
        
            #声明一个textBrower，用来显示收集的信息
        self.textArea = QTextBrowser()
        
            #布局一，横向布局，添加passLabel,lineEdit,runButton，设置前后的空白分别为20和280，中间充满
        hLayout1 = QHBoxLayout()
        hLayout1.addSpacing(20)
        hLayout1.addWidget(self.passLabel)
        hLayout1.addWidget(self.lineEdit)
        hLayout1.addWidget(self.runButton)
        hLayout1.addSpacing(100)
            #布局二，横向布局，添加tipLabe，提示信息显示，设置前面的空白为20，后边充满
        hLayout2 = QHBoxLayout()
        hLayout2.addSpacing(20)
        hLayout2.addWidget(self.tipLabel)
            #布局三，横向布局，添加textArea，设这前后的空白为20和60，中间充满
        hLayout3 = QHBoxLayout()
        hLayout3.addSpacing(20)
        hLayout3.addWidget(self.textArea)
        hLayout3.addSpacing(60)
        
            #总其布局，纵向布局，将上面的三个布局加入其中，设置间隔为20，最下面的空白为40
        mainLayout = QVBoxLayout()
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout1)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout2)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout3)
        mainLayout.addSpacing(60)
        self.setLayout(mainLayout)
        #runButton的槽函数链接
        self.connect(self.runButton, SIGNAL("clicked()"),self.run)
    #获取内存信息的函数
    def memory_stat(self):
        mem = {}
        f = open("/proc/meminfo")
        lines = f.readlines()
        f.close()
        for line in lines:
            if len(line) < 2: continue
            name = line.split(':')[0]
            var = line.split(':')[1].split()[0]
            mem[name] = long(var)
        mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
        return mem
    #读取磁盘信息函数
    def disk_stat(self):
        cmd = "df -h --total | grep total"
        output = ""
        hd = {}
        hd['available'] = 0
        hd['capacity'] = 0
        hd['free'] = 0
        hd['used'] = 0
        status = commands.getstatusoutput(cmd)
        if status[0] == 0:
            output = status[1]
        disklist = QString(output).simplified().split(" ")
        num = len(disklist)
        if num < 5:
            return hd
        else:
            hd['free'] = int(float(disklist[3].split("G")[0])*1024*1024)
            hd['capacity'] = int(float(disklist[1].split("G")[0])*1024*1024)
            hd['used'] = int(float(disklist[2].split("G")[0])*1024*1024)
            hd['available'] = hd['capacity'] - hd['used']
        return hd
    
    def disk_stat_(self):
        hd = {}
        disk = self.get_mounted_disks()
        total = 0
        used = 0
        free = 0
        for i in range(len(disk)):
            total += int(disk[i]["total"])
            used += int(disk[i]["used"])
            free += int(disk[i]["free"])
        
        hd['available'] = total - used
        hd['capacity'] = total
        hd['free'] = free
        hd['used'] = used
        
        return hd
    #读取cpu信息函数
    def get_fs_info(self,path):

        hddinfo = os.statvfs(path)
        total = hddinfo.f_frsize * hddinfo.f_blocks
        free = hddinfo.f_frsize * hddinfo.f_bavail
        used = hddinfo.f_frsize * (hddinfo.f_blocks - hddinfo.f_bfree)
        return {'total': int(float(total)/1024),
                'free': int(float(free)/1024),
                'used': int(float(used)/1024)}
    
    def get_mounted_disks(self):
        with open('/proc/mounts', 'r') as f:
            mounts = f.readlines()
     
        disk = []
        for mount in mounts:
            if mount.startswith('/dev/'):
                mount = mount.split()
                dev = mount[0]
                target = mount[1]
                
          
                disk.append(self.get_fs_info(target))
        return disk
    def cpu_stat(self):
        cpu = []
        cpuinfo = {}
        f = open("/proc/cpuinfo")
        lines = f.readlines()
        f.close()
        for line in lines:
                if line == '\n':
                    cpu.append(cpuinfo)
                    cpuinfo = {}
                if len(line) < 2: continue
                name = line.split(':')[0].rstrip()
                var = line.split(':')[1]
                cpuinfo[name] = var
        return cpu[0]
    #读取负载信息函数
    def load_stat(self):
        loadavg = {}
        f = open("/proc/loadavg")
        con = f.read().split()
        f.close()
        loadavg['lavg_1']=con[0]
        loadavg['lavg_5']=con[1]  #average load per five minute
        loadavg['lavg_15']=con[2]
        loadavg['nr']=con[3]
        loadavg['last_pid']=con[4]
        return loadavg
    #读取运行时间函数
    def uptime_stat(self):
        uptime = {}
        f = open("/proc/uptime")
        con = f.read().split()
        f.close()
        all_sec = float(con[0])
        MINUTE,HOUR,DAY = 60,3600,86400
        uptime['day'] = int(all_sec / DAY )
        uptime['hour'] = int((all_sec % DAY) / HOUR)
        uptime['minute'] = int((all_sec % HOUR) / MINUTE)
        uptime['second'] = int(all_sec % MINUTE)
        uptime['Free rate'] = float(con[1]) / float(con[0])
        return uptime
    #读取网络信息函数
    def net_stat(self):
        net = []
        f = open("/proc/net/dev")
        lines = f.readlines()
        f.close()
        for line in lines[2:]:
                con = line.split()
         
                if (len(con) == 16):
                    intf = {}
                    intf['interface'] = con[0].split(':')[0].rstrip()#first data includes two content
                    intf['ReceiveBytes'] = int(con[0].split(':')[1])
                    intf['ReceivePackets'] = int(con[1])
                    intf['ReceiveErrs'] = int(con[2])
                    intf['ReceiveDrop'] = int(con[3])
                    intf['ReceiveFifo'] = int(con[4])
                    intf['ReceiveFrames'] = int(con[5])
                    intf['ReceiveCompressed'] = int(con[6])
                    intf['ReceiveMulticast'] = int(con[7])
                    intf['TransmitBytes'] = int(con[8])
                    intf['TransmitPackets'] = int(con[9])
                    intf['TransmitErrs'] = int(con[10])
                    intf['TransmitDrop'] = int(con[11])
                    intf['TransmitFifo'] = int(con[12])
                    intf['Transmitcolls'] = int(con[13])
                    intf['Transmitcarrier'] = int(con[14])
                    intf['TransmitCompressed'] = int(con[15])
                    
                elif (len(con) == 17):
                    intf = {}
                    intf['interface'] = con[0]
                    intf['ReceiveBytes'] = int(con[1])
                    intf['ReceivePackets'] = int(con[2])
                    intf['ReceiveErrs'] = int(con[3])
                    intf['ReceiveDrop'] = int(con[4])
                    intf['ReceiveFifo'] = int(con[5])
                    intf['ReceiveFrames'] = int(con[6])
                    intf['ReceiveCompressed'] = int(con[7])
                    intf['ReceiveMulticast'] = int(con[8])
                    intf['TransmitBytes'] = int(con[9])
                    intf['TransmitPackets'] = int(con[10])
                    intf['TransmitErrs'] = int(con[11])
                    intf['TransmitDrop'] = int(con[12])
                    intf['TransmitFifo'] = int(con[13])
                    intf['Transmitcolls'] = int(con[14])
                    intf['Transmitcarrier'] = int(con[15])
                    intf['TransmitCompressed'] = int(con[16])
                net.append(intf)
        return net
        #将flaot类型的数，转换为string的函数
    def floatToString(self, a):
        if a <= 0 :
            e = int(a*100000000)
            b = QString().number(e)
            m = len(b)
            x = ""
        elif a > 0:
            e = int(a)
            x = QString().number(e)
            s = a - float(e)
            
            f = int(s*100000000)
            b = QString().number(f)
            m = len(b)
            
        if (8-m) == 0:
            n = b
        elif (8-m) == 1:
            n = "0" + b
        elif (8-m) == 2:
            n = "0" + "0" + b
        elif (8-m) == 3:
            n = "0" + "0" + "0" + b
        elif (8-m) == 4:
            n = "0" + "0" + "0" + "0" + b
        elif (8-m) == 5:
            n = "0" + "0" +"0" + "0" + "0" + b   
        else:
            n = "0" + "0" +"0" + "0" + "0" + "0" + b
        c = x +"."+ n
        return c
    
    #读文件，取密码
    def readText(self):
        return "mcosterminal"
    
    #button运行函数
    def run(self):
        self.mypass = self.readText()#读取文件信息，内容为密码
        if (self.lineEdit.text() == self.mypass):
                self.mymem = self.memory_stat()#返回内存信息
                self.mydisk = self.disk_stat()#返回硬盘信息
                self.mycpu = self.cpu_stat()#返回cpu信息
                self.myload = self.load_stat()#返回负载信息
                self.myuptime = self.uptime_stat()#返回运行时间
                self.mynet = self.net_stat()#返回网络信息
                
                
                self.textArea.clear()
                self.lineEdit.clear()
                usedText = QString().number(self.mymem['MemUsed'])
                totalText = QString().number(self.mymem['MemTotal'])
                freeText = QString().number(self.mymem['MemFree'])
                buffersText = QString().number(self.mymem['Buffers'])
                cachedText = QString().number(self.mymem['Cached'])
                self.textArea.append(u"内存：")
                self.textArea.append(u"总共内存：" + "\t\t" + totalText + " \tKB "+ "\r\n" + u"已经使用内存：" + "\t" + usedText+ " \tKB "+ "\r\n" + u"空闲内存：" + "\t\t" + freeText+ " \tKB "+ "\r\n" +"Buffers:\t\t"+ buffersText+ " \tKB "+ "\r\n" +"Cached:\t\t"+ cachedText+ " \tKB ")
               
                freeText1 = QString().number(self.mydisk['free'])
                avaiText1 = QString().number(self.mydisk['available'])
                totalText1 = QString().number(self.mydisk['capacity'])
                
                usedText1 = QString().number(self.mydisk['used'])
                self.textArea.append(" ")
                self.textArea.append(u"硬盘：")
                self.textArea.append(u"硬盘总容量：" + "\t\t" + totalText1+ " \tKB " + "\r\n" + u"硬盘总可使用容量：" + "\t"  + freeText1+ " \tKB " + "\r\n" + u"已经使用容量：" + "\t" + usedText1+ " \tKB " + "\r\n" +u"当前空闲容量：" + "\t" + avaiText1+ " \tKB ")
                self.textArea.append(" ")
                self.textArea.append(u"Cpu型号：")
                self.textArea.append("Model name:\t"+self.mycpu['model name'] +  "Cpu MHz:\t\t"+self.mycpu['cpu MHz'] +  "Cache size:\t\t"+self.mycpu['cache size'] +  "Vendor_id:\t\t"+self.mycpu['vendor_id'] + "Cpu family:\t\t"+self.mycpu['cpu family'] +  "Model:\t\t"+self.mycpu['model'] + "Clflush size:\t\t"+self.mycpu['clflush size'] +  "Processor:\t\t"+self.mycpu['processor'])
              
                self.textArea.append(u"负载情况：")
                self.textArea.append(u"lavg_1:" + "\t" + self.myload['lavg_1'] +"\r\n" + u"lavg_5:" + "\t" + self.myload['lavg_5'] +"\r\n" + u"lavg_15:" + "\t" + self.myload['lavg_15'] +"\r\n" + u"nr:" + "\t" + self.myload['nr'] +"\r\n" + u"last_pid:" + "\t" + self.myload['last_pid'])
                self.textArea.append(" ")
                self.textArea.append(u"主机运行时间：")
                self.textArea.append(u"天数："+ "\t" + QString().number(self.myuptime['day']) + "\r\n" +u"小时数：" + "\t"  + QString().number(self.myuptime['hour']) + "\r\n" +u"分数：" + "\t" + QString().number(self.myuptime['minute']) + "\r\n" +u"秒数：" + "\t" + QString().number(self.myuptime['second']))
                a = self.floatToString(self.myuptime["Free rate"])
                self.textArea.append(u"空闲率："+ "\t" + a)
                self.textArea.append(" ")
                self.textArea.append(u"网络流量传输：")
                self.textArea.append(u"网卡（interface）:" + "\t" + self.mynet[0]['interface'] +"\r\n"+ u"接收的字节数：" + "\t"  + QString().number(self.mynet[0]['ReceiveBytes']) +"\r\n"+ u"接收的包数：" + "\t\t"  + QString().number(self.mynet[0]['ReceivePackets']) +"\r\n"+ u"接收的错误报告数：" + "\t"  + QString().number(self.mynet[0]['ReceiveErrs']) +"\r\n" + u"接收的桢数：" + "\t\t"  + QString().number(self.mynet[0]['ReceiveFrames']) +"\r\n"+ u"接收的丢失数量：" + "\t"  + QString().number(self.mynet[0]['ReceiveDrop']))
                self.textArea.append(u"传输的字节数：" + "\t"  + QString().number(self.mynet[0]['TransmitBytes']) +"\r\n"+ u"传输的包数：" + "\t\t"  + QString().number(self.mynet[0]['TransmitPackets']) +"\r\n"+ u"传输的错误报告数："  + "\t" + QString().number(self.mynet[0]['TransmitErrs']) +"\r\n"+  u"传输的丢失数量：" + "\t"  + QString().number(self.mynet[0]['TransmitDrop']))
                self.textArea.append(u"网卡（interface）:" + "\t" + self.mynet[1]['interface'] +"\r\n"+ u"接收的字节数：" + "\t"  + QString().number(self.mynet[1]['ReceiveBytes']) +"\r\n"+ u"接收的包数：" + "\t\t"  + QString().number(self.mynet[1]['ReceivePackets']) +"\r\n"+ u"接收的错误报告数：" + "\t"  + QString().number(self.mynet[1]['ReceiveErrs']) +"\r\n" + u"接收的桢数：" + "\t\t"  + QString().number(self.mynet[1]['ReceiveFrames']) +"\r\n"+ u"接收的丢失数量：" + "\t"  + QString().number(self.mynet[1]['ReceiveDrop']))
                self.textArea.append(u"传输的字节数：" + "\t"  + QString().number(self.mynet[1]['TransmitBytes']) +"\r\n"+ u"传输的包数：" + "\t\t"  + QString().number(self.mynet[1]['TransmitPackets']) +"\r\n"+ u"传输的错误报告数："  + "\t" + QString().number(self.mynet[1]['TransmitErrs']) +"\r\n"+  u"传输的丢失数量：" + "\t"  + QString().number(self.mynet[1]['TransmitDrop']))
          
        elif self.lineEdit.text() == "":
            InfoDialog.instance().MessageBox(u'警告',u'密码不能为空!')
            # .(u'密码不能为空!').exec_()
            self.textArea.clear()
        else:
            InfoDialog.instance().MessageBox(u'警告',u'密码错误!')
            # InfoHintDialog(u'密码错误!').exec_()
            self.lineEdit.clear()

class ToolWidget(QDialog):
    def __init__(self,parent = None):
        super(ToolWidget,self).__init__(parent)
   
        self.setWindowTitle(u'硬件设备')
        self.desktop = QApplication.desktop()
        self.setFixedSize(600,600)
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.Dialog)

        self.move((self.desktop.width()-self.width())/2,(self.desktop.height()-self.height())/2)
        self.tabWidget = TabWidget()
      
        self.tabWidget.netService = NetWidget(self)
        self.tabWidget.usbList = UsbList(self)
  
        self.tabWidget.addTab(self.tabWidget.netService, u"网络诊断")
        self.tabWidget.addTab(self.tabWidget.usbList,u"USB硬件列表")
       
        
        layout = QVBoxLayout()
        layout.addSpacing(33)
        layout.addWidget(self.tabWidget)

        layout.setMargin(0)
        self.setLayout(layout)
        
        self.tabWidget.netService.lineEdit.setFocus(True)
        
        self.closeButton = QPushButton()
        self.closeButton.setObjectName("settingDlgBtn")

            
        self.closeButton.mousePressed = False
        self.closeButton.setFixedSize(30,30)

        self.closeButton.move(QPoint(self.geometry().width()-self.closeButton.frameGeometry().width() - (self.tabWidget.tabBar().height()-self.closeButton.geometry().height())/2,(self.tabWidget.tabBar().height()-self.closeButton.geometry().height())/2))
        
        self.cancelButton = QPushButton(u"退出",self)
        self.cancelButton.setObjectName("settingDlgBtn")

        self.cancelButton.setFixedSize(75,27)
        self.cancelButton.setFlat(True)
        self.cancelButton.move(QPoint(self.width()-self.cancelButton.width()-30,self.height()-self.cancelButton.height()-20))
        
        self.connect(self.cancelButton, SIGNAL("clicked()"),self.cancel)
        self.connect(self.closeButton, SIGNAL("clicked()"),self.cancel)
       
        
    def mouseMoveEvent(self,event):
        if self.closeButton.mousePressed:
            self.move(self.pos() + event.pos() - self.currentPos)   
        self.default = QString()
    def mousePressEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.currentPos = event.pos()
            self.closeButton.mousePressed = True
   
    def mouseReleaseEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.closeButton.mousePressed = False
            
    def cancel(self):
        self.close() 
        
    def paintEvent(self,event):
        
        painter = QPainter(self)
        painter.save()
        pix = QPixmap("../images/terminaltool.png")
        painter.drawPixmap(QRect(0,0,800,33),pix)

        painter.restore()


if __name__ == "__main__":
    import sys
    from PyQt4.QtGui import QApplication
    from PyQt4.QtCore import QTextCodec
    app = QApplication(sys.argv)
    QTextCodec.setCodecForCStrings(QTextCodec.codecForName("utf-8"))
    win = NetWidget()

    # win2 = HardWidget()
    win.show()
    # win2.show()
    app.exec_()
