class STCLogger():
    DEBUG = "debug"
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"
    CRITICAL = "critical"
    def __init__(self):

        self.loggername = "STCLogger"
        #当前日志模式
        self.setLogLevel(self.INFO)

        #logging.basicConfig(level=logging.DEBUG)
        self.logger = logging.getLogger(self.loggername)

        self.logger.setLevel(logging.DEBUG)

        # create a file handler
        self.handler = logging.FileHandler(ConfigHelper.LOGCATPATH, "a", encoding="UTF-8")
        self.handler.setLevel(logging.DEBUG)

        # create a logging format
        self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.handler.setFormatter(self.formatter)

        # add the handlers to the logger
        self.logger.addHandler(self.handler)

    def removeHandler(self):
        self.logger.removeHandler(self.handler)
        return

    def e(self, *args):
        self.logger.error(args)
        self.filterLog(self.ERROR,args)
        self.removeHandler()
        return


    def w(self, *args):
        self.logger.warning(args)
        self.filterLog(self.WARNING, args)
        self.removeHandler()
        return

    def i(self, *args):
        self.logger.info(args)
        self.filterLog(self.INFO, args)
        self.removeHandler()
        return

    def d(self, *args):
        self.logger.debug(args)
        self.filterLog(self.DEBUG, args)
        self.removeHandler()
        return

    def c(self, *args):
        self.logger.critical(args)
        self.filterLog(self.CRITICAL, args)
        self.removeHandler()
        return



    def filterLog(self,mode, args):
        preLevel = self.getCurLogLevel(mode)
        if preLevel >= self.level:
            ConsoleController.windowPrintInfo(self.loggername, mode, args)
        else:
            return

    def setLogLevel(self,level):
        if level is self.DEBUG:
            self.level = 0
        elif level is self.INFO:
            self.level = 1
        elif level is self.WARNING:
            self.level = 2
        elif level is self.ERROR:
            self.level = 3
        elif level is self.CRITICAL:
            self.level = 4

    def getCurLogLevel(self,level):
        if level is self.DEBUG:
            return 0
        elif level is self.INFO:
            return 1
        elif level is self.WARNING:
            return 2
        elif level is self.ERROR:
            return 3
        elif level is self.CRITICAL:
            return 4 class AboutWindow(BaseWindow):
    def __init__(self):
        super().__init__()
        super().initWindow()
        self.setupUi()
        self.show()
        # self.setWindowOpacity(0.8)

    def setupUi(self):
        self.initWindowTitle()
        self.initAboutTitle()
        self.initProduction()
        self.initGitAddress()
        self.initCompanyAddress()
        self.initVersionNumber()

    def initVersionNumber(self):
        self.versionNumber = QtWidgets.QLabel(self)
        self.versionNumber.setGeometry(QtCore.QRect(50, 230, 300, 21))
        self.versionNumber.setObjectName("label_4")
        self.versionNumber.setText("版本号：Release version v1.2") #版本号应该写到版本配置文件里面去，从哪里读取

    def initCompanyAddress(self):
        self.company = QtWidgets.QPushButton(self)
        self.company.setGeometry(50, 195, 300, 23)
        self.company.setStyleSheet("QPushButton{background: transparent; color: blue}")
        self.company.setObjectName("pushButton")
        self.company.clicked.connect(self.openCompanyUrl)
        self.company.setText("https://www.starcor.com/ch/index.html")

    def initGitAddress(self):
        self.gitAddress = QtWidgets.QPushButton(self)
        self.gitAddress.setGeometry(QtCore.QRect(50, 160, 300, 50))
        self.gitAddress.setStyleSheet("QPushButton{background: transparent; color: blue; text-align: left}")
        self.gitAddress.setLayoutDirection(Qt.LayoutDirectionAuto)
        self.gitAddress.setObjectName("label_3")
        self.gitAddress.clicked.connect(self.openGitUrl)
        self.gitAddress.setText("https://github.com/starcor-company/XulDebugTool")

    def initProduction(self):
        self.production = QLabel(self)
        self.production.setGeometry(50, 125, 300, 23 * 2)
        self.production.setWordWrap(True)
        self.production.setText("Copyright (c) 2017, 北京视达科科技有限责任公司")

    def initAboutTitle(self):
        self.aboutTitle = QtWidgets.QLabel(self)
        self.aboutTitle.setGeometry(QtCore.QRect(0, 18, 400, 100))
        self.aboutTitle.setStyleSheet("QLabel{background: black; color: white;}")
        font = QFont()
        font.setPointSize(32)
        self.aboutTitle.setAlignment(Qt.AlignCenter)
        self.aboutTitle.setFont(font)
        self.aboutTitle.setObjectName("label_2")
        self.aboutTitle.setText("XulDebugTool")

    def initWindowTitle(self):
        self.setWindowFlags(Qt.WindowCloseButtonHint)
        self.setFixedSize(400, 300)
        self.setStyleSheet("QMainWindow{border-color: black; background: white;}")
        self.setWindowTitle("关于")

    def openCompanyUrl(self):
        webbrowser.open("https://www.starcor.com/ch/index.html")

    def openGitUrl(self):
        webbrowser.open("https://github.com/starcor-company/XulDebugTool") class BaseWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'XulDebugTool'

    def initWindow(self):
        self.setWindowTitle(self.title)
        self.setWindowIcon(IconTool.buildQIcon('icon.png'))
        self.center()

    # 设置窗口居中
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft()) class ButtomWindow(QTabWidget):
    def __init__(self, parent=None):
        super(ButtomWindow, self).__init__(parent)
        self.initUi()


    def initUi(self):
        self.tabBar = QTabBar()
        self.consoleView = ConsoleWindow()
        self.tabBar.tabBarClicked.connect(self.status)
        self.tabBar.setExpanding(False)
        self.setTabBar(self.tabBar)
        self.addTab(self.consoleView,IconTool.buildQIcon('logcat.png'), "Logcat")
        self.consoleView.setVisible(False)
        self.setFixedHeight(Utils.getItemHeight())
        self.setTabPosition(QTabWidget.South)
        self.setStyleSheet("QTabBar::tab {border: none; height: "+str(Utils.getItemHeight())+"px; width:100px;color:black;}"
                            "QTabBar::tab:selected { border: none;background: lightgray; } ")

    def status(self):
      if self.tabBar.tabText(self.tabBar.currentIndex()) == 'Logcat':
        if self.consoleView.isVisible():
          self.consoleView.setVisible(False)
          self.preHeight = self.width()
          self.setFixedHeight(Utils.getItemHeight())
        else:
          self.consoleView.setVisible(True)
          self.setMaximumHeight(Utils.getWindowHeight()) class DataQueryDialog(BaseDialog):
    finishSignal = pyqtSignal(str)

    def __init__(self, data):
        self.modes = []
        self.currentRowCount = 0
        if isinstance(data,dict):
            self.data = data
            self.providerId = self.data['@name']
            self.url = ''
            self.providerName = self.data['ds']['@providerClass']
            super().__init__(self.providerName)
            self.initWindow()
            self.url = XulDebugServerHelper.HOST + MODES[
                self.modeComboBox.currentText().lower()] + '/' + self.providerId + '?'
            self.requestLineEdit.setText(self.url)
        else:
            self.data  = data
            self.providerId = ((data.url.rsplit('/',1))[1].split('?',1))[0]
            self.providerName = data.name
            self.url = data.url
            super().__init__(self.providerName)
            self.initWindow()
            self.requestLineEdit.setText(self.url)

    def initWindow(self):
        super().initWindow()
        self.setFixedSize(466, 256)
        self.setWindowModality(QtCore.Qt.ApplicationModal)

        self.requestLineEdit = QtWidgets.QLineEdit(self)
        self.requestLineEdit.move(36, 15)
        self.requestLineEdit.resize(300, Utils.getItemHeight())

        self.modeLable = QtWidgets.QLabel(self)
        self.modeLable.move(36, 50)
        self.modeLable.resize(130, Utils.getItemHeight())
        self.modeLable.setText('Mode:')

        self.modeComboBox = QtWidgets.QComboBox(self)
        self.modeComboBox.move(187, 50)
        self.modeComboBox.resize(150, Utils.getItemHeight())
        self.modeComboBox.setEditable(False)

        # 查询的mode应该从项目支持的mode获取
        # 但是因为各个项目的provider写的不标准
        # 所以这里统一固定这些方式,不是所有的provider都支持这6种
        # self.modes = self.data['ds']['@mode'].split('|')
        self.modes = MODES
        for model in self.modes.keys():
            self.modeComboBox.addItem(model)

        self.parseUrl2Mode(self.url)
        self.modeComboBox.setMaxVisibleItems(5)
        self.modeComboBox.currentTextChanged.connect(self.onModeChanged)

        self.requestButton = QtWidgets.QPushButton(self)
        self.requestButton.move(350, 15)
        self.requestButton.resize(90, Utils.getItemHeight())
        self.requestButton.setText('Request')
        self.requestButton.clicked.connect(self.onBtnClicked)

        self.initTableView(self.url)

    def initTableView(self,url):
        row = 1;
        entrys = []
        if url != '' and url != None:
            entrys=url.split('?',1)[1].split('&')
            for element in entrys:
                if element != '' and element != None:
                    row += 1

        self.tableView = QtWidgets.QTableWidget(row,2,self)
        self.tableView.move(36, 3*Utils.getItemHeight())
        self.tableView.resize(300, Utils.getItemHeight() * (row+1))
        self.tableView.setColumnWidth(0, 150)
        self.tableView.setColumnWidth(1, 150)
        self.tableView.horizontalHeader().setFixedHeight(Utils.getItemHeight())
        self.tableView.horizontalHeader().setStyleSheet("QHeaderView::section{background:lightblue;}");
        self.tableView.verticalHeader().setDefaultSectionSize(Utils.getItemHeight())
        self.tableView.setAlternatingRowColors(True)
        self.tableView.setHorizontalHeaderLabels(['where', 'is'])
        self.tableView.setFrameStyle(QtWidgets.QTableWidget.NoFrame)
        self.tableView.setShowGrid(True)
        self.tableView.verticalHeader().setVisible(False)
        self.tableView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        for i, entry in enumerate(entrys):
            if entry != '' and entry != None:
                querylist = entry.split('=')
                self.tableView.setItem(i, 0, QtWidgets.QTableWidgetItem(querylist[0]))
                self.tableView.setItem(i, 1, QtWidgets.QTableWidgetItem(querylist[1]))

        # fill data
        # 初始化查询条件表,预留一行空数据
        for j in range(self.tableView.columnCount()):
            newItem = QtWidgets.QTableWidgetItem('')
            self.tableView.setItem(self.tableView.rowCount()-1, j, newItem)

        self.tableView.cellChanged.connect(self.onCellChanged)


    def parseUrl2Mode(self,url):
        if url != '' and url != None:
            mode = url.rsplit('/', 2)[1].split('-')[0]
            self.modeComboBox.setCurrentText(mode)
        else:
            self.modeComboBox.setCurrentText('query')


    def onModeChanged(self):
        self.url = XulDebugServerHelper.HOST + MODES[self.modeComboBox.currentText().lower()] \
                   + '/' + self.providerId + '?' + self.__getQueryParam()
        self.requestLineEdit.setText(self.url)

    def onCellChanged(self):
        # 当单元格变化的时候检测需不需要新增一行
        item = self.tableView.currentItem()
        if item.text():
            if item.column() == 0:
                brother = self.tableView.item(self.currentRowCount, 1)
            else:
                brother = self.tableView.item(self.currentRowCount, 0)
            # 当前节点和兄弟节点都有值的时候新增一行
            if brother and brother.text():
                self.currentRowCount += 1
                row = self.tableView.rowCount()
                self.tableView.insertRow(row)
                self.tableView.setItem(row, 0, QtWidgets.QTableWidgetItem())
                self.tableView.setItem(row, 1, QtWidgets.QTableWidgetItem())
                # 加上表头,不超过7行,超过滚动条显示
                if (self.currentRowCount + 2) <= 7:
                    self.tableView.resize(300, Utils.getItemHeight() * (self.currentRowCount + 2))
                else:
                    self.tableView.resize(322, Utils.getItemHeight() * 7)
        url = self.url + self.__getQueryParam()
        self.requestLineEdit.setText(url)

    def onBtnClicked(self):
        self.url = XulDebugServerHelper.HOST + MODES[self.modeComboBox.currentText().lower()] \
                   + '/' + self.providerId + '?' + self.__getQueryParam()
        self.treeViewDataRefresh()
        self.finishSignal.emit(self.url)
        self.close()

    def treeViewDataRefresh(self):
        dateTime = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(time.time()))

        #用左侧的model树来查询的时候
        if isinstance(self.data, dict):
            FavoriteDB.insertHistory(self.providerName,self.url,dateTime,0)
            STCLogger().i('dataQuery record is insert to DataBase of history: ' + self.url)
            return

        #用收藏功能里面的记录查询
        if self.data.type:
            if self.data.type == 'favorites_type':#更新收藏记录的时候要先更新历史记录，在更新收藏记录时将最新的历史记录和收藏记录关联起来

                FavoriteDB.insertHistory(self.providerName, self.url,dateTime, 1)
                STCLogger().i('dataQuery record is insert to DataBase of history :' + self.url)
                rows = FavoriteDB.selectBySQL('select max(id) from '+ FavoriteDB.TABLE_HISTORY)
                for row in rows:
                    historyMaxId = row[0]
                FavoriteDB.updateFavorites('and id = '+ str(self.data.id), name = self.providerName,url = self.url,date = dateTime,history_id = historyMaxId)
                FavoriteDB.updateHistory('and id = '+str(self.data.historyId), favorite = 0)
                STCLogger().i('dataQuery record is update DataBase of favorites :' + self.url)
            elif self.data.type == 'history_type':
                FavoriteDB.insertHistory(self.providerName, self.url,dateTime, 0)
                STCLogger().i('dataQuery record is insert to DataBase of history :' + self.url)



    def __getQueryParam(self):
        # 获取所有查询条件,并组装成查询参数
        param = ''
        queryClause = {}
        for i in range(self.tableView.rowCount()):
            for j in range(self.tableView.columnCount()):
                item = self.tableView.item(i, j)
                if item:
                    if j == 0:
                        whereClause = item.text()
                    else:
                        isClause = item.text()
            if whereClause and isClause:
                queryClause[whereClause] = isClause
        for k, v in queryClause.items():
            param += (k + '=' + v + '&')
        param = param.rsplit('&',1)[0]
        return param

    def setData(self, data):
        self.modes = data['ds']['@mode'].split('|')
        for model in self.modes:
            self.modeComboBox.addItem(model)
        self.providerId = data['@name']
        self.url = XulDebugServerHelper.HOST + self.modeComboBox.currentText() + '/' + self.providerId + '?'
        self.requestLineEdit.setText(self.url) class FavoriteTreeView(QTreeView):
    def __init__(self,window, parent=None):
        self.mainWindow = window
        try:
            super(FavoriteTreeView,self).__init__(parent)
            self.treeModel = QStandardItemModel()
            self.favorites = QStandardItem(ROOT_FAVORITES)
            self.buildFavoritesTree()
            self.providerQueryHistory = QStandardItem(ROOT_PROVIDERQUERYHISTORY)
            self.buildQueryHistory()
            self.treeModel.appendColumn([self.favorites,self.providerQueryHistory])
            self.treeModel.setHeaderData(0, Qt.Horizontal, 'Record')

            self.setModel(self.treeModel)
            self.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.setContextMenuPolicy(Qt.CustomContextMenu)
            self.customContextMenuRequested.connect(self.openContextMenu)
            self.doubleClicked.connect(self.onTreeItemDoubleClicked)
            self.setSelectionBehavior(QAbstractItemView.SelectItems)
            # 设置该控件可以多选
            self.setSelectionMode(QAbstractItemView.ExtendedSelection)
            # self.clicked.connect(self.clickState)
        except Exception as e:
            STCLogger().e(e)

    def buildFavoritesTree(self):
        self.favorites.removeRows(0,self.favorites.rowCount())
        rows = FavoriteDB.selectFavorites(" order by name asc")
        for row in rows:
            providerItem = QStandardItem(row[1] + "   " + row[3])
            providerItem.type = ITEM_TYPE_FAVORITES
            providerItem.id = row[0]
            providerItem.name = row[1]
            providerItem.url = row[2]
            providerItem.date = row[3]
            providerItem.historyId = row[4]
            urlItem = QStandardItem(row[2])
            urlItem.type = ITEM_TYPE_URL
            providerItem.appendRow(urlItem)
            self.favorites.appendRow(providerItem)

    def buildQueryHistory(self):
        self.providerQueryHistory.removeRows(0,self.providerQueryHistory.rowCount())
        rows = FavoriteDB.selectHistory('order by date desc')
        for row in rows:
            providerItem = QStandardItem(row[1]+"   "+row[3])
            providerItem.type = ITEM_TYPE_HISTORY
            providerItem.id = row[0]
            providerItem.name = row[1]
            providerItem.url = row[2]
            providerItem.date = row[3]
            providerItem.favorite = row[4]
            urlItem = QStandardItem(row[2])
            urlItem.type = ITEM_TYPE_URL
            providerItem.appendRow(urlItem)
            self.providerQueryHistory.appendRow(providerItem)


    @pyqtSlot(QModelIndex)
    def onTreeItemDoubleClicked(self, index):
        item = self.treeModel.itemFromIndex(index)
        dateTime = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(time.time()))
        if item.type == ITEM_TYPE_FAVORITES :#更新收藏记录的时候要先更新历史记录，在更新收藏记录时将最新的历史记录和收藏记录关联起来
            FavoriteDB.insertHistory(item.name, item.url,dateTime, 1)
            rows = FavoriteDB.selectBySQL('select max(id) from ' + FavoriteDB.TABLE_HISTORY)
            for row in rows:
                historyMaxId = row[0]

            FavoriteDB.updateFavorites('and id = '+ str(item.id), name = item.name,url = item.url,date = dateTime, history_id=historyMaxId)
            FavoriteDB.updateHistory('and id = ' + str(item.historyId), favorite=1)
            self.mainWindow.onGetQueryUrl(item.url)
        elif item.type == ITEM_TYPE_HISTORY:
            FavoriteDB.insertHistory(item.name, item.url, dateTime, 0)
            self.mainWindow.onGetQueryUrl(item.url)

    @pyqtSlot(QPoint)
    def openContextMenu(self,point):
        list = self.selectedIndexes()
        if len(list) > 1:
            self.menuBatchOperation(list)
        elif len(list) == 1:
            self.menuOperation(point)

    def menuOperation(self,point):
        index = self.indexAt(point)
        if not index.isValid():
            return
        item = self.treeModel.itemFromIndex(index)
        menu = QMenu()

        if item.type == ITEM_TYPE_HISTORY:
            queryAction = QAction(IconTool.buildQIcon('data.png'), '&Edit ...', self,triggered=lambda: self.showQueryDialog(item))
            queryAction.setShortcut('Alt+E')
            menu.addAction(queryAction)

            favoritesAction = QAction(IconTool.buildQIcon('star.png'), 'Add to &favorites', self,triggered=lambda: self.add2Favorites(item))
            favoritesAction.setShortcut('Alt+F')
            menu.addAction(favoritesAction)

            deleteAction = QAction(IconTool.buildQIcon('clear.png'), '&Delete', self,triggered=lambda: self.deleteHistory(item))
            deleteAction.setShortcut('Ctrl+D')
            menu.addAction(deleteAction)

        if item.type == ITEM_TYPE_FAVORITES:
            queryAction = QAction(IconTool.buildQIcon('data.png'), '&Edit ...', self,triggered=lambda: self.showQueryDialog(item))
            queryAction.setShortcut('Alt+E')
            menu.addAction(queryAction)

            disFavoritesAction = QAction(IconTool.buildQIcon('remove_favorites.png'), 'Remove from &favorites', self,triggered=lambda: self.remove2Favorites(item))
            disFavoritesAction.setShortcut('Alt+F')
            menu.addAction(disFavoritesAction)

            deleteAction = QAction(IconTool.buildQIcon('clear.png'), '&Delete', self,triggered=lambda: self.deleteFavorite(item))
            deleteAction.setShortcut('Ctrl+D')
            menu.addAction(deleteAction)

        if item.type == ITEM_TYPE_URL:
            copyAction = QAction(IconTool.buildQIcon('copy.png'), 'Copy', self,triggered=lambda: pyperclip.copy('%s' % index.data()))
            copyAction.setShortcut('Ctrl+C')
            menu.addAction(copyAction)

        menu.exec_(self.viewport().mapToGlobal(point))

    def menuBatchOperation(self,list):
        itemList = []
        #标记本次批量操作所有记录的类别是否一致，如果不一致就不进行右键批量操作
        itemTpye = None;
        for modelIndex in list:
            item = self.treeModel.itemFromIndex(modelIndex)
            if itemTpye != None:
                if itemTpye != item.type:
                    return
            itemTpye = item.type
            itemList.append(item)

        menu = QMenu()
        if itemTpye == ITEM_TYPE_HISTORY:
            deleteAction = QAction(IconTool.buildQIcon('clear.png'), '&Delete', self,triggered=lambda: self.deleteHistoryBatch(itemList))
            deleteAction.setShortcut('Ctrl+D')
            menu.addAction(deleteAction)

        if itemTpye == ITEM_TYPE_FAVORITES:
            deleteAction = QAction(IconTool.buildQIcon('clear.png'), '&Delete', self,triggered=lambda: self.deleteFavoritesBatch(itemList))
            deleteAction.setShortcut('Ctrl+D')
            menu.addAction(deleteAction)

        menu.exec_(QCursor.pos())

    def showQueryDialog(self,item):
        self.dialog = DataQueryDialog(item)
        self.dialog.finishSignal.connect(self.mainWindow.onGetQueryUrl)
        self.dialog.show()
        STCLogger().i('show queryDataDialog' )

    def add2Favorites(self,item):
        if item.type == ITEM_TYPE_HISTORY:
            dateTime = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(time.time()))
            FavoriteDB.insertFavorites(item.name,item.url,dateTime,item.id)
            STCLogger().i('the history record add to DataBase of favorites :' + item.url)
            self.updateTree()

    def deleteFavorite(self,item):
        if item.type == ITEM_TYPE_FAVORITES:
            FavoriteDB.deleteFavorites('and id = ' + str(item.id))
            FavoriteDB.deleteHistory(' and id = '+ str(item.historyId))
            STCLogger().i('this record delete from DataBase:' + item.url)
            self.updateTree()

    def deleteFavoritesBatch(self,list):
        FavoriteDB.deleteFavoritesBatch(list)
        STCLogger().i('A batch of favorite records was deleted')
        self.updateTree()

    def deleteHistory(self,item):
        if item.type == ITEM_TYPE_HISTORY:
            FavoriteDB.deleteHistory('and id = '+str(item.id))
            STCLogger().i('this record delete from DataBase:' + item.url)
            self.updateTree()

    def deleteHistoryBatch(self,list):
        FavoriteDB.deleteHistoryBatch(list)
        STCLogger().i('A batch of historical records was deleted')
        self.updateTree()

    def remove2Favorites(self,item):
        if item.type == ITEM_TYPE_FAVORITES:
            FavoriteDB.deleteFavorites('and id = '+str(item.id))
            STCLogger().i('this record remove from DataBase of favorites:' + item.url)
            self.updateTree()

    def updateTree(self):
        self.buildFavoritesTree()
        self.buildQueryHistory() class PropertyEditor(QTreeView):
    def __init__(self, headerList=['Key', 'Value'], parent=None):
        super(PropertyEditor, self).__init__(parent)
        self.model = PropertyModel(self)
        self.setModel(self.model)
        self.model.setHeaderData(headerList)

    def addProperty(self, p):
        self.model.addProperty(p)
        self.expandToDepth(0)

    def clearProperty(self):
        self.model.clear() class UpdateProperty(QTreeWidget):
    def __init__(self, parent=None):
        super(UpdateProperty, self).__init__(parent)
        self.data = None
        self.viewId = ''
        self.sameFlag = True
        self.viewTag = ''
        self.pageId = ''
        self.inputWidget = QTreeWidget(self)
        self.inputWidget.setFixedHeight(Utils.getWindowHeight() * 0.83)
        self.inputWidget.setFixedWidth(Utils.getWindowWidth() / 3)
        self.inputWidget.setStyleSheet("QTreeWidget::item{height:" + str(Utils.getItemHeight()) + "px}")

        self.inputWidget.setHeaderLabels(['Key', 'Value'])

        self.inputAttr = QTreeWidgetItem()
        self.inputAttr.setText(0, 'Attr')
        self.inputAttr.setBackground(0, item_color)
        self.inputAttr.setBackground(1, item_color)
        self.inputStyle = QTreeWidgetItem()
        self.inputStyle.setText(0, 'Style')
        self.inputStyle.setBackground(0, item_color)
        self.inputStyle.setBackground(1, item_color)
        self.inputWidget.insertTopLevelItem(0, self.inputAttr)
        self.inputWidget.insertTopLevelItem(1, self.inputStyle)
        self.inputAttr.setExpanded(True)
        self.inputWidget.expanded.connect(self.changeExpand)
        self.inputWidget.collapsed.connect(self.changeExpand)
        self.initClassBox()

        self.listView = QListView(self)
        self.listView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.slm = QStringListModel()
        self.slm.setStringList(ITEM_EVENT)
        self.listView.setModel(self.slm)
        self.listView.move(30, 150)
        self.listView.resize(300, len(ITEM_EVENT) * Utils.getItemHeight())
        self.listView.clicked.connect(self.itemClickedEvent)
        STCLogger().i('init UpdateProperty')

    def inputString(self):
        STCLogger().i('input key = ')

    def changeExpand(self):
        classHeight = int(3.25 * Utils.getItemHeight())
        if self.inputAttr.isExpanded() and self.inputAttr.child(0):
            classHeight = classHeight + (ITEM_ATTR.__len__() + 1) * Utils.getItemHeight()
        if self.inputStyle.isExpanded() and self.inputAttr.child(0):
            classHeight = classHeight + (ITEM_STYLE.__len__() + 1) * Utils.getItemHeight()
        self.ClassBox_1.move(30, classHeight)
        self.ClassBox_2.move(150, classHeight)
        self.listView.move(30, classHeight + Utils.getItemHeight())

    def updateAttrUrl(self):
        num = 0
        for key, value in ITEM_ATTR.items():
            attr = self.inputAttr.child(num).text(1)
            if self.inputAttr.child(num).text(0) not in ITEM_ATTR:
                self.inputAttr.child(num).setText(0, list(ITEM_ATTR.keys())[num])
                QMessageBox.critical(self, "提示", self.tr("不能更改key值，请重新添加。"))
                return
            if attr != ITEM_ATTR[self.inputAttr.child(num).text(0)]:
                ITEM_ATTR[key] = attr
                XulDebugServerHelper.updateUrl('set-attr', self.viewId, key, attr)
            num += 1
        self.updateAddProperty('set-attr', num, self.inputAttr)

    def updateStyleUrl(self):
        num2 = 0
        for key, value in ITEM_STYLE.items():
            style = self.inputStyle.child(num2).text(1)
            if self.inputStyle.child(num2).text(0) not in ITEM_STYLE:
                self.inputStyle.child(num2).setText(0, list(ITEM_STYLE.keys())[num2])
                QMessageBox.critical(self, "提示", self.tr("不能更改key值，请重新添加。"))
                return
            if style != ITEM_STYLE[self.inputStyle.child(num2).text(0)]:
                ITEM_STYLE[key] = style
                XulDebugServerHelper.updateUrl('set-style', self.viewId, key, style)
            num2 += 1
        self.updateAddProperty('set-style', num2, self.inputStyle)

    def updateAddProperty(self, type, num, root):
        if root.child(num) is None:
            return
        item = root.child(num)
        if str(item.text(0)) == '' or str(item.text(1)) == '':
            return
        if type == 'set-attr':
            for key, value in ITEM_ATTR.items():
                if (key == str(item.text(0)) or str(item.text(0)) not in ATTR_AREA) and not str(item.text(0)).startswith("img"):
                    if str(item.text(0)) in STYLE_AREA:
                        QMessageBox.critical(self, "提示", self.tr("您输入的为style属性，请在style栏内输入。"))
                    item.setText(0, '')
                    item.setText(1, '')
                    return
            ITEM_ATTR.setdefault(str(item.text(0)), str(item.text(1)))
        elif type == 'set-style':
            for key, value in ITEM_STYLE.items():
                if key == str(item.text(0)) or str(item.text(0)) not in STYLE_AREA:
                    if str(item.text(0)) in ATTR_AREA:
                        QMessageBox.critical(self, "提示", self.tr("您输入的为attr属性，请在attr栏内输入。"))
                    item.setText(0, '')
                    item.setText(1, '')
                    return
            ITEM_STYLE.setdefault(str(item.text(0)), str(item.text(1)))

        result = XulDebugServerHelper.updateUrl(type, self.viewId, item.text(0), item.text(1))
        if result is None or result.status != 200:
            return
        STCLogger().i('updateAddProperty:' + item.text(0) + ',' + item.text(1))
        self.addQTreeWidgetItem(root)

    def updateItemUI(self):
        if self.sameFlag:
            return
        for pos1, item1 in enumerate(ITEM_ATTR.items()):
            item = self.getQTreeWidgetItem(pos1, item1[0], item1[1])
            self.inputAttr.addChild(item)
        for pos2, item2 in enumerate(ITEM_STYLE.items()):
            item = self.getQTreeWidgetItem(pos2, item2[0], item2[1])
            self.inputStyle.addChild(item)
        if self.viewTag in ITEM_TAG:
            self.addQTreeWidgetItem(self.inputAttr)
            self.addQTreeWidgetItem(self.inputStyle)

        self.inputWidget.itemChanged.connect(self.updateAttrUrl)
        self.inputWidget.itemChanged.connect(self.updateStyleUrl)
        self.changeExpand()

        self.slm.setStringList(ITEM_EVENT)
        self.listView.setModel(self.slm)
        self.listView.resize(300, len(ITEM_EVENT) * 30)

    def itemClickedEvent(self, qModelIndex):
        print("click " + ITEM_EVENT[qModelIndex.row()])
        XulDebugServerHelper.fireItemEvent(ITEM_EVENT[qModelIndex.row()], self.viewId)

    def getQTreeWidgetItem(self, pos, key, value):
        item = QTreeWidgetItem()
        item.setText(0, key)
        item.setText(1, value)
        if pos % 2 == 1:
            item.setBackground(0, property_color_one)
            item.setBackground(1, property_color_one)
        else:
            item.setBackground(0, property_color_two)
            item.setBackground(1, property_color_two)
        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsUserCheckable)
        return item

    def addQTreeWidgetItem(self, root):
        addItem = QTreeWidgetItem()
        addItem.setIcon(0, IconTool.buildQIcon('add.png'))
        addItem.setText(0, '')
        addItem.setText(1, '')
        addItem.setBackground(0, add_color)
        addItem.setBackground(1, add_color)
        addItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable)
        root.addChild(addItem)
        self.changeExpand()

    def initData(self, pageId, data):
        dict = json.loads(data)
        action = dict['action']
        if action == "click":
            id = dict['Id']
            xml = dict['xml']
            if id == self.viewId:
                self.sameFlag = True
            else:
                self.sameFlag = False
                ITEM_STYLE.clear()
                ITEM_ATTR.clear()
                self.inputAttr.takeChildren()
                self.inputStyle.takeChildren()
                self.viewId = id
            element = Utils.findNodeById(id, xml)
            self.viewTag = element.tag
            children = element.getchildren()
            ITEM_EVENT.clear()
            for item in children:
                if item.attrib is not None:
                    if item.tag == 'attr':
                        ITEM_ATTR.setdefault(item.attrib['name'], item.text)
                    if item.tag == 'style':
                        ITEM_STYLE.setdefault(item.attrib['name'], item.text)
                    if item.tag == 'action':
                        ITEM_EVENT.append(item.attrib['action'])
        self.initPageClassData(pageId)

    def initClassBox(self):
        self.ClassBox_1 = QComboBox(self)
        self.ClassBox_1.setEditable(False)
        self.ClassBox_1.setMaxVisibleItems(2)
        self.ClassBox_1.setInsertPolicy(QComboBox.InsertAtTop)
        self.ClassBox_1.addItem("add-class")
        self.ClassBox_1.addItem("remove-class")
        self.ClassBox_1.move(30, int(3.25 * Utils.getItemHeight()))
        self.ClassBox_1.resize(150, 30)

        self.ClassBox_2 = QComboBox(self)
        self.ClassBox_2.setEditable(False)
        self.ClassBox_2.move(150, int(3.25 * Utils.getItemHeight()))
        self.ClassBox_2.resize(200, 30)
        self.ClassBox_2.activated.connect(self.updateClass)
        ITEM_CLASS.clear()
        self.initAllClassData()

    def initAllClassData(self):
        all = XulDebugServerHelper.getAllSelector()
        if all.data:
            selector = Utils.xml2json(all.data, 'selector')
            if selector == '':
                return
            for select in selector['select']:
                if '@class' in select.keys() and select['@class'] not in ITEM_CLASS:
                    ITEM_CLASS.append(select['@class'])

    def initPageClassData(self, pageId):
        if self.pageId == pageId:
            return
        all = XulDebugServerHelper.getPageSelector(pageId)
        if all.data:
            page = Utils.xml2json(all.data, 'page')
            if page == '':
                return
            for item in page:
                if item == 'selector':
                    selector = page['selector']
                    if selector is None or 'select' not in selector.keys():
                        return
                    try:
                        for select in selector['select']:
                            if '@class' in select.keys() and select['@class'] not in ITEM_CLASS:
                                ITEM_CLASS.append(select['@class'])
                    except:
                        print("select exception!")

        for name in ITEM_CLASS:
            self.ClassBox_2.addItem(name)

    def updateClass(self):
        XulDebugServerHelper.updateClassUrl(self.ClassBox_1.currentText(), self.viewId, self.ClassBox_2.currentText()) class ConfigurationDB(QObject):

    @staticmethod
    def saveConfiguration(key ,value):
        if key == None or len(str(key))<1:
            return
        conn = sqlite3.connect('XulDebugTool.db')
        cursor = conn.execute("select count(*) from "+DBManager.TABLE_CONFIGURATION+" where config_key = '"+str(key)+"'");
        for row in cursor:
            count = row[0]
        if count > 0:
            conn.execute("update "+DBManager.TABLE_CONFIGURATION+" set config_value = '"+str(value)+"' where config_key = '"+str(key)+"'")
        else:
            conn.execute("insert into "+DBManager.TABLE_CONFIGURATION+" (config_key,config_value) values('"+str(key)+"','"+str(value)+"')")
        conn.commit()
        conn.close()

    @staticmethod
    def getConfiguration(key):
        if key == None or len(str(key))<1:
            return
        conn = sqlite3.connect('XulDebugTool.db')
        cursor = conn.execute("select * from " + DBManager.TABLE_CONFIGURATION + " where config_key = '" + str(key)+"'");
        result = ''
        for row in cursor:
            result = row[2]
        cursor.close()
        conn.close()
        return result class ConfigHelper(object):
    LOGCATPATH = ""

    #以下是配置信息所对应的key
    KEY_LOGCATPATH = 'logcatPath'

    @staticmethod
    def initLogConfigPath():
        ConfigHelper.LOGCATPATH = ConfigurationDB.getConfiguration(ConfigHelper.KEY_LOGCATPATH)
        if len(ConfigHelper.LOGCATPATH)<=0:
            ConfigHelper.LOGCATPATH = str(os.getcwd()) + "\logcat.txt"
            ConfigurationDB.saveConfiguration(ConfigHelper.KEY_LOGCATPATH,ConfigHelper.LOGCATPATH) class IconTool(object):
    def __init__(self):
        super().__init__()

    def buildQIcon(iconName):
        return QIcon(os.path.join('..', 'resources', 'images', iconName))

    def buildQPixmap(pixmapName):
        return QPixmap(os.path.join('..', 'resources', 'images', pixmapName)) class Utils(object):
    windowWidth = 1920
    windowHeight = 1080
    itemHeight = 30

    @staticmethod
    def xml2json(xml, tag):
        # 将xml的某个tag转化成json
        doc = xmltodict.parse(xml)[tag]
        if doc != None:
            str = json.dumps(dict(doc))
            return json.loads(str)
        else:
            return ''

    @staticmethod
    def scriptCreator(path, name, page):
        script = QWebEngineScript()
        f = open(path, 'r')
        script.setSourceCode(f.read())
        script.setInjectionPoint(QWebEngineScript.DocumentReady)
        script.setName(name)
        script.setWorldId(QWebEngineScript.MainWorld)
        page.scripts().insert(script)

    @staticmethod
    def findNodeById(id, xml):
        root = etree.fromstring(xml)
        # print(etree.tostring(root, pretty_print=True).decode('utf-8'))
        try:
            list = root.xpath("//*[@id=%s]" % id)
        except Exception as e:
            STCLogger().e(e)
        return list[0]

    @staticmethod
    def setWindowWidth(width):
        Utils.windowWidth = width

    @staticmethod
    def setWindowHeight(height):
        Utils.windowHeight = height
        Utils.itemHeight = int(Utils.windowHeight / 36.0)

    @staticmethod
    def getWindowWidth():
        return Utils.windowWidth

    @staticmethod
    def getWindowHeight():
        return Utils.windowHeight

    @staticmethod
    def getItemHeight():
        return Utils.itemHeight

    @staticmethod
    def setAutoLoginState(loginState):
        try:
            conn = sqlite3.connect('XulDebugTool.db')
            cursor = conn.cursor()
            cursor.execute("delete from login")
            cursor.execute("insert into login (name) values ('" + str(loginState) + "')")
            conn.commit()
        except Exception as e:
            print(e)
        finally:
            cursor.close()
            conn.close()

    @staticmethod
    def getAutoLoginState():
        try:
            conn = sqlite3.connect('XulDebugTool.db')
            cursor = conn.cursor()
            cursor.execute('select * from login')
            result = cursor.fetchone()
        except Exception:
            return []
        finally:
            cursor.close()
            conn.close()
        return result class XulDebugServerHelper(object):
    HOST = ''
    __LIST_PAGE = 'list-pages'
    __GET_LAYOUT = 'get-layout'
    __LIST_USER_OBJECTS = 'list-user-objects'
    __GET_USER_OBJECT = 'get-user-object'
    __SET_ATTR = 'set-attr'
    __SET_STYLE = 'set-style'
    __ADD_CLASS = 'add-class'
    __REMOVE_CLASS = 'remove-class'
    __CLEAR_ALL_CACHES = 'clear-all-caches'
    __REQUEST_FOCUS = 'request-focus'
    __GET_SELECTOR = 'get-selector'
    __FIRE_EVENT = 'fire-event'

    @staticmethod
    def listPages():
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + XulDebugServerHelper.__LIST_PAGE
                http = urllib3.PoolManager()
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def getLayout(pageId, skipProp=True, withBindingData=True, withPosition=True, withSelector=True):
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + quote(XulDebugServerHelper.__GET_LAYOUT + '/' + pageId)
                http = urllib3.PoolManager()
                r = http.request('GET', url, fields={'skip-prop': skipProp,
                                         'with-binding-data': withBindingData,
                                         'with-position': withPosition,
                                         'with-selector': withSelector})
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def isXulDebugServerAlive():
        r = XulDebugServerHelper.listPages()
        if r:
            return r.status == 200
        else:
            return False

    @staticmethod
    def listUserObject():
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + XulDebugServerHelper.__LIST_USER_OBJECTS
                http = urllib3.PoolManager()
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def getUserObject(objectId):
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + quote(XulDebugServerHelper.__GET_USER_OBJECT + '/' + objectId)
                http = urllib3.PoolManager()
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def updateUrl(type, id, key, value):
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + quote(type + '/' + id + '/' + key + '/' + value)
                http = urllib3.PoolManager()
                STCLogger().i("updateUrl = " + url)
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def clearAllCaches():
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + XulDebugServerHelper.__CLEAR_ALL_CACHES
                http = urllib3.PoolManager()
                STCLogger().i("clearAllCaches = " + url)
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def focusChooseItemUrl(id):
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + XulDebugServerHelper.__REQUEST_FOCUS + '/' + id
                http = urllib3.PoolManager()
                STCLogger().i("focusChooseItemUrl = " + url)
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def getAllSelector():
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + XulDebugServerHelper.__GET_SELECTOR
                http = urllib3.PoolManager()
                STCLogger().i("getAllSelector = " + url)
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def getPageSelector(pageId):
        return XulDebugServerHelper.getLayout(pageId, False, False, False, True)

    @staticmethod
    def updateClassUrl(type, id, className):
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + quote(type + '/' + id + '/' + className)
                http = urllib3.PoolManager()
                STCLogger().i("updateClassUrl = " + url)
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return
            return r

    @staticmethod
    def fireItemEvent(action, id):
        if XulDebugServerHelper.HOST == '':
            raise ValueError('Host is empty!')
        else:
            try:
                url = XulDebugServerHelper.HOST + quote(XulDebugServerHelper.__FIRE_EVENT + '/' + id + '/' + action)
                http = urllib3.PoolManager()
                STCLogger().i("fireItemEvent = " + url)
                r = http.request('GET', url)
            except Exception as e:
                STCLogger().e(e)
                return r class WebShareObject(QWidget):
    jsCallback = pyqtSignal(str)
    def __init__(self):
        super(WebShareObject, self).__init__()

    def _getStrValue(self):
        return '100'

    def _setStrValue(self, value):
        self.jsCallback.emit(str(value))
        WebDataHandler().readData(value)

    strValue = pyqtProperty(str, fget=_getStrValue, fset=_setStrValue)
import os
import pyperclip
import json
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineScript, QWebEnginePage
from PyQt5.QtWidgets import *
from XulDebugTool.logcatapi.Logcat import STCLogger
from XulDebugTool.ui.AboutWindow import AboutWindow
from XulDebugTool.ui.BaseWindow import BaseWindow
from XulDebugTool.ui.widget.ButtomConsoleWindow import ButtomWindow
from XulDebugTool.ui.widget.DataQueryDialog import DataQueryDialog
from XulDebugTool.ui.widget.FavoriteTreeView import FavoriteTreeView
from XulDebugTool.ui.widget.PropertyEditor import PropertyEditor
from XulDebugTool.ui.widget.UpdateProperty import UpdateProperty
from XulDebugTool.ui.widget.model.database.ConfigurationDB import ConfigurationDB
from XulDebugTool.utils.ConfigHelper import ConfigHelper
from XulDebugTool.utils.IconTool import IconTool
from XulDebugTool.utils.Utils import Utils
from XulDebugTool.utils.XulDebugServerHelper import XulDebugServerHelper
from XulDebugTool.webprocess.WebShareObject import WebShareObject
        from XulDebugTool.ui.ConnectWindow import ConnectWindow  # 不应该在这里导入，但是放在前面会有问题

    def initSearchView(self):
        self.settings = QSettings('XulDebugTool')
        self.searchHistory = self.settings.value('searchHistory', [])

        self.searchWidget = QWidget()
        self.searchWidget.setStyleSheet(".QWidget{border:1px solid rgb(220, 220, 220)}")
        searchPageLayout = QHBoxLayout()
        self.searchLineEdit = QLineEdit()

        self.searchIcon = QAction(self)
        self.searchIcon.setIcon(IconTool.buildQIcon('find_h.png'))

        self.searchMenu = QMenu(self)
        for text in self.searchHistory:
            self.action = QAction(text, self, triggered=lambda: self.searchLineEdit.setText(text))
            self.searchMenu.addAction(self.action)
        self.searchIcon.setMenu(self.searchMenu)

        self.searchDelIcon = QAction(self)
        self.searchDelIcon.setIcon(IconTool.buildQIcon('del.png'))

        self.searchLineEdit.addAction(self.searchIcon, QLineEdit.LeadingPosition)
        self.searchLineEdit.addAction(self.searchDelIcon, QLineEdit.TrailingPosition)
        self.searchDelIcon.setVisible(False)
        self.searchLineEdit.setStyleSheet("border:2px groove gray;border-radius:10px;padding:2px 4px")

        searchPageLayout.addWidget(self.searchLineEdit)
        self.searchLineEdit.textChanged.connect(self.searchPage)
        self.searchLineEdit.editingFinished.connect(self.saveSearchHistory)
        self.searchDelIcon.triggered.connect(self.searchDelClick)
        self.previousBtn = QPushButton()
        self.previousBtn.setStyleSheet("background:transparent;")
        self.previousBtn.setIcon(IconTool.buildQIcon('up.png'))
        self.previousBtn.setFixedSize(15, 20)
        searchPageLayout.addWidget(self.previousBtn)
        self.previousBtn.clicked.connect(lambda: self.previousBtnClick(self.searchLineEdit.text()))
        self.nextBtn = QPushButton()
        self.nextBtn.setIcon(IconTool.buildQIcon('down.png'))
        self.nextBtn.setStyleSheet("background:transparent;")
        self.nextBtn.setFixedSize(15, 20)
        self.nextBtn.clicked.connect(lambda: self.nextBtnClick(self.searchLineEdit.text()))
        searchPageLayout.addWidget(self.nextBtn)
        self.matchCase = QCheckBox("Match Case")
        self.matchCase.setChecked(False)
        self.matchCase.stateChanged.connect(self.matchCaseChange)
        searchPageLayout.addWidget(self.matchCase)

        self.matchTips = QLabel()
        self.matchTips.setFixedWidth(100)
        self.searchClose = QPushButton("×")
        self.searchClose.setFixedWidth(10)
        self.searchClose.setStyleSheet("background:transparent;")
        self.searchClose.clicked.connect(self.searchCloseClick)
        searchPageLayout.addWidget(self.matchTips)
        searchPageLayout.addWidget(self.searchClose)
        self.searchWidget.setLayout(searchPageLayout)
        return self.searchWidget

    def clickCheckBox(self, checkBox, name):
        if checkBox.isChecked():
            STCLogger().i('select '+name)
            self.selectCheckBoxInfo(name)
        else:
            STCLogger().i('cancel '+name)
            self.cancelCheckBoxInfo(name)

    def selectCheckBoxInfo(self, str):
        if None != self.url:
            checkedStr = str + '=' + 'true'
            unCheckedStr = str + '=' + 'false'
            if self.url.find('?') == -1:
                self.url += '?'
                self.url += checkedStr
            else:
                if self.url.find(str) == -1:
                    self.url += '&'
                    self.url += checkedStr
                elif self.url.find(unCheckedStr) != -1:
                    self.url = self.url.replace(unCheckedStr, checkedStr)
            self.showXulDebugData(self.url)

    def cancelCheckBoxInfo(self, str):
        if None != self.url:
            checkedStr = str + '=' + 'true'
            if self.url.find(checkedStr) >= -1:
                split = self.url.split(checkedStr)
                self.url = ''.join(split)
                self.url = self.url.replace('&&', '&')
                self.url = self.url.replace('?&', '?')
                if self.url.endswith('?'):
                    self.url = self.url[:-1]
                if self.url.endswith('&'):
                    self.url = self.url[:-1]
                self.showXulDebugData(self.url)

    def rightSiderClick(self, index):
        # 两次单击同一个tabBar时显示隐藏内容区域
        if self.rightSiderTabBar.tabText(index) == self.rightSiderClickInfo:
            if self.rightSiderTabWidget.width() == Utils.getItemHeight():
                self.rightSiderTabWidget.setMaximumWidth(Utils.getWindowWidth())
                self.rightSiderTabWidget.setMinimumWidth(Utils.getItemHeight())
            else:
                self.rightSiderTabWidget.setFixedWidth(Utils.getItemHeight())
        else:
            if self.rightSiderTabWidget.width() == Utils.getItemHeight():
                self.rightSiderTabWidget.setMaximumWidth(Utils.getWindowWidth())
                self.rightSiderTabWidget.setMinimumWidth(Utils.getItemHeight())
        self.rightSiderClickInfo = self.rightSiderTabBar.tabText(index)

    def clearCache(self):
        r = XulDebugServerHelper.clearAllCaches()
        if r.status == 200:
            self.statusBar().showMessage('cache cleanup success')
        else:
            self.statusBar().showMessage('cache cleanup failed')

    def setLogPath(self):
        file_path = QFileDialog.getSaveFileName(self, 'save file', ConfigHelper.LOGCATPATH,"Txt files(*.txt)")
        if len(file_path[0]) > 0:

            ConfigurationDB.saveConfiguration(ConfigHelper.KEY_LOGCATPATH,file_path[0])