# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'autoStartDesktopSet.ui'
#
# Created: Fri May 27 11:33:29 2016
#      by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(658, 357)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Ignored)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
        Form.setSizePolicy(sizePolicy)
        self.verticalLayout_3 = QtGui.QVBoxLayout(Form)
        self.verticalLayout_3.setSpacing(0)
        self.verticalLayout_3.setMargin(0)
        self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
        self.widget = QtGui.QWidget(Form)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
        self.widget.setSizePolicy(sizePolicy)
        self.widget.setObjectName(_fromUtf8("widget"))
        self.horizontalLayout_top = QtGui.QHBoxLayout(self.widget)
        self.horizontalLayout_top.setSpacing(0)
        self.horizontalLayout_top.setMargin(0)
        self.horizontalLayout_top.setObjectName(_fromUtf8("horizontalLayout_top"))
        self.label = QtGui.QLabel(self.widget)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout_top.addWidget(self.label)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_top.addItem(spacerItem)
        self.label_2 = QtGui.QLabel(self.widget)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.horizontalLayout_top.addWidget(self.label_2)
        spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_top.addItem(spacerItem1)
        self.verticalLayout_3.addWidget(self.widget)
        self.widget_2 = QtGui.QWidget(Form)
        self.widget_2.setObjectName(_fromUtf8("widget_2"))
        self.verticalLayout_2 = QtGui.QVBoxLayout(self.widget_2)
        self.verticalLayout_2.setSpacing(0)
        self.verticalLayout_2.setMargin(0)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setSpacing(0)
        self.horizontalLayout.setContentsMargins(-1, -1, 0, -1)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.line = QtGui.QFrame(self.widget_2)
        self.line.setFrameShape(QtGui.QFrame.VLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName(_fromUtf8("line"))
        self.horizontalLayout.addWidget(self.line)
        self.tableWidget = QtGui.QTableWidget(self.widget_2)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth())
        self.tableWidget.setSizePolicy(sizePolicy)
        self.tableWidget.setLineWidth(0)
        self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
        self.tableWidget.setColumnCount(0)
        self.tableWidget.setRowCount(0)
        self.horizontalLayout.addWidget(self.tableWidget)
        self.line_2 = QtGui.QFrame(self.widget_2)
        self.line_2.setFrameShape(QtGui.QFrame.VLine)
        self.line_2.setFrameShadow(QtGui.QFrame.Sunken)
        self.line_2.setObjectName(_fromUtf8("line_2"))
        self.horizontalLayout.addWidget(self.line_2)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.line_3 = QtGui.QFrame(self.widget_2)
        self.line_3.setFrameShape(QtGui.QFrame.HLine)
        self.line_3.setFrameShadow(QtGui.QFrame.Sunken)
        self.line_3.setObjectName(_fromUtf8("line_3"))
        self.verticalLayout.addWidget(self.line_3)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setSpacing(0)
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem2)
        self.pushButton = QtGui.QPushButton(self.widget_2)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        self.pushButton.setText(_fromUtf8(""))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.horizontalLayout_2.addWidget(self.pushButton)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.verticalLayout_3.addWidget(self.widget_2)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.label.setText(_translate("Form", "设备标识", None))
        self.label_2.setText(_translate("Form", "设备描述", None))


from PyQt4.QtGui import QWidget, QFrame, QAbstractItemView, QTableWidgetItem
from PyQt4.QtCore import QString, Qt, pyqtSlot, SIGNAL
import  commands
from common import common_run
from os import getenv

class UsbList(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(UsbList, self).__init__(parent)
        self.setupUi(self)
        self.__borderImagesPath = getenv('WIN_UI_IMAGES_PATH') # 读取环境变量 图片路径
        self.__set_stylesheet()
        self.update_date()

    @pyqtSlot()
    def on_pushButton_clicked(self):#pushbutton for update
        self.update_date()

    def __set_stylesheet(self):
        self.verticalLayout_3.setContentsMargins(int(common_run.get_width(40.0)),
                                                 int(common_run.get_height(20.0)),
                                                 int(common_run.get_width(40.0)),
                                                 int(common_run.get_height(60.0)))

        self.verticalLayout_2.setSpacing(int(common_run.get_height(12.0)))

        __button_size_height = common_run.get_height(30.0)
        __button_size_with = common_run.get_width(75.0)
        self.pushButton.setMinimumHeight(int(__button_size_height))
        self.pushButton.setMinimumWidth(int(__button_size_with))
        self.pushButton.setMaximumHeight(int(__button_size_height))
        self.pushButton.setMaximumWidth(int(__button_size_with))
        __font_size = str(int(common_run.get_height(12.0)))
        self.pushButton.setText(u'刷新')
        self.pushButton.setStyleSheet(
             QString("QPushButton{color: rgb(255,255,255);font: 63 "+__font_size+"pt;border-image: url(%1/settingWindow/btn_backgound1.png);border: 2px;}"
            "QPushButton:hover{border-image:url(%1/settingWindow/btn_backgound2.png);border: 2px;}"
            "QPushButton:pressed{border-image: url(%1/settingWindow/btn_backgound3.png);border: 2px;}").arg(str(self.__borderImagesPath))
        )


        __font_size = str(int(common_run.get_height(13.0)))
        self.widget.setStyleSheet("background-color: rgb(220, 220, 220);"
                                  "font: 63 " + __font_size + "pt \"ubuntu\" ;")

        self.widget.setMinimumHeight(int(common_run.get_height(40.0)))
        self.horizontalLayout_top.setContentsMargins(int(common_run.get_width(40.0)),
                                                     0,
                                                     int(common_run.get_width(40.0)),
                                                     0)

        __font_size = str(int(common_run.get_height(11.0)))
        self.tableWidget.setStyleSheet("font: 63 " + __font_size + "pt \"ubuntu\" ;"
                                                                   "text-align: center;"
                                                                   "border:0px groove rgb(200,200,200);")

        self.tableWidget.verticalHeader().setHidden(True)
        self.tableWidget.horizontalHeader().setHidden(True)
        self.tableWidget.setShowGrid(False)
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)

        self.tableWidget.setFrameShape(QFrame.NoFrame)
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setColumnWidth(0,int(common_run.get_width(100.0)))


    def getUsbDevice(self):
        cmd = "lsusb"
        usblist = []
        statusOutput = commands.getstatusoutput(cmd)
        if statusOutput[0] == 0:  # 如果是0，则执行成功
            output = statusOutput[1]  # 第二个元素就是命令行执行后的输出
        else:
            output = ""

        temp = output.split("\n")
        for i in range(len(temp)):
            if not QString(temp[i]).contains("except"):
                usblist.append(temp[i])

        usbcount = len(usblist)

        if (usbcount == 0):
            return []
        else:
            usbList = self.fillUsbList(usblist);
            return usbList

    def fillUsbList(self, usbList):
        usbInfo = ""
        usbListStr = []

        for i in range(len(usbList)):
            list = {}
            usbInfo = usbList[i]
            insec = usbInfo.split("ID ")[1]
            bus = usbInfo.split("ID ")[0]
            if (insec != "" and bus != ""):
                content = insec.split(" ")
                buslist = bus.split(" ")
                deviceId = content[0]
                busId = buslist[1]
                _describe = ""

                for j in range(len(content)):
                    _describe = _describe + " " + content[j]
                list["deviceId"] = deviceId
                list["describe"] = _describe
                list["bus"] = busId
                usbListStr.append(list)

        return usbListStr

    def update_date(self):
        self.tableWidget.clear()
        usbList = self.getUsbDevice()
        usbNum = len(usbList)
        self.tableWidget.setRowCount(usbNum)
        for i in range(usbNum):
            pTWItemBus = QTableWidgetItem(usbList[i]["bus"])
            pTWItemBus.setTextAlignment(Qt.AlignCenter)
            self.tableWidget.setItem(i, 0, pTWItemBus)

            pTWItemName = QTableWidgetItem(usbList[i]["deviceId"])
            pTWItemName.setTextAlignment(Qt.AlignCenter)
            self.tableWidget.setItem(i, 1, pTWItemName)

            pTWItemStatus = QTableWidgetItem(usbList[i]["describe"])
            pTWItemStatus.setTextAlignment(Qt.AlignCenter)
            self.tableWidget.setItem(i, 2, pTWItemStatus)





"""

import commands
from PyQt4.QtCore import Qt, SIGNAL, QString
from PyQt4.QtGui import QWidget, QPushButton, QVBoxLayout, QTableWidget, QAbstractItemView, QTableWidgetItem, \
    QHBoxLayout
from common import common_run

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

        self.tableWidgetUsb = QTableWidget()


        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.setMargin(40)

        self.mainLayout.addWidget(self.tableWidgetUsb)
        self.mainLayout.addSpacing(40)
        self.setLayout()

    def setLayout(self):
        strList = [u"总线ID", u"设备ID", u"设备描述"]
        self.tableWidgetUsb.setHorizontalHeaderLabels(strList)

        self.tableWidgetUsb.setEditTriggers(QAbstractItemView.NoEditTriggers)
        usbList = self.getUsbDevice()
        usbNum = len(usbList)

        self.tableWidgetUsb.setRowCount(usbNum + 1)

        # 填充数据

        for i in range(usbNum):
            pTWItemBus = QTableWidgetItem(usbList[i]["bus"])
            pTWItemBus.setTextAlignment(Qt.AlignCenter)
            self.tableWidgetUsb.setItem(i, 0, pTWItemBus)

            pTWItemName = QTableWidgetItem(usbList[i]["deviceId"])
            pTWItemName.setTextAlignment(Qt.AlignCenter)
            self.tableWidgetUsb.setItem(i, 1, pTWItemName)

            pTWItemStatus = QTableWidgetItem(usbList[i]["describe"])
            pTWItemStatus.setTextAlignment(Qt.AlignCenter)
            self.tableWidgetUsb.setItem(i, 2, pTWItemStatus)



        # 最后一行加一个刷新
        stwid = QWidget()
        sthLayout = QHBoxLayout();
        butFlush = QPushButton(u"刷新")
        butFlush.setObjectName("settingDlgBtn")

        sthLayout.addWidget(butFlush)
        sthLayout.setMargin(0)
        sthLayout.setAlignment(butFlush, Qt.AlignCenter);
        butFlush.setFixedSize(75, 27)
        butFlush.setFlat(True)
        self.connect(butFlush, SIGNAL("clicked()"), self.usbFlush)
        stwid.setLayout(sthLayout)
        self.tableWidgetUsb.setCellWidget(usbNum, 2, stwid)

    def usbFlush(self):
        self.tableWidgetUsb.clear()
        self.setLayout()



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 = UsbList()

    win.show()

    app.exec_()

"""
