class LayerSelectionPage(QFrame):
    #TODO. Filtering, (visible) row selection, multi selection
    colparams = ((0, 65, 'Name'), (1, 235, 'Title'), (2, 350, 'Keywords'))
    XFER_BW = 40

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

        #convenience link
        self.confconn_link = self.parent.parent.confconn

        #flag top prevent read read action on keyword delete. New logic makes this redundant
        #self.keywordbypass = False

        QToolTip.setFont(QFont('SansSerif', 10))

        #label
        filterlabel = QLabel('Filter')
        availablelabel = QLabel('Available Layers')
        selectionlabel = QLabel('Layer Selections')
        keywordlabel = QLabel('Keyword')
        explainlabel = QLabel(
            "Edit Group assignments using this dialog or to simply initialise the Layer-Config just click 'Finish'"
        )

        #selection buttons
        chooseallbutton = QPushButton('>>')
        chooseallbutton.setFixedWidth(self.XFER_BW)
        chooseallbutton.clicked.connect(self.doChooseAllClickAction)

        choosebutton = QPushButton('>')
        choosebutton.setFixedWidth(self.XFER_BW)
        choosebutton.clicked.connect(self.doChooseClickAction)

        rejectbutton = QPushButton('<')
        rejectbutton.setFixedWidth(self.XFER_BW)
        rejectbutton.clicked.connect(self.doRejectClickAction)

        rejectallbutton = QPushButton('<<')
        rejectallbutton.setFixedWidth(self.XFER_BW)
        rejectallbutton.clicked.connect(self.doRejectAllClickAction)

        #operation buttons
        finishbutton = QPushButton('Finish')
        finishbutton.setToolTip('Finish and Close layer selection dialog')
        finishbutton.clicked.connect(self.parent.close)

        resetbutton = QPushButton('Reset')
        resetbutton.font()
        resetbutton.setToolTip(
            'Read Layer from LDS GetCapabilities request. Overwrites current Layer Config'
        )
        resetbutton.clicked.connect(self.doResetClickAction)

        self.available_sfpm = LDSSFPAvailableModel(self)
        self.selection_sfpm = LDSSFPSelectionModel(self)

        self.available_sfpm.setSourceModel(self.parent.available_model)
        self.selection_sfpm.setSourceModel(self.parent.selection_model)

        #textedits
        filteredit = QLineEdit('')
        filteredit.setToolTip(
            'Filter Available-Layers pane (filter operates across Name and Title fields and accepts Regex expressions)'
        )
        filteredit.textChanged.connect(self.available_sfpm.setActiveFilter)

        self.keywordcombo = QComboBox()
        self.keywordcombo.setToolTip(
            'Select or Add a unique identifier to be saved in layer config (keyword)'
        )
        self.keywordcombo.addItems(list(self.confconn_link.assigned))
        self.keywordcombo.setEditable(True)
        self.keywordcombo.activated.connect(self.doKeyComboChangeAction)

        lgindex = self.confconn_link.getLayerGroupIndex(
            self.confconn_link.lgval, col=1)
        lgentry = self.confconn_link.lglist[lgindex] if LU.assessNone(
            lgindex) else None
        #keywordedit = self.keywordcombo.lineEdit().text().toUtf8().data().decode('utf8')# for writing
        #if no entry or layer indicated then blank
        self.keywordcombo.lineEdit().setText(
            '' if lgentry is None or lgentry[0] == LORG.LAYER else
            lgentry[1])  #self.confconn_link.lgval)#TODO. group only

        #header
        headmodel = QStandardItemModel()
        headmodel.setHorizontalHeaderLabels([
            i[2] for i in self.colparams
        ][:self.parent.available_model.columnCount()])

        headview1 = QHeaderView(Qt.Horizontal)
        headview1.setModel(headmodel)
        headview1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        headview2 = QHeaderView(Qt.Horizontal)
        headview2.setModel(headmodel)
        headview2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        #table
        self.available = QTableView()
        self.available.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.available.setSelectionMode(QAbstractItemView.MultiSelection)

        self.selection = QTableView()
        self.selection.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.selection.setSelectionMode(QAbstractItemView.MultiSelection)

        #interesting, must set model after selection attributes but before headers else row selections/headers don't work properly
        self.available.setModel(self.available_sfpm)
        self.selection.setModel(self.selection_sfpm)

        self.available.setSortingEnabled(True)
        self.available.setHorizontalHeader(headview1)

        self.selection.setSortingEnabled(True)
        self.selection.setHorizontalHeader(headview2)

        for cp in self.colparams:
            self.available.setColumnWidth(cp[0], cp[1])
            self.selection.setColumnWidth(cp[0], cp[1])

        self.available.verticalHeader().setVisible(False)
        self.available.horizontalHeader().setVisible(True)

        self.selection.verticalHeader().setVisible(False)
        self.selection.horizontalHeader().setVisible(True)

        #layout
        vbox00 = QVBoxLayout()
        vbox00.addWidget(availablelabel)
        vbox00.addWidget(self.available)

        vbox01 = QVBoxLayout()
        vbox01.addWidget(chooseallbutton)
        vbox01.addWidget(choosebutton)
        vbox01.addWidget(rejectbutton)
        vbox01.addWidget(rejectallbutton)

        vbox02 = QVBoxLayout()
        vbox02.addWidget(selectionlabel)
        vbox02.addWidget(self.selection)

        vbox10 = QVBoxLayout()
        vbox10.addWidget(filterlabel)
        vbox10.addWidget(filteredit)

        hbox12 = QHBoxLayout()
        hbox12.addWidget(keywordlabel)
        hbox12.addStretch(1)
        #hbox12.addWidget(inspbutton)
        #hbox12.addWidget(addbutton)
        #hbox12.addWidget(delbutton)

        vbox12 = QVBoxLayout()
        vbox12.addLayout(hbox12)
        vbox12.addWidget(self.keywordcombo)

        #00|01|02
        #10|11|12
        grid0 = QGridLayout()
        grid0.addLayout(vbox00, 1, 0)
        grid0.addLayout(vbox01, 1, 1)
        grid0.addLayout(vbox02, 1, 2)
        grid0.addLayout(vbox10, 0, 0)
        grid0.addLayout(vbox12, 0, 2)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(resetbutton)
        hbox2.addStretch(1)
        hbox2.addWidget(explainlabel)
        hbox2.addWidget(finishbutton)
        #gbox1.setLayout(hbox2)

        vbox3 = QVBoxLayout()
        vbox3.addLayout(grid0)
        #vbox3.addLayout(hbox3)
        #vbox3.addWidget(line0)
        vbox3.addLayout(hbox2)

        self.setLayout(vbox3)

    def doChooseAllClickAction(self):
        '''Moves the lot to Selected'''
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(
            LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        if not self.checkKeyword(ktext): return
        #------------------------------
        self.parent.signalModels(self.parent.STEP.PRE)
        #self.parent.selection_model.mdata += self.parent.available_model.mdata
        self.parent.selection_model.initData(self.confconn_link.complete)
        self.parent.available_model.initData([])
        self.parent.signalModels(self.parent.STEP.POST)
        #------------------------------
        self.parent.writeKeysToLayerConfig(ktext)
        #self.confconn_link.setupAssignedLayerList()
        if self.keywordcombo.findText(ktext) == -1:
            self.keywordcombo.addItem(ktext)

    def doChooseClickAction(self):
        '''Takes available selected and moves to selection'''
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(
            LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        #ktext = str(self.keywordcombo.lineEdit().text())
        if not self.checkKeyword(ktext): return
        #------------------------------
        select = self.available.selectionModel()
        if select.hasSelection():
            self.transferSelectedRows(select.selectedRows(),
                                      self.available_sfpm, self.selection_sfpm)
            #------------------------------
            self.parent.writeKeysToLayerConfig(ktext)
            #self.confconn_link.assigned = self.confconn_link.setupAssignedLayerList()
            # -1 to indicate no index since 0,1,... are valid
            if self.keywordcombo.findText(ktext) == -1:
                self.keywordcombo.addItem(ktext)
        else:
            ldslog.warn('L2R > Transfer action without selection')
        #TRACE#
        #pdb.set_trace()
        self.available.clearSelection()

    def transferSelectedRows(self, indices, from_model, to_model):
        tlist = []
        for proxymodelindex in indices:
            transfer = from_model.getData(proxymodelindex)
            tlist.append((proxymodelindex, transfer), )

        to_model.addData([t[1] for t in tlist])
        from_model.delData([t[0] for t in tlist])
        return tlist

    def doRejectClickAction(self):
        '''Takes available selected and moves to selection'''
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(
            LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        if not self.checkKeyword(ktext): return
        #------------------------------
        select = self.selection.selectionModel()
        if select.hasSelection():
            tlist = self.transferSelectedRows(select.selectedRows(),
                                              self.selection_sfpm,
                                              self.available_sfpm)
            #------------------------------
            kindex = self.keywordcombo.findText(ktext)
            remainder = self.parent.deleteKeysFromLayerConfig(
                [ll[1][0] for ll in tlist], ktext)
            if remainder > 0 and kindex == -1:
                #items+newkey -> add
                self.parent.writeKeysToLayerConfig(ktext)
                self.keywordcombo.addItem(ktext)
            elif remainder == 0 and kindex > -1:
                #empty+oldkey -> del
                self.keywordcombo.removeItem(kindex)
                self.keywordcombo.clearEditText()
        else:
            ldslog.warn('R2L < Transfer action without selection')
        #TRACE#
        #pdb.set_trace()
        self.selection.clearSelection()

    def doRejectAllClickAction(self):
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(
            LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        if not self.checkKeyword(ktext): return
        #------------------------------
        self.parent.deleteKeysFromLayerConfig(
            [ll[0] for ll in self.parent.selection_model.mdata], ktext)
        #------------------------------
        self.parent.signalModels(self.parent.STEP.PRE)
        #self.parent.available_model.mdata += self.parent.selection_model.mdata
        self.parent.available_model.initData(self.confconn_link.complete)
        self.parent.selection_model.initData([])
        self.parent.signalModels(self.parent.STEP.POST)
        #------------------------------
        #self.confconn_link.setupAssignedLayerList()
        #self.keywordbypass = True
        self.keywordcombo.removeItem(self.keywordcombo.findText(ktext))
        self.keywordcombo.clearEditText()

    def doKeyComboChangeAction(self):
        '''Reset the available pane and if there is anything in the keyword box use this to init the selection pane'''
        #HACK
        #if self.keywordbypass:
        #    self.keywordbypass = False
        #    return
        #------------------------------
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(
            LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        #------------------------------
        av_sl = self.parent.splitData(ktext, self.confconn_link.complete)
        #av_sl = self.parent.splitData(ktext,self.confconn_link.complete)
        self.parent.signalModels(self.parent.STEP.PRE)
        self.parent.available_model.initData(av_sl[0])
        self.parent.selection_model.initData(av_sl[1])
        self.parent.signalModels(self.parent.STEP.POST)

    def doResetClickAction(self):
        '''Dumps the LC and rebuilds from a fresh read of the caps doc'''
        #int warning (QWidget parent, QString title, QString text, QString button0Text, QString button1Text = QString(), QString button2Text = QString(), int defaultButtonNumber = 0, int escapeButtonNumber = -1)
        ans = QMessageBox.warning(
            self, "Reset",
            "This action will overwrite your Layer Configuration using the current LDS settings (potentially adding new or removing layers). Continue?",
            "Continue", "Cancel")
        if ans:
            #Cancel
            ldslog.warn('Cancelling Reset operation')
            return
        #Continue
        ldslog.warn('Reset Layer Config')
        self.parent.resetLayers()
        self.keywordcombo.clear()

    def checkKeyword(self, ktext):
        '''Checks keyword isn't null and isn't part of the LDS supplied keywords'''
        if LU.assessNone(ktext) is None:
            QMessageBox.about(self, "Keyword Required",
                              "Please enter a Keyword to assign Layer(s) to")
            return False
        if ktext in self.confconn_link.reserved:
            QMessageBox.about(
                self, "Reserved Keyword",
                "'{}' is a reserved keyword, please select again".format(
                    ktext))
            return False
        return True
示例#2
0
class LayerSelectionPage(QFrame):
    #TODO. Filtering, (visible) row selection, multi selection
    colparams = ((0,65,'Name'), (1,235,'Title'), (2,350,'Keywords'))
    XFER_BW = 40
    def __init__(self, parent=None):
        super(LayerSelectionPage, self).__init__(parent)
        self.parent = parent
        
        #convenience link
        self.confconn_link = self.parent.parent.confconn
        
        #flag top prevent read read action on keyword delete. New logic makes this redundant
        #self.keywordbypass = False

        QToolTip.setFont(QFont('SansSerif', 10))
        
        #label
        filterlabel = QLabel('Filter')
        availablelabel = QLabel('Available Layers')
        selectionlabel = QLabel('Layer Selections')
        keywordlabel = QLabel('Keyword')
        explainlabel = QLabel("Edit Group assignments using this dialog or to simply initialise the Layer-Config just click 'Finish'")
        
        #selection buttons
        chooseallbutton = QPushButton('>>')
        chooseallbutton.setFixedWidth(self.XFER_BW)
        chooseallbutton.clicked.connect(self.doChooseAllClickAction)
        
        choosebutton = QPushButton('>')
        choosebutton.setFixedWidth(self.XFER_BW)
        choosebutton.clicked.connect(self.doChooseClickAction)
        
        rejectbutton = QPushButton('<')
        rejectbutton.setFixedWidth(self.XFER_BW)
        rejectbutton.clicked.connect(self.doRejectClickAction)
        
        rejectallbutton = QPushButton('<<')
        rejectallbutton.setFixedWidth(self.XFER_BW)
        rejectallbutton.clicked.connect(self.doRejectAllClickAction)
        
        #operation buttons        
        finishbutton = QPushButton('Finish')
        finishbutton.setToolTip('Finish and Close layer selection dialog')
        finishbutton.clicked.connect(self.parent.close)
        
        resetbutton = QPushButton('Reset')
        resetbutton.font()
        resetbutton.setToolTip('Read Layer from LDS GetCapabilities request. Overwrites current Layer Config')       
        resetbutton.clicked.connect(self.doResetClickAction)
        
        self.available_sfpm = LDSSFPAvailableModel(self)
        self.selection_sfpm = LDSSFPSelectionModel(self)
        
        self.available_sfpm.setSourceModel(self.parent.available_model)
        self.selection_sfpm.setSourceModel(self.parent.selection_model)
        
        #textedits
        filteredit = QLineEdit('')
        filteredit.setToolTip('Filter Available-Layers pane (filter operates across Name and Title fields and accepts Regex expressions)')       
        filteredit.textChanged.connect(self.available_sfpm.setActiveFilter)
        
        self.keywordcombo = QComboBox()
        self.keywordcombo.setToolTip('Select or Add a unique identifier to be saved in layer config (keyword)')
        self.keywordcombo.addItems(list(self.confconn_link.assigned))
        self.keywordcombo.setEditable(True)
        self.keywordcombo.activated.connect(self.doKeyComboChangeAction)
        
        lgindex = self.confconn_link.getLayerGroupIndex(self.confconn_link.lgval,col=1)
        lgentry = self.confconn_link.lglist[lgindex] if LU.assessNone(lgindex) else None
        #keywordedit = self.keywordcombo.lineEdit().text().toUtf8().data().decode('utf8')# for writing
        #if no entry or layer indicated then blank 
        self.keywordcombo.lineEdit().setText('' if lgentry is None or lgentry[0]==LORG.LAYER else lgentry[1])#self.confconn_link.lgval)#TODO. group only
        
        #header
        headmodel = QStandardItemModel()
        headmodel.setHorizontalHeaderLabels([i[2] for i in self.colparams][:self.parent.available_model.columnCount()])
        
        headview1 = QHeaderView(Qt.Horizontal)
        headview1.setModel(headmodel)
        headview1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) 
        
        headview2 = QHeaderView(Qt.Horizontal)
        headview2.setModel(headmodel)
        headview2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)            

        #table
        self.available = QTableView()
        self.available.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.available.setSelectionMode(QAbstractItemView.MultiSelection)       
        
        self.selection = QTableView()
        self.selection.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.selection.setSelectionMode(QAbstractItemView.MultiSelection)
        
        #interesting, must set model after selection attributes but before headers else row selections/headers don't work properly
        self.available.setModel(self.available_sfpm)
        self.selection.setModel(self.selection_sfpm)
        
        self.available.setSortingEnabled(True)
        self.available.setHorizontalHeader(headview1)
        
        self.selection.setSortingEnabled(True)
        self.selection.setHorizontalHeader(headview2)

        for cp in self.colparams:
            self.available.setColumnWidth(cp[0],cp[1])
            self.selection.setColumnWidth(cp[0],cp[1])

        self.available.verticalHeader().setVisible(False)
        self.available.horizontalHeader().setVisible(True)
        
        self.selection.verticalHeader().setVisible(False)
        self.selection.horizontalHeader().setVisible(True)
        
        
        #layout  
        vbox00 = QVBoxLayout()
        vbox00.addWidget(availablelabel)
        vbox00.addWidget(self.available)
        
        vbox01 = QVBoxLayout()
        vbox01.addWidget(chooseallbutton)
        vbox01.addWidget(choosebutton)
        vbox01.addWidget(rejectbutton)
        vbox01.addWidget(rejectallbutton)
        
        vbox02 = QVBoxLayout()
        vbox02.addWidget(selectionlabel)
        vbox02.addWidget(self.selection)

        
        vbox10 = QVBoxLayout()
        vbox10.addWidget(filterlabel)
        vbox10.addWidget(filteredit)
        
        hbox12 = QHBoxLayout()
        hbox12.addWidget(keywordlabel)
        hbox12.addStretch(1)
        #hbox12.addWidget(inspbutton)
        #hbox12.addWidget(addbutton)
        #hbox12.addWidget(delbutton)
        
        vbox12 = QVBoxLayout()
        vbox12.addLayout(hbox12)
        vbox12.addWidget(self.keywordcombo)
                
        #00|01|02
        #10|11|12
        grid0 = QGridLayout()
        grid0.addLayout(vbox00,1,0)
        grid0.addLayout(vbox01,1,1)
        grid0.addLayout(vbox02,1,2)
        grid0.addLayout(vbox10,0,0)
        grid0.addLayout(vbox12,0,2)
        
        
        hbox2 = QHBoxLayout()
        hbox2.addWidget(resetbutton)
        hbox2.addStretch(1)
        hbox2.addWidget(explainlabel)
        hbox2.addWidget(finishbutton)
        #gbox1.setLayout(hbox2)
        
        
        
        vbox3 = QVBoxLayout()
        vbox3.addLayout(grid0)
        #vbox3.addLayout(hbox3)
        #vbox3.addWidget(line0)
        vbox3.addLayout(hbox2)
        
        self.setLayout(vbox3)


            
    def doChooseAllClickAction(self):
        '''Moves the lot to Selected'''
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        if not self.checkKeyword(ktext): return
        #------------------------------
        self.parent.signalModels(self.parent.STEP.PRE)
        #self.parent.selection_model.mdata += self.parent.available_model.mdata
        self.parent.selection_model.initData(self.confconn_link.complete)
        self.parent.available_model.initData([])
        self.parent.signalModels(self.parent.STEP.POST)
        #------------------------------
        self.parent.writeKeysToLayerConfig(ktext)
        #self.confconn_link.setupAssignedLayerList()
        if self.keywordcombo.findText(ktext) == -1:
            self.keywordcombo.addItem(ktext)
    
    def doChooseClickAction(self):
        '''Takes available selected and moves to selection'''
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        #ktext = str(self.keywordcombo.lineEdit().text())
        if not self.checkKeyword(ktext): return
        #------------------------------
        select = self.available.selectionModel()
        if select.hasSelection():
            self.transferSelectedRows(select.selectedRows(),self.available_sfpm,self.selection_sfpm)
            #------------------------------
            self.parent.writeKeysToLayerConfig(ktext)
            #self.confconn_link.assigned = self.confconn_link.setupAssignedLayerList()
            # -1 to indicate no index since 0,1,... are valid
            if self.keywordcombo.findText(ktext) == -1:
                self.keywordcombo.addItem(ktext)
        else:
            ldslog.warn('L2R > Transfer action without selection')        
        #TRACE#
        #pdb.set_trace()
        self.available.clearSelection()
          
        
    def transferSelectedRows(self,indices,from_model,to_model):
        tlist = []
        for proxymodelindex in indices:
            transfer = from_model.getData(proxymodelindex)
            tlist.append((proxymodelindex,transfer),)

        to_model.addData([t[1] for t in tlist])
        from_model.delData([t[0] for t in tlist])
        return tlist
            
    def doRejectClickAction(self):
        '''Takes available selected and moves to selection'''
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        if not self.checkKeyword(ktext): return
        #------------------------------
        select = self.selection.selectionModel()
        if select.hasSelection():
            tlist = self.transferSelectedRows(select.selectedRows(),self.selection_sfpm,self.available_sfpm)
            #------------------------------
            kindex = self.keywordcombo.findText(ktext)
            remainder = self.parent.deleteKeysFromLayerConfig([ll[1][0] for ll in tlist],ktext)
            if remainder > 0 and kindex == -1:
                #items+newkey -> add
                self.parent.writeKeysToLayerConfig(ktext)
                self.keywordcombo.addItem(ktext)
            elif remainder == 0 and kindex > -1:
                #empty+oldkey -> del
                self.keywordcombo.removeItem(kindex)
                self.keywordcombo.clearEditText()
        else:
            ldslog.warn('R2L < Transfer action without selection')
        #TRACE#
        #pdb.set_trace()
        self.selection.clearSelection()

                
    def doRejectAllClickAction(self):
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        if not self.checkKeyword(ktext): return
        #------------------------------
        self.parent.deleteKeysFromLayerConfig([ll[0] for ll in self.parent.selection_model.mdata],ktext)
        #------------------------------
        self.parent.signalModels(self.parent.STEP.PRE)
        #self.parent.available_model.mdata += self.parent.selection_model.mdata
        self.parent.available_model.initData(self.confconn_link.complete)
        self.parent.selection_model.initData([])
        self.parent.signalModels(self.parent.STEP.POST)        
        #------------------------------
        #self.confconn_link.setupAssignedLayerList()
        #self.keywordbypass = True
        self.keywordcombo.removeItem(self.keywordcombo.findText(ktext))
        self.keywordcombo.clearEditText()
        
    def doKeyComboChangeAction(self):
        '''Reset the available pane and if there is anything in the keyword box use this to init the selection pane'''
        #HACK
        #if self.keywordbypass:
        #    self.keywordbypass = False
        #    return
        #------------------------------
        #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data())
        ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text()))
        #------------------------------
        av_sl = self.parent.splitData(ktext,self.confconn_link.complete)
        #av_sl = self.parent.splitData(ktext,self.confconn_link.complete)
        self.parent.signalModels(self.parent.STEP.PRE)
        self.parent.available_model.initData(av_sl[0])
        self.parent.selection_model.initData(av_sl[1])
        self.parent.signalModels(self.parent.STEP.POST)
    
    def doResetClickAction(self):
        '''Dumps the LC and rebuilds from a fresh read of the caps doc'''
        #int warning (QWidget parent, QString title, QString text, QString button0Text, QString button1Text = QString(), QString button2Text = QString(), int defaultButtonNumber = 0, int escapeButtonNumber = -1)
        ans = QMessageBox.warning(self, "Reset","This action will overwrite your Layer Configuration using the current LDS settings (potentially adding new or removing layers). Continue?","Continue","Cancel")
        if ans:
            #Cancel
            ldslog.warn('Cancelling Reset operation')
            return
        #Continue
        ldslog.warn('Reset Layer Config')
        self.parent.resetLayers()
        self.keywordcombo.clear()

    def checkKeyword(self,ktext):
        '''Checks keyword isn't null and isn't part of the LDS supplied keywords'''
        if LU.assessNone(ktext) is None:
            QMessageBox.about(self, "Keyword Required","Please enter a Keyword to assign Layer(s) to")
            return False
        if ktext in self.confconn_link.reserved:
            QMessageBox.about(self, "Reserved Keyword","'{}' is a reserved keyword, please select again".format(ktext))
            return False
        return True
class FindReplace(QWidget):
    """
    Find replace widget bar
    """
    NbReplaced = pyqtSignal(int)

    def __init__(self, parent=None):
        """
        This class provides an graphical interface to find and replace text

        @param parent: 
        @type parent:
        """
        QWidget.__init__(self, parent)
        self.editor = None
        self.styleEdit = {
            False: "background-color:rgb(255, 175, 90);",
            True: ""
        }

        self.createButton()
        self.createWidgets()
        self.createConnections()

    def showEnhanced(self, textSelected=''):
        """
        Show enhanced (focus and text selected)
        """
        self.show()
        if len(textSelected): self.edit.setEditText(textSelected)
        self.edit.setFocus()
        self.edit.lineEdit().selectAll()

    def createButton(self):
        """
        create qt buttons
        Buttons defined:
         * Previous
         * Next
         * Replace
        """
        self.previousButton = QtHelper.createButton(
            self,
            text=self.tr("Find Previous"),
            triggered=self.findPrevious,
            icon=QIcon(":/find_previous.png"))
        self.nextButton = QtHelper.createButton(self,
                                                text=self.tr("Find Next"),
                                                triggered=self.findNext,
                                                icon=QIcon(":/find_next.png"))
        self.replaceButton = QtHelper.createButton(self,
                                                   text=self.tr("Replace..."),
                                                   triggered=self.replaceFind,
                                                   icon=QIcon(":/replace.png"))

    def createWidgets(self):
        """
        QtWidgets creation

        QHBoxLayout
         -------------------------------------------.....
        | QLabel: QLineEdit QButton QButton QCheckBox |
         -------------------------------------------.....

        ....--------------------------------------
             QLabel: QLineEdit QButton QCheckBox |
        ....--------------------------------------
        """
        glayout = QGridLayout()

        self.edit = QLineEditMore(parent=self)
        self.edit.setEditable(1)
        self.edit.setMaxCount(10)
        self.edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.edit.lineEdit().setPlaceholderText("Search text in your test?")
        self.edit.setMinimumWidth(200)

        self.replaceEdit = QComboBox(self)
        self.replaceEdit.setEditable(1)
        self.replaceEdit.setMaxCount(10)
        self.replaceEdit.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)
        self.replaceEdit.lineEdit().setPlaceholderText(
            "Replace the text with?")
        self.replaceEdit.setMinimumWidth(200)

        self.caseCheck = QCheckBox(self.tr("Case Sensitive"))
        self.caseCheck.setChecked(
            QtHelper.str2bool(Settings.instance().readValue(
                key='Editor/find-case-sensitive')))
        self.caseWordCheck = QCheckBox(self.tr("Whole word only"))
        self.caseWordCheck.setChecked(
            QtHelper.str2bool(
                Settings.instance().readValue(key='Editor/find-whole-word')))
        self.allCheck = QCheckBox(self.tr("All occurences"))
        self.allCheck.setChecked(
            QtHelper.str2bool(
                Settings.instance().readValue(key='Editor/replace-all')))
        self.caseRegexpCheck = QCheckBox(self.tr("Regular expression"))
        self.caseRegexpCheck.setChecked(
            QtHelper.str2bool(
                Settings.instance().readValue(key='Editor/find-regexp')))
        self.caseWrapCheck = QCheckBox(self.tr("Wrap at the end"))
        self.caseWrapCheck.setChecked(
            QtHelper.str2bool(
                Settings.instance().readValue(key='Editor/find-wrap')))

        glayout.addWidget(self.edit, 0, 1)
        glayout.addWidget(self.nextButton, 0, 3)
        glayout.addWidget(self.previousButton, 0, 2)
        glayout.addWidget(self.caseCheck, 2, 2)
        glayout.addWidget(self.caseWrapCheck, 2, 3)
        glayout.addWidget(self.caseWordCheck, 3, 2)
        glayout.addWidget(self.caseRegexpCheck, 3, 3)

        glayout.addWidget(self.replaceEdit, 1, 1)
        glayout.addWidget(self.replaceButton, 1, 2)
        glayout.addWidget(self.allCheck, 1, 3)

        self.previousButton.setDisabled(True)
        self.nextButton.setDisabled(True)

        self.setLayout(glayout)

        flags = Qt.WindowFlags()
        flags |= Qt.Window
        flags |= Qt.WindowTitleHint
        flags |= Qt.WindowCloseButtonHint
        flags |= Qt.MSWindowsFixedSizeDialogHint
        self.setWindowFlags(flags)

        self.setWindowIcon(QIcon(":/main.png"))
        self.setWindowTitle("Find And Replace")

    def createConnections(self):
        """
        create qt connection
        """
        self.edit.editTextChanged.connect(self.textHasChanged)
        self.edit.EnterPressed.connect(self.returnPressed)
        self.caseCheck.stateChanged.connect(self.find)

    def returnPressed(self):
        """
        Return key pressed
        Find next in this case
        """
        self.findNext()

    def setEditor(self, editor):
        """
        Set the target to find the text

        @param editor: 
        @type editor:   
        """
        self.editor = editor

    def textHasChanged(self, txt):
        """
        Find text has changed
        """
        text = self.edit.currentText()
        if len(text) > 0:
            self.previousButton.setEnabled(True)
            self.nextButton.setEnabled(True)
            self.find(changed=True, forward=True)
        else:
            self.previousButton.setDisabled(True)
            self.nextButton.setDisabled(True)

    def updateComboBox(self):
        """
        Update combobox
        """
        comboUpdated = False
        for i in range(self.edit.count()):
            if self.edit.itemText(i) == self.edit.currentText():
                comboUpdated = True
        if not comboUpdated:
            self.edit.addItem(self.edit.currentText())

        comboUpdated = False
        for i in range(self.replaceEdit.count()):
            if self.replaceEdit.itemText(i) == self.replaceEdit.currentText():
                comboUpdated = True
        if not comboUpdated:
            self.replaceEdit.addItem(self.replaceEdit.currentText())

    def clearText(self):
        """
        Clear all QlineEdit
        """
        self.edit.setStyleSheet("")

        self.edit.clearEditText()

        self.replaceEdit.clearEditText()

    def findPrevious(self):
        """
        Find previous occurence
        """
        # update combobox
        self.updateComboBox()

        # find previous
        self.find(changed=False, forward=False)

    def findNext(self, line=-1, index=-1):
        """
        Find next occurence
        """
        # update combobox
        self.updateComboBox()

        return self.find(changed=False, forward=True, line=line, index=index)

    def find(self, changed=True, forward=True, line=-1, index=-1):
        """
        Call the find function

        @param changed: 
        @type changed: boolean  

        @param forward: 
        @type forward: boolean      
        """
        text = self.edit.currentText()
        if len(text) == 0:
            self.edit.setStyleSheet("")
            return None
        else:
            found = self.editor.findText(
                text,
                changed,
                forward,
                case=self.caseCheck.isChecked(),
                words=self.caseWordCheck.isChecked(),
                regexp=self.caseRegexpCheck.isChecked(),
                wraps=self.caseWrapCheck.isChecked(),
                line=line,
                index=index)
            self.edit.setStyleSheet(self.styleEdit[found])
            return found

    def replaceFind(self):
        """
        Replace and find
        """
        if (self.editor is None): return

        replaceText = self.replaceEdit.currentText()
        searchText = self.edit.currentText()
        if not self.caseCheck.isChecked(): searchText = searchText.lower()
        current = -1
        nbReplaced = 0

        # find the first occurence from the beginning of the doc or not
        if not self.allCheck.isChecked():
            detected = self.findNext()
        else:
            detected = self.findNext(line=0, index=0)
        (line, _) = self.editor.getCursorPosition()

        while detected:
            previous = current
            selectedText = self.editor.selectedText()

            # normalize the text in lower case if the case sensitive is not activated
            if not self.caseCheck.isChecked():
                selectedText = selectedText.lower()

            # replace the selection
            if self.editor.hasSelectedText() and selectedText == searchText:
                self.editor.replace(replaceText)
                nbReplaced += 1

            # find the next occurence of the word
            detected = self.findNext()
            (current, _) = self.editor.getCursorPosition()

            # all doc readed ? break the loop
            if previous > current: break
            if current == line and previous != -1: break

            # just execute one replace
            if not self.allCheck.isChecked(): break

        self.allCheck.setCheckState(Qt.Unchecked)
        self.NbReplaced.emit(nbReplaced)