Exemplo n.º 1
0
class ActionBar(QFrame):
    """
    SIGNALS:
    @changeCurrent(PyQt_PyObject)
    @runFile(QString)
    @reopenTab(QString)
    @recentTabsModified()
    """

    def __init__(self, main_combo=False):
        super(ActionBar, self).__init__()
        self.setObjectName("actionbar")
        hbox = QHBoxLayout(self)
        hbox.setContentsMargins(1, 1, 1, 1)
        hbox.setSpacing(1)

        self.lbl_checks = QLabel('')
        self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.lbl_checks.setFixedWidth(48)
        self.lbl_checks.setVisible(False)
        hbox.addWidget(self.lbl_checks)

        self.combo = QComboBox()
        self.combo.setIconSize(QSize(16, 16))
        #model = QStandardItemModel()
        #self.combo.setModel(model)
        #self.combo.view().setDragDropMode(QAbstractItemView.InternalMove)
        self.combo.setMaximumWidth(300)
        self.combo.setObjectName("combotab")
        self.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
            self.current_changed)
        self.combo.setToolTip(translations.TR_COMBO_FILE_TOOLTIP)
        self.combo.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.combo, SIGNAL(
            "customContextMenuRequested(const QPoint &)"),
            self._context_menu_requested)
        hbox.addWidget(self.combo)

        self.symbols_combo = QComboBox()
        self.symbols_combo.setIconSize(QSize(16, 16))
        self.symbols_combo.setObjectName("combo_symbols")
        self.connect(self.symbols_combo, SIGNAL("activated(int)"),
            self.current_symbol_changed)
        hbox.addWidget(self.symbols_combo)

        self.code_navigator = CodeNavigator()
        hbox.addWidget(self.code_navigator)

        self._pos_text = "Line: %d, Col: %d"
        self.lbl_position = QLabel(self._pos_text % (0, 0))
        self.lbl_position.setObjectName("position")
        self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.lbl_position)

        self.btn_close = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.btn_close.setIconSize(QSize(16, 16))
        if main_combo:
            self.btn_close.setObjectName('navigation_button')
            self.btn_close.setToolTip(translations.TR_CLOSE_FILE)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                self.about_to_close_file)
        else:
            self.btn_close.setObjectName('close_split')
            self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                self.close_split)
        self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.btn_close)

    def resizeEvent(self, event):
        super(ActionBar, self).resizeEvent(event)
        if event.size().width() < 350:
            self.symbols_combo.hide()
            self.code_navigator.hide()
            self.lbl_position.hide()
        else:
            self.symbols_combo.show()
            self.code_navigator.show()
            self.lbl_position.show()

    def add_item(self, text, neditable):
        """Add a new item to the combo and add the neditable data."""
        self.combo.addItem(text, neditable)
        self.combo.setCurrentIndex(self.combo.count() - 1)

    def get_editables(self):
        editables = []
        for index in range(self.combo.count()):
            neditable = self.combo.itemData(index)
            editables.append(neditable)
        return editables

    def add_symbols(self, symbols):
        """Add the symbols to the symbols's combo."""
        self.symbols_combo.clear()
        for symbol in symbols:
            data = symbol[1]
            if data[1] == 'f':
                icon = QIcon(":img/function")
            else:
                icon = QIcon(":img/class")
            self.symbols_combo.addItem(icon, data[0])

    def set_current_symbol(self, index):
        self.symbols_combo.setCurrentIndex(index)

    def update_item_icon(self, neditable, icon):
        index = self.combo.findData(neditable)
        self.combo.setItemIcon(index, icon)

    def update_item_text(self, neditable, text):
        index = self.combo.findData(neditable)
        self.combo.setItemText(index, text)

    def current_changed(self, index):
        """Change the current item in the combo."""
        neditable = self.combo.itemData(index)
        self.emit(SIGNAL("changeCurrent(PyQt_PyObject, int)"), neditable, index)

    def current_symbol_changed(self, index):
        """Change the current symbol in the combo."""
        self.emit(SIGNAL("goToSymbol(int)"), index)

    def update_line_col(self, line, col):
        """Update the line and column position."""
        self.lbl_position.setText(self._pos_text % (line, col))

    def _context_menu_requested(self, point):
        """Display context menu for the combo file."""
        if self.combo.count() == 0:
            # If there is not an Editor opened, don't show the menu
            return
        menu = QMenu()
        actionAdd = menu.addAction(translations.TR_ADD_TO_PROJECT)
        actionRun = menu.addAction(translations.TR_RUN_FILE)
        menuSyntax = menu.addMenu(translations.TR_CHANGE_SYNTAX)
        self._create_menu_syntax(menuSyntax)
        menu.addSeparator()
        actionClose = menu.addAction(translations.TR_CLOSE_FILE)
        actionCloseAll = menu.addAction(translations.TR_CLOSE_ALL_FILES)
        actionCloseAllNotThis = menu.addAction(
            translations.TR_CLOSE_OTHER_FILES)
        menu.addSeparator()
        actionSplitH = menu.addAction(translations.TR_SPLIT_VERTICALLY)
        actionSplitV = menu.addAction(translations.TR_SPLIT_HORIZONTALLY)
        menu.addSeparator()
        actionCopyPath = menu.addAction(
            translations.TR_COPY_FILE_PATH_TO_CLIPBOARD)
        actionReopen = menu.addAction(translations.TR_REOPEN_FILE)
        actionUndock = menu.addAction(translations.TR_UNDOCK_EDITOR)
        if len(settings.LAST_OPENED_FILES) == 0:
            actionReopen.setEnabled(False)
        #Connect actions
        self.connect(actionSplitH, SIGNAL("triggered()"),
            lambda: self._split(False))
        self.connect(actionSplitV, SIGNAL("triggered()"),
            lambda: self._split(True))
        self.connect(actionRun, SIGNAL("triggered()"),
            self._run_this_file)
        self.connect(actionAdd, SIGNAL("triggered()"),
            self._add_to_project)
        self.connect(actionClose, SIGNAL("triggered()"),
            self.about_to_close_file)
        self.connect(actionCloseAllNotThis, SIGNAL("triggered()"),
            self._close_all_files_except_this)
        self.connect(actionCloseAll, SIGNAL("triggered()"),
            self._close_all_files)
        self.connect(actionCopyPath, SIGNAL("triggered()"),
            self._copy_file_location)
        self.connect(actionReopen, SIGNAL("triggered()"),
            self._reopen_last_tab)
        self.connect(actionUndock, SIGNAL("triggered()"),
            self._undock_editor)

        menu.exec_(QCursor.pos())

    def _create_menu_syntax(self, menuSyntax):
        """Create Menu with the list of syntax supported."""
        syntax = list(settings.SYNTAX.keys())
        syntax.sort()
        for syn in syntax:
            menuSyntax.addAction(syn)
            self.connect(menuSyntax, SIGNAL("triggered(QAction*)"),
                self._reapply_syntax)

    def _reapply_syntax(self, syntaxAction):
        #TODO
        if [self.currentIndex(), syntaxAction] != self._resyntax:
            self._resyntax = [self.currentIndex(), syntaxAction]
            self.emit(SIGNAL("syntaxChanged(QWidget, QString)"),
                self.currentWidget(), syntaxAction.text())

    def set_current_file(self, neditable):
        index = self.combo.findData(neditable)
        self.combo.setCurrentIndex(index)

    def set_current_by_index(self, index):
        self.combo.setCurrentIndex(index)

    def about_to_close_file(self, index=None):
        """Close the NFile object."""
        if index is None:
            index = self.combo.currentIndex()
        neditable = self.combo.itemData(index)
        if neditable:
            neditable.nfile.close()

    def close_split(self):
        self.emit(SIGNAL("closeSplit()"))

    def close_file(self, neditable):
        """Receive the confirmation to close the file."""
        index = self.combo.findData(neditable)
        self.combo.removeItem(index)
        return index

    def _run_this_file(self):
        """Execute the current file."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("runFile(QString)"), neditable.file_path)

    def _add_to_project(self):
        """Emit a signal to let someone handle the inclusion of the file
        inside a project."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("addToProject(QString)"), neditable.file_path)

    def _reopen_last_tab(self):
        self.emit(SIGNAL("reopenTab(QString)"),
            settings.LAST_OPENED_FILES.pop())
        self.emit(SIGNAL("recentTabsModified()"))

    def _undock_editor(self):
        self.emit(SIGNAL("undockEditor()"))

    def _split(self, orientation):
        self.emit(SIGNAL("splitEditor(bool)"), orientation)

    def _copy_file_location(self):
        """Copy the path of the current opened file to the clipboard."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        QApplication.clipboard().setText(neditable.file_path,
            QClipboard.Clipboard)

    def _close_all_files(self):
        """Close all the files opened."""
        for i in range(self.combo.count()):
            self.about_to_close_file(0)

    def _close_all_files_except_this(self):
        """Close all the files except the current one."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        for i in reversed(list(range(self.combo.count()))):
            ne = self.combo.itemData(i)
            if ne is not neditable:
                self.about_to_close_file(i)
Exemplo n.º 2
0
class ImmatriculationSCoopViewWidget(FWidget):

    def __init__(self, parent, dmd=None, *args, **kwargs):
        super(ImmatriculationSCoopViewWidget, self).__init__(
            parent=parent, *args, **kwargs)

        self.parent = parent
        self.parentWidget().set_window_title("FORMULAIRE D’IMMATRICULATION")
        self.dmd = dmd
        self.scoop = self.dmd.scoop
        self.name_declarant_field = QLineEdit()
        self.name_declarant_field.setPlaceholderText("M. / Mme")
        self.name_declarant_field.setMaximumWidth(600)

        self.procuration_field = QLineEdit()
        self.procuration_field.setPlaceholderText(
            "Réf.de la Procuration le cas échéant")
        self.procuration_field.setMaximumWidth(600)
        self.quality_box = QComboBox()
        self.quality_box.setMaximumWidth(600)
        self.quality_box.currentIndexChanged.connect(self.change_select)
        self.qualities_list = get_qualities()
        for index, value in enumerate(self.qualities_list):
            self.quality_box.addItem(
                "{}".format(self.qualities_list.get(value).upper()), value)

        self.type_box = QComboBox()
        self.type_box.setMaximumWidth(600)
        self.type_lists = Immatriculation.TYPES
        for index, value in enumerate(self.type_lists):
            print(value)
            self.type_box.addItem("{}".format(value[1], index))
        self.tel_declarant_field = IntLineEdit()
        self.tel_declarant_field.setInputMask('## ## ## ##')
        self.tel_declarant_field.setMaximumWidth(600)
        self.btn = Button_save("Sauvegarder")
        self.btn.setMaximumWidth(600)
        self.btn.clicked.connect(self.save)

        declarant_formbox = QFormLayout()
        declarant_formbox.addRow(FLabel("<strong>Type de d'immatriculation *: </strong>"), self.type_box)
        declarant_formbox.addRow(FLabel("<strong>Nom et prénom du declarant *: </strong>"), self.name_declarant_field)
        declarant_formbox.addRow(FLabel("<strong>En qualité de *: </strong>"), self.quality_box)
        declarant_formbox.addRow(FLabel("<strong>Procuration *: </strong>"), self.procuration_field)
        declarant_formbox.addRow(FLabel("<strong>Numéro tel. du declarant *: </strong>"), self.tel_declarant_field)
        declarant_formbox.addRow(FLabel(""), self.btn)
        self.declarantGroupBox = QGroupBox("Info. du déclarant de la {} *".format(self.scoop.denomination))
        self.declarantGroupBox.setStyleSheet(CSS_CENTER)
        self.declarantGroupBox.setLayout(declarant_formbox)
        vbox = QVBoxLayout()
        # vbox.addWidget(self.infoGroupBox)
        vbox.addWidget(self.declarantGroupBox)
        # vbox.addLayout(editbox)
        self.setLayout(vbox)

    def change_select(self):
        self.qlt_select = self.quality_box.itemData(
            self.quality_box.currentIndex())

        self.procuration_field.setEnabled(False)
        if self.qlt_select == Immatriculation.TP:
            self.procuration_field.setEnabled(True)
            # if check_is_empty(self.procuration_field):
            #     return False

    def is_not_valide(self):
        # print(check_is_empty(self.name_declarant_field))
        if self.quality_box.itemData(self.quality_box.currentIndex()) == Immatriculation.TP:
            if check_is_empty(self.procuration_field) or check_is_empty(self.tel_declarant_field):
                return True
        return check_is_empty(self.name_declarant_field) or check_is_empty(self.tel_declarant_field)

    def save(self):
        if self.is_not_valide():
            return False

        imma = Immatriculation()
        imma.scoop = self.scoop
        imma.typ_imm = self.type_lists[self.type_box.currentIndex()][0]
        imma.name_declarant = self.name_declarant_field.text()
        imma.quality = self.quality_box.itemData(self.quality_box.currentIndex())
        imma.procuration = self.procuration_field.text()
        imma.tel_declarant = self.tel_declarant_field.text()
        imma.save_ident()
        self.dmd.status = self.dmd.ENDPROCCES
        self.dmd.save_()
        self.parent.change_context(ResgistrationManagerWidget)
Exemplo n.º 3
0
class NodeList(QWidget):
    def __init__(self,  parent, mainWindow, dockBrowser):
        super(NodeList,  self).__init__(parent)
        
        self.__browsers = dockBrowser
        # Necessary
        self.type = "views"
        self.icon = QIcon(":list.png")
        self.name = ""
        self.__mainWindow = mainWindow
        self.__parent = parent
    
        # Specific
        self.currentIndexDir = None
        self.currentNodeDir = None
        
        self.g_display()
        self.initCallback(dockBrowser)

        self.loader = loader.loader()
        self.lmodules = self.loader.modules
        self.taskmanager = TaskManager()
        self.env = env.env()
        
    def g_display(self):
        self.setMinimumSize(QSize(400, 300))
        self.createSubMenu()
        self.vlayout = QVBoxLayout(self)
        self.hlayout = QHBoxLayout()
        self.vlayout.addLayout(self.hlayout)

        self.initListView()
        self.initThumbsView()
        
        self.topButton = QPushButton(self)
        self.topButton.setFixedSize(QSize(32,32))
        self.topButton.setFlat(True)
        self.topButton.setIcon(QIcon(":previous.png"))
        self.topButton.setIconSize(QSize(32,32))
        self.hlayout.addWidget(self.topButton)

        self.listButton = QPushButton(self)
        self.listButton.setFixedSize(QSize(32, 32))
        self.listButton.setFlat(True)
        self.listButton.setIcon(QIcon(":list.png"))
        self.listButton.setIconSize(QSize(32,32))
        self.hlayout.addWidget(self.listButton)

        self.thumButton = QPushButton(self)
        self.thumButton.setFixedSize(QSize(32, 32))
        self.thumButton.setFlat(True)
        self.thumButton.setIcon(QIcon(":image.png"))
        self.thumButton.setIconSize(QSize(32,32))
        self.hlayout.addWidget(self.thumButton)

        self.thumSize = QComboBox()
        self.thumSize.setMaximumWidth(100)
        self.thumSize.addItem("Small")
        self.thumSize.addItem("Medium")
        self.thumSize.addItem("Large")
        self.connect(self.thumSize, SIGNAL("currentIndexChanged(QString)"), self.sizeChanged)
        self.hlayout.addWidget(self.thumSize)


        self.thumButton.setEnabled(True)
        self.thumSize.setEnabled(False)
        self.listButton.setEnabled(False)
        
        self.comboBoxPath = NodeComboBox(self)
        self.comboBoxPath.setMinimumSize(QSize(251,32))
        self.comboBoxPath.setMaximumSize(QSize(16777215,32))
        self.hlayout.addWidget(self.comboBoxPath)
        
    def initListView(self):    
        self.ListView = ListView(self, self.__mainWindow)
	self.ListModel = ListModel(self)
        self.ListModelFilter = QSortFilterProxyModel()
        self.ListModelFilter.setDynamicSortFilter(True)
        self.ListModelFilter.setSortCaseSensitivity(Qt.CaseInsensitive)
        self.ListModelFilter.setSourceModel(self.ListModel) 
        self.ListView.setModels(self.ListModel, self.ListModelFilter)
        self.ListView.setModel(self.ListModelFilter)
        self.ListView.setSubMenu(self.submenuFile)

        self.vlayout.addWidget(self.ListView)
        
    def initThumbsView(self):
        self.ThumbsView = ThumbsView(self.__mainWindow, self)
        self.ThumbsItemModel = ThumbsItemModel(self.ThumbsView.thread)
        
        self.ThumbsView.setModels(self.ThumbsItemModel)
        self.ThumbsView.setSubMenu(self.submenuFile)
        self.vlayout.addWidget(self.ThumbsView)

    def initCallback(self, dockBrowser):
        self.connect(self.topButton, SIGNAL("clicked()"),  self.moveToTop)

        self.connect(self.listButton, SIGNAL("clicked()"),  self.listActivated)
        self.connect(self.thumButton, SIGNAL("clicked()"),  self.thumbActivated)

        self.connect(self.comboBoxPath, SIGNAL("currentIndexChanged(const QString & )"),  self.comboBoxPathChanged)
        self.connect(ConnectorCallback.instance, SIGNAL("reload"), self.reload,  Qt.BlockingQueuedConnection)        
        self.connect(dockBrowser.treeView, SIGNAL("changeDirectory"), self.loadFolder)
        self.connect(dockBrowser.treeView, SIGNAL("reloadNodeView"), self.reload)
        dockBrowser.treeView.connect(self, SIGNAL("setIndexAndExpand"), dockBrowser.treeView.setIndexAndExpand)
        dockBrowser.treeView.connect(self, SIGNAL("setIndex"), dockBrowser.treeView.setCurrentIndexForChild)
        
    def moveToTop(self):
        if self.currentIndexDir <> None :
            index = self.__browsers.treeItemModel.indexWithNode(self.currentNodeDir)
            parent = self.__browsers.treeItemModel.parent(index)
            if parent:
                self.emit(SIGNAL("setIndexAndExpand"), self, parent)
                self.currentIndexDir = parent
            else :
                self.emit(SIGNAL("setIndexAndExpand"), self, index)
                self.currentIndexDir  = index
    
    def comboBoxPathChanged(self, text):
        node = self.comboBoxPath.getNode(str(text))    
        if node.this == self.currentNodeDir.this :
            return
        index = self.comboBoxPath.getBrowserIndex(str(text))
        self.loadFolder(node, index)
        self.emit(SIGNAL("setIndex"), self, self.currentIndexDir)
  
#    def comboBoxModeChanged(self, index):
#        if index == 0 :
#            self.ListView.setVisible(True)
#            self.ThumbsView.setVisible(False)
#        else :
#            self.ListView.setVisible(False)
#            self.ThumbsView.setVisible(True)
#        self.reloadChangedView()
        
    def listActivated(self):
        self.ListView.setVisible(True)
        self.ThumbsView.setVisible(False)
        self.reloadChangedView()

        #Desactivate thumb buttons
        self.thumButton.setEnabled(True)
        self.thumSize.setEnabled(False)
        self.listButton.setEnabled(False)

    def thumbActivated(self):
        self.ListView.setVisible(False)
        self.ThumbsView.setVisible(True)
        self.reloadChangedView()

        self.thumButton.setEnabled(False)
        self.thumSize.setEnabled(True)
        self.listButton.setEnabled(True)

    def reloadChangedView(self):
        if not self.visibleRegion().isEmpty() :
            view = self.viewVisible()
            if view.getModel().currentNodeDir is not None and view.getModel().currentNodeDir.this == self.currentNodeDir.this :
                return
            self.loadFolder(self.currentNodeDir, self.currentIndexDir, 1)
  
    # Specific type views
    def loadFolder(self,  node, indexFolder = None,  force = None):
        if node is None :
            return
        if self.currentNodeDir is not None :
            if force is None and self.currentNodeDir.this == node.this:
                return
        if force <> 2 and str(self) <> str(self.__browsers.getChild()) :
            return
            
        self.currentIndexDir = indexFolder
        self.currentNodeDir = node
        self.comboBoxPath.addPathAndSelect(node, indexFolder)
        
        if self.ThumbsView.isVisible() :
            self.ThumbsView.loadFolder(node, force)
        if self.ListView.isVisible() or force == 2:
            self.ListView.loadFolder(node)
        if force == 2 :
            self.emit(SIGNAL("setIndexAndExpand"), self, self.currentIndexDir)
    
    def setChildSelected(self):
        if str(self.__browsers.getChild()) <> str(self) :
            index = self.__browsers.treeItemModel.indexWithNode(self.currentNodeDir)
            self.emit(SIGNAL("setIndexAndExpand"), self, index)

    def getListCurrentItems(self):
        view = self.viewVisible()
        return view.getListCurrentItems()
    
    def getListCurrentNode(self):
        view = self.viewVisible()
        return view.getListCurrentNode()
    
    def reload(self):
        self.loadFolder(self.currentNodeDir, self.currentIndexDir, 1)
    
    def refreshIndexBrowser(self):
        self.emit(SIGNAL("setIndex"), self, self.currentIndexDir)
        
    def viewVisible(self):
        if self.ListView.isVisible() :
            return self.ListView
        if self.ThumbsView.isVisible() :
            return self.ThumbsView
        return self.ListView

    def changeDirectoryBrowser(self, node):
        dockNodeTree = self.__mainWindow.dockNodeTree
        currentIndex = dockNodeTree.treeView.selectionModel().currentIndex()
        if currentIndex is None :
            return
        currentItem = dockNodeTree.treeItemModel.getItem(currentIndex)
        #if not node.next.empty():
        newcurrent = currentItem.childWithNode(node)
        if not newcurrent:
            return
        #            
        index = dockNodeTree.treeItemModel.index(newcurrent.childNumber(),  0,  currentIndex)
        self.emit(SIGNAL("setIndexAndExpand"), self, index)
        #    #self.loadFolder(node, index)

    ###############
    ## CONTEXT  MENU ##
    ###############
    def createSubMenu(self):
        self.extractor = Extractor(self.__mainWindow)
        self.connect(self.extractor, SIGNAL("filled"), self.launchExtract)
	self.submenuFile = QMenu()
        self.submenuFile.addAction(QIcon(":exec.png"),  "Open", self.openDefault, "Listview")
        self.menuModules = self.submenuFile.addMenu(QIcon(":exec.png"),  "Open With")
        self.menuTags = MenuTags(self, self.__mainWindow, self.getListCurrentNode)
        self.submenuFile.addSeparator()
        self.submenuFile.addAction(QIcon(":hexedit.png"), QApplication.translate("ListView", "Hexeditor", None, QApplication.UnicodeUTF8), self.launchHexedit, "Listview")
        self.submenuFile.addAction(QIcon(":extract.png"), QApplication.translate("ListView", "Extract", None, QApplication.UnicodeUTF8), self.extractNodes, "Listview")
        self.submenuFile.addSeparator()
        self.submenuFile.addAction(QIcon(":info.png"), QApplication.translate("ListView", "Property", None, QApplication.UnicodeUTF8), self.propertyNodes, "Listview")

    def launchExtract(self):
        res = self.extractor.getArgs()
        arg = self.env.libenv.argument("gui_input")
        lnodes = self.env.libenv.ListNode()
        lnodes.thisown = 0
        for node in res["nodes"]:
            lnodes.append(node)
        arg.thisown = 0
        arg.add_path("syspath", str(res["path"]))
        arg.add_lnode("files", lnodes)
        arg.add_bool("recursive", int(res["recurse"]))
        self.taskmanager.add("extract", arg, ["thread", "gui"])


    def extractNodes(self):
        self.extractor.launch(self.getListCurrentNode())

    def openDefault(self):
      nodes = self.getListCurrentNode()
      for node in nodes:
        arg = self.env.libenv.argument("gui_input")
        arg.thisown = 0 
        ft = FILETYPE()
        try:
          mod = ft.findcompattype(node)[0]
          if self.lmodules[mod]:
            conf = self.lmodules[mod].conf
            cdl = conf.descr_l
            for a in cdl:
              if a.type == "node":
                 arg.add_node(a.name, node)
          self.taskmanager.add(mod, arg, ["thread", "gui"])       
        except IndexError: 
          arg.add_node("file", node)
          self.taskmanager.add("hexedit", arg, ["thread", "gui"])        
 
    def launchHexedit(self):
        nodes = self.getListCurrentNode()
        for node in nodes:
            arg = self.env.libenv.argument("gui_input")
            arg.thisown = 0
            arg.add_node("file", node)
            self.taskmanager.add("hexedit", arg, ["thread", "gui"])

    def propertyNodes(self):
        if not self.__mainWindow.QPropertyDialog.isVisible():
            self.__mainWindow.QPropertyDialog.fillInfo(self.currentNodeDir, self.getListCurrentNode())
            iReturn = self.__mainWindow.QPropertyDialog.exec_()
            self.__mainWindow.QPropertyDialog.removeAttr()
        else:
            QMessageBox.critical(self, "Erreur", u"This box is already open")


# CALLBACK

    def sizeChanged(self, string):
        if string == "Small":
            self.ThumbsView.configure(64, 64)
        elif string == "Medium":
            self.ThumbsView.configure(96, 96)
        elif string == "Large":
            self.ThumbsView.configure(128, 128)
Exemplo n.º 4
0
class OCAHPanel(QFrame):
    def __init__(self, parent):
        QFrame.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("OCAHPanel" + str(len(parent.findChildren(OCAHPanel))))

#         self.frame_WindIA = QFrame(parent)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Raised)
        self.setObjectName(("frame_WindIA"))
        self.hLayout = QHBoxLayout(self)
        self.hLayout.setSpacing(0)
        self.hLayout.setMargin(0)
        self.hLayout.setObjectName(("hLayout"))

        self.basicFrame = Frame(self, "HL")
        self.basicFrame.layoutBoxPanel.setSpacing(0)
        # self.basicFrame.layoutBoxPanel.setMargin(0)
        self.hLayout.addWidget(self.basicFrame)

        self.lblIA = QLabel(self.basicFrame)
        self.lblIA.setMinimumSize(QSize(200, 0))
        self.lblIA.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lblIA.setFont(font)
        self.lblIA.setObjectName(("lblIA"))
        self.basicFrame.Add = self.lblIA
        self.cmbType = QComboBox(self.basicFrame)
        self.cmbType.setMinimumSize(QSize(70, 0))
        self.cmbType.setMaximumWidth(70)
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.cmbType.setFont(font)
        self.cmbType.setObjectName(("cmbType"))
        self.basicFrame.Add = self.cmbType



        self.txtAltitudeM = QLineEdit(self.basicFrame)
        self.txtAltitudeM.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.txtAltitudeM.setFont(font)
        self.txtAltitudeM.setObjectName(self.objectName() + "_txtAltitudeM")
        self.txtAltitudeM.setText("0.0")
        self.txtAltitudeM.setMinimumWidth(70)
        self.txtAltitudeM.setMaximumWidth(70)
        self.basicFrame.Add = self.txtAltitudeM

        labelM = QLabel(self.basicFrame)
        labelM.setObjectName(("labelM"))
        labelM.setText(" m ")
        self.basicFrame.Add = labelM

        self.txtAltitude = QLineEdit(self.basicFrame)
        sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.txtAltitude.sizePolicy().hasHeightForWidth())
        self.txtAltitude.setSizePolicy(sizePolicy)
        self.txtAltitude.setMinimumSize(QSize(70, 0))
        self.txtAltitude.setMaximumSize(QSize(70, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.txtAltitude.setFont(font)
        self.txtAltitude.setObjectName(self.objectName() + "_txtAltitude")
        self.basicFrame.Add = self.txtAltitude

        labelFt = QLabel(self.basicFrame)
        labelFt.setObjectName(("labelFt"))
        labelFt.setText(" ft")
        self.basicFrame.Add = labelFt

        spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.hLayout.addItem(spacerItem)
        
        self.altitude = Altitude.NaN()
        self.customValue = Speed(30).Knots
        self.cmbType.addItems(["OCA", "OCH"])
        # self.cmbType.currentIndexChanged.connect(self.changeType)
        self.cmbType.setCurrentIndex(0)
        self.lblIA.setText("Intermediate Segment Minimum:")
        # self.txtAltitude.setEnabled(False)
        self.txtAltitudeM.textChanged.connect(self.txtAltitudeMChanged)
        self.txtAltitude.textChanged.connect(self.txtAltitudeChanged)
        
        self.captionUnits = "ft"

        self.flag = 0
        self.txtAltitudeM.setText("0.0")
        self.txtAltitude.setText("0.0")
    def txtAltitudeChanged(self):
        try:
            test = float(self.txtAltitude.text())
            if self.flag==0:
                self.flag=1;
            if self.flag==2:
                self.flag=0;
            if self.flag==1:
                try:
                    self.txtAltitudeM.setText(str(round(Unit.ConvertFeetToMeter(float(self.txtAltitude.text())), 4)))
                except:
                    self.txtAltitudeM.setText("0.0")
                self.emit(SIGNAL("Event_0"), self)
        except:
            str0 = "You must input the float type in \"%s\"."%(self.Caption)
            QMessageBox.warning(self, "Warning" , str0)
            self.txtAltitudeM.setText("0.0")
            self.txtAltitude.setText("0.0")


    def txtAltitudeMChanged(self):
        try:
            test = float(self.txtAltitudeM.text())
            if self.flag==0:
                self.flag=2;
            if self.flag==1:
                self.flag=0;
            if self.flag==2:
                try:
                    self.txtAltitude.setText(str(round(Unit.ConvertMeterToFeet(float(self.txtAltitudeM.text())), 4)))
                except:
                    self.txtAltitude.setText("0.0")
                self.emit(SIGNAL("Event_0"), self)
        except:
            str0 = "You must input the float type in \"%s\"."%(self.Caption)
            QMessageBox.warning(self, "Warning" , str0)
            self.txtAltitude.setText("0.0")
            self.txtAltitudeM.setText("0.0")

        try:
            self.altitude = Altitude(float(self.txtAltitude.text()), AltitudeUnits.FT)
        except:
            self.altitude = Altitude.NaN()
    # def txtAltitudeChanged(self):
    #     try:
    #         self.altitude = Altitude(float(self.txtAltitude.text()), AltitudeUnits.FT)
    #     except:
    #         self.altitude = Altitude.NaN()
    # def setAltitude(self, value):
    #     self.altitude = value

#     def getValue(self, SpeedUnits_0 = SpeedUnits.KTS):    
#         return Speed(float(self.txtAltitude.text()), SpeedUnits_0)
    def method_2(self, altitude_0):
        altitude = Altitude(0)
        try:
            altitude = Altitude(float(self.txtAltitude.text()), AltitudeUnits.FT)
        except:
            altitude = Altitude(0)
        if (self.cmbType.currentIndex() == 0):
            return altitude
        return Altitude(altitude.Feet + altitude_0.Feet, AltitudeUnits.FT);

    def method_3(self, altitude_0):
        altitude = Altitude(0)
        try:
            altitude = Altitude(float(self.txtAltitude.text()), AltitudeUnits.FT)
        except:
            altitude = Altitude(0)
        if (self.cmbType.currentIndex() != 0):
            return altitude
        return Altitude(altitude.Feet - altitude_0.Feet, AltitudeUnits.FT);


    
    def changeType(self):
        pass
        
    # def get_altitude(self):
    #     return self.altitude
    # Value = property(get_altitude, setAltitude, None, None)

    def get_isEmpty(self):
        try:
            num = float(self.txtAltitude.text())
            return False
        except:
            return True
    IsEmpty = property(get_isEmpty, None, None, None)
    
    def get_CaptionUnits(self):
        return self.captionUnits
    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits
    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def get_Caption(self):
        caption = self.lblIA.text()
        val = caption.left(caption.length() - 1)
        return val
    def set_Caption(self, captionStr):
        self.lblIA.setText(captionStr + ":")
    Caption = property(get_Caption, set_Caption, None, None)



    def get_Value(self):
        try:
            return Altitude(float(self.txtAltitudeM.text()))
        except:
            return Altitude(0.0)

    def set_Value(self, altitude):
        if isinstance(altitude, Altitude):
            if self.captionUnits == "m":
                self.txtAltitudeM.setText(str(altitude.Metres))
            else:
                self.txtAltitude.setText(str(altitude.Feet))
        else:
            str0 = "You must input the type \"Altitude\" in \"%s\"."%(self.Caption)
            QMessageBox.warning(self, "Warning" , str0)
            self.txtAltitudeM.setText("0.0")
    Value = property(get_Value, set_Value, None, None)

    

    def set_LabelWidth(self, width):
        self.lblIA.setMinimumSize(QSize(width, 0))
        self.lblIA.setMaximumSize(QSize(width, 16777215))
    LabelWidth = property(None, set_LabelWidth, None, None)

    def get_ReadOnly(self):
        return self.txtAltitudeM.isReadOnly()
    def set_ReadOnly(self, bool):
        self.txtAltitudeM.setReadOnly(bool)
        self.txtAltitude.setReadOnly(bool)
    ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def get_Enabled(self):
        return self.txtAltitudeM.isEnabled()
    def set_Enabled(self, bool):
        self.txtAltitudeM.setEnabled(bool)
        self.txtAltitude.setEnabled(bool)
    Enabled = property(get_Enabled, set_Enabled, None, None)
Exemplo n.º 5
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        self.tpr.start()
        
    def quitProcessRunner(self):
        self.tpr.join()
        self.tpr.quit()
        self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()
Exemplo n.º 6
0
class fileFolderRenamerCreater(QtGui.QMainWindow):
    
    '''==========================================================================================================================================
    GUI Class.
    =========================================================================================================================================='''
    
    def __init__(self):
        '''----------------------------------------------------------------------------------------------------------------------------------
        GUI Window
        ----------------------------------------------------------------------------------------------------------------------------------'''
        QtGui.QMainWindow.__init__(self)       

        self.resize(600, 100)
        self.setWindowTitle("Renamer")
        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)
        self.main_layout = QGridLayout(self.central_widget)

        '''----------------------------------------------------------------------------------------------------------------------------------
        Layout of the GUI.
        ----------------------------------------------------------------------------------------------------------------------------------'''      
        self.window_layer_01 = QGridLayout()
        self.main_layout.addLayout(self.window_layer_01, 0, 0, 1, 1)           
        self.window_layer_02 = QGridLayout()
        self.main_layout.addLayout(self.window_layer_02, 1, 0, 1, 1)   
        self.window_layer_03 = QGridLayout()
        self.main_layout.addLayout(self.window_layer_03, 2, 0, 1, 1)
        self.window_layer_04 = QGridLayout()
        self.main_layout.addLayout(self.window_layer_04, 3, 0, 1, 1)
        self.window_layer_05 = QGridLayout()
        self.main_layout.addLayout(self.window_layer_05, 4, 0, 1, 1)
        self.window_layer_05 = QGridLayout()
        self.main_layout.addLayout(self.window_layer_05, 5, 0, 1, 1)
        self.window_layer_06 = QGridLayout()
        self.main_layout.addLayout(self.window_layer_06, 6, 0, 1, 1)
        self.window_layer_07 = QGridLayout()
        self.main_layout.addLayout(self.window_layer_07, 7, 0, 1, 1)        

        self.window_column_02 =QHBoxLayout()
        self.main_layout.addLayout(self.window_column_02, 4, 1, 1, 1) 
        self.window_column_03 =QHBoxLayout()
        self.main_layout.addLayout(self.window_column_03, 2, 1, 1, 1)            
        self.window_column_04 =QHBoxLayout()        
        self.main_layout.addLayout(self.window_column_04, 3, 1, 1, 1)

        '''----------------------------------------------------------------------------------------------------------------------------------
        Widgets
        ----------------------------------------------------------------------------------------------------------------------------------'''  

        self.asset_name_label_01 = QLabel("Project")
        self.asset_name_label_01.setMinimumWidth(70)
        self.asset_name_label_01.setMaximumWidth(70)
        self.window_layer_02.addWidget(self.asset_name_label_01, 0, 0, 1, 1)         
        
        self.project_name_folder = QComboBox()
        self.project_name_folder.setMinimumWidth(200)
        self.project_name_folder.setMaximumWidth(200)
        self.window_layer_02.addWidget(self.project_name_folder, 0, 1, 1, 1)
        srcfileName = os.listdir(ProjectMasterFolder)
        getFolders=[(each) for each in srcfileName if "." not in each]
        firstPick=["Pick Project"]
        self.project_name_folder.addItems(firstPick)
        self.project_name_folder.addItems(getFolders)

        self.asset_name_label_01 = QLabel("AssetName")
        self.asset_name_label_01.setMinimumWidth(70)
        self.asset_name_label_01.setMaximumWidth(70)
        self.window_layer_02.addWidget(self.asset_name_label_01, 0, 2, 1, 1) 

        
        self.asset_name_field_01 = QtGui.QLineEdit()
        self.asset_name_field_01.setText("")
        self.asset_name_field_01.setMinimumHeight(25)
        self.asset_name_field_01.setMaximumHeight(50) 
        self.asset_name_field_01.setMinimumWidth(100)
        self.asset_name_field_01.setMaximumWidth(100)
        self.window_layer_02.addWidget(self.asset_name_field_01, 0, 3, 1, 1)      
        
        self.asset_label = QLabel("Category")
        self.asset_label.setMinimumWidth(120)
        self.asset_label.setMaximumWidth(120)
        self.window_layer_02.addWidget(self.asset_label, 0, 4, 1, 1) 

        self.asset_dropdown_01 = QComboBox()
        self.asset_dropdown_01.setMinimumWidth(120)
        self.asset_dropdown_01.setMaximumWidth(120)
        self.window_layer_02.addWidget(self.asset_dropdown_01, 0, 5, 1, 1)
        self.asset_dropdown_01.addItems(Asset)
        #self.populateSequence(spinner=self.asset_dropdown_01)
        #self.asset_dropdown_01.currentIndexChanged[str].connect(self.on_langComboBox_IndexChanged)

        self.type_label = QLabel("Type")
        self.type_label.setMinimumWidth(120)
        self.type_label.setMaximumWidth(120)
        self.window_layer_02.addWidget(self.type_label, 0, 6, 1, 1) 

        self.type_dropdown_01 = QComboBox()
        self.type_dropdown_01.setMinimumWidth(120)
        self.type_dropdown_01.setMaximumWidth(120)
        self.window_layer_02.addWidget(self.type_dropdown_01, 0, 7, 1, 1)
        self.type_dropdown_01.addItems(Type)
        #self.populateSequence(spinner=self.type_dropdown_01)
        #self.type_dropdown_01.currentIndexChanged[str].connect(self.on_langComboBox_IndexChanged)

        self.ep_name_label = QLabel("Episode")
        self.ep_name_label.setMinimumWidth(70)
        self.ep_name_label.setMaximumWidth(70)
        self.window_layer_02.addWidget(self.ep_name_label, 0, 8, 1, 1) 
        
        self.ep_name_field = QtGui.QLineEdit()
        self.ep_name_field.setText("802")
        self.ep_name_field.setMinimumHeight(25)
        self.ep_name_field.setMaximumHeight(50) 
        self.ep_name_field.setMinimumWidth(100)
        self.ep_name_field.setMaximumWidth(100)
        self.window_layer_02.addWidget(self.ep_name_field, 0, 9, 1, 1)     

  
   
        self.dest_label_01 = QLabel("new path:")
        self.dest_label_01.setMinimumWidth(100)
        self.dest_label_01.setMaximumWidth(100)
        self.window_layer_05.addWidget(self.dest_label_01, 0, 0, 1, 1) 
        
        self.dest_folder_field_01 = QtGui.QLineEdit()
        self.dest_folder_field_01.setText(mayaFolder)        
        #self.dest_folder_field_01.setText(mayaFolder)        
        self.dest_folder_field_01.setMinimumHeight(25)
        self.dest_folder_field_01.setMaximumHeight(50) 
        self.dest_folder_field_01.setMinimumWidth(450)
        self.dest_folder_field_01.setMaximumWidth(450)
        self.window_layer_05.addWidget(self.dest_folder_field_01, 0, 1, 1, 1) 


        self.get_src_button = QPushButton("refresh")
        self.get_src_button.setMinimumHeight(25)

        self.get_dest_button = QPushButton("refresh")
        self.get_dest_button.setMinimumHeight(25)
        self.get_dest_button.setMaximumHeight(50) 
        self.get_dest_button.setMinimumWidth(100)
        self.get_dest_button.setMaximumWidth(100)
        self.connect(self.get_dest_button, SIGNAL('clicked()'), self._refresh)
        self.window_layer_05.addWidget(self.get_dest_button, 0, 4, 1, 1)   
        
        self.get_src_button = QPushButton("open folder")
        self.get_src_button.setMinimumHeight(25)

        self.get_dest_button = QPushButton("open folder")
        self.get_dest_button.setMinimumHeight(25)
        self.get_dest_button.setMaximumHeight(50) 
        self.get_dest_button.setMinimumWidth(100)
        self.get_dest_button.setMaximumWidth(100)
        self.connect(self.get_dest_button, SIGNAL('clicked()'), self._open_destination)
        self.window_layer_05.addWidget(self.get_dest_button, 0, 5, 1, 1)   

        self.do_it_buttton = QPushButton("Create!")
        self.do_it_buttton.setMinimumHeight(25)
        self.do_it_buttton.setMaximumHeight(50) 
        self.do_it_buttton.setMinimumWidth(100)
        self.do_it_buttton.setMaximumWidth(150)
        #self.do_it_buttton.clicked.connect(self._start)
        self.connect(self.do_it_buttton, SIGNAL('clicked()'), self._operation)
        self.window_layer_06.addWidget(self.do_it_buttton, 0, 0, 1, 1)   

################################################
#     def on_comboBoxParent_currentIndexChanged(self, index):
#         '''----------------------------------------------------------------------------------------------------------------------------------
#         Once the source sequence is chosen, 
#         this will populate the source shot spinner
#         ----------------------------------------------------------------------------------------------------------------------------------'''   
#         sourceSequence=self.sourceSequenceSpinner
#         getText=sourceSequence.currentText()
#         sourceShot=self.sourceShotSpinner
#         shotContainer=self._getShotFolder(getText)
#         shotContainer.append('')
#         shotContainer.reverse()
#         noshow="select sequence"
#         sourceShot.clear()
#         sourceShot.addItems(shotContainer)
# 
#     def deston_comboBoxParent_currentIndexChanged(self, index):
#         '''----------------------------------------------------------------------------------------------------------------------------------
#         Once the destination sequence is chosen, 
#         this will populate the destination shot spinner
#         ----------------------------------------------------------------------------------------------------------------------------------'''   
#         srcfileName=[]   
#         for (root, directories, files) in os.walk(ProjectMasterFolder):
#             for filename in files:
#                 srcfileName.append(filename)   
#         destinationShot=self.destinationSequenceSpinner
#         destinationShot.clear()
#         destinationShot.addItems(srcfileName)
        
              
        
    def _refresh(self):
        Project=self.project_name_folder
        Project=Project.currentText()
        Project=str(Project)        
        Asset=self.asset_dropdown_01
        Asset=Asset.currentText()
        Asset=str(Asset)
        Type=self.type_dropdown_01
        Type=Type.currentText()
        Type=str(Type)
        AssetName=self.asset_name_field_01
        AssetName=AssetName.text()
        AssetName=str(AssetName)        
        Episode=self.ep_name_field
        Episode=Episode.text()
        Episode=str(Episode)        
        destination=self.dest_folder_field_01
        destination=destination.text()
        destination=str(destination)        
        if Project =="Pick Project":
            print "You must assign a project"
            return
        elif len(AssetName)==0:
            print "you must give the asset a name"
            return
        elif Asset =="Pick Category":
            print "You must pick a Category"
            return
        elif Type=="Pick Asset Type":
            print "you much pick an Asset Type"
            return
        elif Type =="Episodic" and len(Episode)==0:
            print "if asset is episodic, you must fill in the episode field"
            return
        else:
            try:
                makeMayaFile=AssetName.split("_")[1]
            except:
                print "AssetName does not have a number assigned. Please give it a number EG:'01_'"   
                return         
            if Type=="Episodic":
                folderPath=ProjectMasterFolder+Project+mayaFolder+Asset+"\\"+Type+"\\"+Episode+"\\"+AssetName+"\\"
                self.dest_folder_field_01.setText(folderPath)
            elif Type=="Series":
                folderPath=ProjectMasterFolder+Project+mayaFolder+Asset+"\\"+Type+"\\"+AssetName+"\\"
                self.dest_folder_field_01.setText(folderPath)        
                
                
                
    def _open_destination(self):
        dest_field_01=self.dest_folder_field_01
        destImagePath=dest_field_01.text()
        destImagePath=str(destImagePath)
        self.get_path(destImagePath)  
                        
    def get_path(self, path):
        try:
            if '\\\\' in path:
                newpath=re.sub(r'\\\\',r'\\', path)
                os.startfile(r'\\'+newpath[1:])    
            else:
                os.startfile(path)
        except:
            print "cannot open path. check if it exists"
            return
            
    def _operation(self):
        Project=self.project_name_folder
        Project=Project.currentText()
        Project=str(Project)         
        Asset=self.asset_dropdown_01
        Asset=Asset.currentText()
        Asset=str(Asset)
        Type=self.type_dropdown_01
        Type=Type.currentText()
        Type=str(Type)
        AssetName=self.asset_name_field_01
        AssetName=AssetName.text()
        AssetName=str(AssetName)        
        Episode=self.ep_name_field
        Episode=Episode.text()
        Episode=str(Episode)        
        destination=self.dest_folder_field_01
        destination=destination.text()
        destination=str(destination)        
        if Project =="Pick Project":
            print "You must assign a project"
            return
        elif len(AssetName)==0:
            print "you must give the asset a name"
            return
        elif Asset =="Pick Category":
            print "You must pick a Category"
            return
        elif Type=="Pick Asset Type":
            print "you much pick an Asset Type"
            return
        elif Type =="Episodic" and len(Episode)==0:
            print "if asset is episodic, you must fill in the episode field"
            return
        else:
            try:
                makeMayaFile=AssetName.split("_")[1]
            except:
                print "AssetName does not have a number assigned. Please give it a number EG:'01_Name'"   
                return         
            if Type=="Episodic":
                folderPath=ProjectMasterFolder+Project+mayaFolder+Asset+"\\"+Type+"\\"+Episode+"\\"+AssetName
                for each in ProductionFolders:
                    makeProject=folderPath+"\\"+each
                    for item in ProductionSubFolders:
                        getAssetNameSuf=item.split("\\")[0]                  
                        ProjectBuild=makeProject+"\\"+item
                        newFile="LA0095_"+makeMayaFile+"_"+getAssetNameSuf+".txt"
                        fname = ProjectBuild+"\\"+newFile
                        if not os.path.exists(ProjectBuild): os.makedirs(ProjectBuild)
                        if not fname:
                            inp=open(fname, 'w+')
                            inp.write("hi"+'\r\n')
                            inp.close()
                            thisFile = fname
                            base = os.path.splitext(thisFile)[0]
                            os.rename(thisFile, base + ".ma")
                            print fname+" has been created"  
                        else:
                            pass                       
            else:
                folderPath=ProjectMasterFolder+Project+mayaFolder+Asset+"\\"+Type+"\\"+AssetName
                for each in ProductionFolders:
                    makeProject=folderPath+"\\"+each
                    for item in ProductionSubFolders:
                        getAssetNameSuf=item.split("\\")[0]
                        ProjectBuild=makeProject+"\\"+item
                        newFile="LA0095_"+makeMayaFile+"_"+getAssetNameSuf+".txt"
                        fname = ProjectBuild+"\\"+newFile
                        if not os.path.exists(ProjectBuild): os.makedirs(ProjectBuild)
                        if not fname:
                            inp=open(fname, 'w+')
                            inp.write("hi"+'\r\n')
                            inp.close()
                            thisFile = fname
                            base = os.path.splitext(thisFile)[0]
                            os.rename(thisFile, base + ".ma")
                            print fname+" has been created"  
                        else:
                            pass         
    def copying(self, root, filename, filepath, dstfolderPath):  
        for each in filename:
            filepath = os.path.join(root, each)
            shutil.copy(filepath, dstfolderPath)
            
    def renaming(self, root, filename, oldNamePart, newNamePart):
        for each in filename:
            filepath = os.path.join(root, each)
            print filepath
            os.rename(filepath, filepath.replace(oldNamePart, newNamePart))
#     def on_langComboBox_IndexChanged(self):
#         '''----------------------------------------------------------------------------------------------------------------------------------
#         This changes the functions of the interface dependent on whether language has been selected
#         ----------------------------------------------------------------------------------------------------------------------------------'''            
#         interfaceWidgetsAccess=[self.size_field_01,
#                                 self.r_field_01, 
#                                 self.g_field_01, 
#                                 self.b_field_01, 
#                                 self.textMode, 
#                                 self.imageMode,
#                                 self.source_folder_field_01, 
#                                 self.source_button, 
#                                 self.source_dropdown_01,
#                                 self.number_field_01,
#                                 self.suf_name_field_01,
#                                 self.format_name_field_01,
#                                 self.srcImage_field_01
#                                 ]
#         langDrop=self.lang_dropdown_01
#         languageType=langDrop.currentText()        
#         getSrcWidget=self.source_folder_field_01
#         srcFolderStuff=self.source_dropdown_01 
#         if languageType!="none":           
#             if languageType =="ES":
#                 langIndex="Placeholder_ES.png"
#                 self.language_lock_down(langIndex, interfaceWidgetsAccess)
#             elif languageType=="ZH":
#                 langIndex="Placeholder_ZH.png"
#                 self.language_lock_down(langIndex, interfaceWidgetsAccess)             
#             elif languageType=="FR":
#                 langIndex="Placeholder_FR.png"
#                 self.language_lock_down(langIndex, interfaceWidgetsAccess)
#         else:
#             for eachWidget in  interfaceWidgetsAccess:
#                 eachWidget.setEnabled(True)            
#             self.dest_field_01.setText(dummyfolder)
#             self.source_folder_field_01.clear()
#             self.source_folder_field_01.setText(mayaFolder)
#             self.r_field_01.setText(redColour)
#             self.g_field_01.setText(greenColour)
#             self.b_field_01.setText(blueColour)
#             getIndex=srcFolderStuff.findText(defaultImage)
#             srcFolderStuff.setCurrentIndex(getIndex) 



    def error(self):
        print "name required to change"
Exemplo n.º 7
0
class ActionBar(QFrame):
    """
    SIGNALS:
    @changeCurrent(PyQt_PyObject)
    @runFile(QString)
    @reopenTab(QString)
    @recentTabsModified()
    """
    def __init__(self, main_combo=False):
        super(ActionBar, self).__init__()
        self.setObjectName("actionbar")
        hbox = QHBoxLayout(self)
        hbox.setContentsMargins(1, 1, 1, 1)
        hbox.setSpacing(1)

        self.lbl_checks = QLabel('')
        self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.lbl_checks.setFixedWidth(48)
        self.lbl_checks.setVisible(False)
        hbox.addWidget(self.lbl_checks)

        self.combo = QComboBox()
        #model = QStandardItemModel()
        #self.combo.setModel(model)
        #self.combo.view().setDragDropMode(QAbstractItemView.InternalMove)
        self.combo.setMaximumWidth(300)
        self.combo.setObjectName("combotab")
        self.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
                     self.current_changed)
        self.combo.setToolTip(translations.TR_COMBO_FILE_TOOLTIP)
        self.combo.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.combo,
                     SIGNAL("customContextMenuRequested(const QPoint &)"),
                     self._context_menu_requested)
        hbox.addWidget(self.combo)

        self.symbols_combo = QComboBox()
        self.symbols_combo.setObjectName("combo_symbols")
        self.connect(self.symbols_combo, SIGNAL("activated(int)"),
                     self.current_symbol_changed)
        hbox.addWidget(self.symbols_combo)

        self.code_navigator = CodeNavigator()
        hbox.addWidget(self.code_navigator)

        self._pos_text = "Line: %d, Col: %d"
        self.lbl_position = QLabel(self._pos_text % (0, 0))
        self.lbl_position.setObjectName("position")
        self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.lbl_position)

        self.btn_close = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        if main_combo:
            self.btn_close.setObjectName('navigation_button')
            self.btn_close.setToolTip(translations.TR_CLOSE_FILE)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                         self.about_to_close_file)
        else:
            self.btn_close.setObjectName('close_split')
            self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT)
            self.connect(self.btn_close, SIGNAL("clicked()"), self.close_split)
        self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.btn_close)

    def resizeEvent(self, event):
        super(ActionBar, self).resizeEvent(event)
        if event.size().width() < 350:
            self.symbols_combo.hide()
            self.code_navigator.hide()
            self.lbl_position.hide()
        else:
            self.symbols_combo.show()
            self.code_navigator.show()
            self.lbl_position.show()

    def add_item(self, text, neditable):
        """Add a new item to the combo and add the neditable data."""
        self.combo.addItem(text, neditable)
        self.combo.setCurrentIndex(self.combo.count() - 1)

    def get_editables(self):
        editables = []
        for index in range(self.combo.count()):
            neditable = self.combo.itemData(index)
            editables.append(neditable)
        return editables

    def add_symbols(self, symbols):
        """Add the symbols to the symbols's combo."""
        self.symbols_combo.clear()
        for symbol in symbols:
            data = symbol[1]
            if data[1] == 'f':
                icon = QIcon(":img/function")
            else:
                icon = QIcon(":img/class")
            self.symbols_combo.addItem(icon, data[0])

    def set_current_symbol(self, index):
        self.symbols_combo.setCurrentIndex(index)

    def update_item_icon(self, neditable, icon):
        index = self.combo.findData(neditable)
        self.combo.setItemIcon(index, icon)

    def update_item_text(self, neditable, text):
        index = self.combo.findData(neditable)
        self.combo.setItemText(index, text)

    def current_changed(self, index):
        """Change the current item in the combo."""
        neditable = self.combo.itemData(index)
        self.emit(SIGNAL("changeCurrent(PyQt_PyObject, int)"), neditable,
                  index)

    def current_symbol_changed(self, index):
        """Change the current symbol in the combo."""
        self.emit(SIGNAL("goToSymbol(int)"), index)

    def update_line_col(self, line, col):
        """Update the line and column position."""
        self.lbl_position.setText(self._pos_text % (line, col))

    def _context_menu_requested(self, point):
        """Display context menu for the combo file."""
        if self.combo.count() == 0:
            # If there is not an Editor opened, don't show the menu
            return
        menu = QMenu()
        actionAdd = menu.addAction(translations.TR_ADD_TO_PROJECT)
        actionRun = menu.addAction(translations.TR_RUN_FILE)
        menuSyntax = menu.addMenu(translations.TR_CHANGE_SYNTAX)
        self._create_menu_syntax(menuSyntax)
        menu.addSeparator()
        actionClose = menu.addAction(translations.TR_CLOSE_FILE)
        actionCloseAll = menu.addAction(translations.TR_CLOSE_ALL_FILES)
        actionCloseAllNotThis = menu.addAction(
            translations.TR_CLOSE_OTHER_FILES)
        menu.addSeparator()
        actionSplitH = menu.addAction(translations.TR_SPLIT_VERTICALLY)
        actionSplitV = menu.addAction(translations.TR_SPLIT_HORIZONTALLY)
        menu.addSeparator()
        actionCopyPath = menu.addAction(
            translations.TR_COPY_FILE_PATH_TO_CLIPBOARD)
        actionReopen = menu.addAction(translations.TR_REOPEN_FILE)
        actionUndock = menu.addAction(translations.TR_UNDOCK_EDITOR)
        if len(settings.LAST_OPENED_FILES) == 0:
            actionReopen.setEnabled(False)
        #Connect actions
        self.connect(actionSplitH, SIGNAL("triggered()"),
                     lambda: self._split(False))
        self.connect(actionSplitV, SIGNAL("triggered()"),
                     lambda: self._split(True))
        self.connect(actionRun, SIGNAL("triggered()"), self._run_this_file)
        self.connect(actionAdd, SIGNAL("triggered()"), self._add_to_project)
        self.connect(actionClose, SIGNAL("triggered()"),
                     self.about_to_close_file)
        self.connect(actionCloseAllNotThis, SIGNAL("triggered()"),
                     self._close_all_files_except_this)
        self.connect(actionCloseAll, SIGNAL("triggered()"),
                     self._close_all_files)
        self.connect(actionCopyPath, SIGNAL("triggered()"),
                     self._copy_file_location)
        self.connect(actionReopen, SIGNAL("triggered()"),
                     self._reopen_last_tab)
        self.connect(actionUndock, SIGNAL("triggered()"), self._undock_editor)

        menu.exec_(QCursor.pos())

    def _create_menu_syntax(self, menuSyntax):
        """Create Menu with the list of syntax supported."""
        syntax = list(settings.SYNTAX.keys())
        syntax.sort()
        for syn in syntax:
            menuSyntax.addAction(syn)
            self.connect(menuSyntax, SIGNAL("triggered(QAction*)"),
                         self._reapply_syntax)

    def _reapply_syntax(self, syntaxAction):
        #TODO
        if [self.currentIndex(), syntaxAction] != self._resyntax:
            self._resyntax = [self.currentIndex(), syntaxAction]
            self.emit(SIGNAL("syntaxChanged(QWidget, QString)"),
                      self.currentWidget(), syntaxAction.text())

    def set_current_file(self, neditable):
        index = self.combo.findData(neditable)
        self.combo.setCurrentIndex(index)

    def set_current_by_index(self, index):
        self.combo.setCurrentIndex(index)

    def about_to_close_file(self, index=None):
        """Close the NFile object."""
        if index is None:
            index = self.combo.currentIndex()
        neditable = self.combo.itemData(index)
        if neditable:
            neditable.nfile.close()

    def close_split(self):
        self.emit(SIGNAL("closeSplit()"))

    def close_file(self, neditable):
        """Receive the confirmation to close the file."""
        index = self.combo.findData(neditable)
        self.combo.removeItem(index)
        return index

    def _run_this_file(self):
        """Execute the current file."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("runFile(QString)"), neditable.file_path)

    def _add_to_project(self):
        """Emit a signal to let someone handle the inclusion of the file
        inside a project."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("addToProject(QString)"), neditable.file_path)

    def _reopen_last_tab(self):
        self.emit(SIGNAL("reopenTab(QString)"),
                  settings.LAST_OPENED_FILES.pop())
        self.emit(SIGNAL("recentTabsModified()"))

    def _undock_editor(self):
        self.emit(SIGNAL("undockEditor()"))

    def _split(self, orientation):
        self.emit(SIGNAL("splitEditor(bool)"), orientation)

    def _copy_file_location(self):
        """Copy the path of the current opened file to the clipboard."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        QApplication.clipboard().setText(neditable.file_path,
                                         QClipboard.Clipboard)

    def _close_all_files(self):
        """Close all the files opened."""
        for i in range(self.combo.count()):
            self.about_to_close_file(0)

    def _close_all_files_except_this(self):
        """Close all the files except the current one."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        for i in reversed(list(range(self.combo.count()))):
            ne = self.combo.itemData(i)
            if ne is not neditable:
                self.about_to_close_file(i)
Exemplo n.º 8
0
    def create_locks_tab(self):
        self.specify_by_currency = QComboBox()

        def on_change_currency(currency):
            if currency != self.Locks_currency:
                self.Locks_currency = LOCKS_CURRENCIES[currency]
            self.specify_by_currency.clear()
            otheri = 0 if self.specify_by_currency.findText('BTC') > 0 else 1
            self.specify_by_currency.removeItem(otheri)
            self.specify_by_currency.addItem(str(LOCKS_CURRENCIES[currency]))
            self.specify_by_currency.addItem('BTC')
            self.specify_by_currency.setMaximumWidth(60)

        def on_btc_amount_change(amount):
            if amount != self.Locks_amount:
                self.Locks_amount = amount

        def on_change_action(act):
            action = LOCK_ACTIONS[act]
            if action != self.Locks_action:
                self.Locks_action = action

        def get_quote():
            specifiedCurrency = self.specify_by_currency.currentText()
            def get_lock():
                if specifiedCurrency == 'BTC':
                    amount = float(self.Locks_amount)
                    outAmount = 0
                else:
                    amount = 0
                    outAmount = float(self.Locks_amount)
                try:
                    lock = self.client.lock(amount=amount, outAmount=outAmount, currency=self.Locks_currency)
                    # print json.dumps(lock, indent=4)
                    pending_locks = self.config.get('pending_locks', [])
                    pending_locks.append(lock)
                    self.config.set_key('pending_locks', pending_locks, True)
                    return lock
                except (CoinapultError, CoinapultErrorECC) as ce:
                    QMessageBox.warning(None, _('Lock Failed'),
                                        _('Lock action failed due to reason: %s') % ce, _('OK'))

            def get_unlock():
                if specifiedCurrency == 'BTC':
                    amount = 0
                    outAmount = float(self.Locks_amount)
                else:
                    amount = float(self.Locks_amount)
                    outAmount = 0

                for addr in self.wallet.addresses():
                    u, used = self.wallet.is_used(addr)
                    if not used and u == 0:
                        self.unlock_address = addr
                        break
                try:
                    unlock = self.client.unlock(amount=amount, outAmount=outAmount,
                                                currency=str(self.Locks_currency),
                                                address=str(self.unlock_address))
                    # print json.dumps(unlock, indent=4)
                    pending_unlocks = self.config.get('pending_unlocks', [])
                    pending_unlocks.append(unlock)
                    self.config.set_key('pending_unlocks', pending_unlocks, True)
                    return unlock
                except (CoinapultError, CoinapultErrorECC) as ce:
                    QMessageBox.warning(None, _('Unlock Failed'),
                                        _('Unlock action failed due to reason: %s') % ce, _('OK'))

            self.quote_button.setDisabled(True)
            if self.Locks_action == 'Lock':
                self.waiting_dialog = WaitingDialog(w, 'Requesting Lock Quote',
                                                    get_lock, self.lock_confirm_dialog)
                self.waiting_dialog.start()
            else:
                self.waiting_dialog = WaitingDialog(w, 'Requesting Unlock Quote',
                                                    get_unlock, self.unlock_confirm_dialog)
                self.waiting_dialog.start()

        w = QWidget()
        self.tabLayout = QGridLayout(w)
        self.tabLayout.setColumnMinimumWidth(3, 400)
        self.tabLayout.setColumnStretch(0, 5)
        self.tabLayout.setHorizontalSpacing(10)

        about_locks_label = QLabel(ABOUT_LOCKS)
        about_locks_label.setWordWrap(True)
        about_locks_label.setOpenExternalLinks(True)
        self.tabLayout.addWidget(about_locks_label, 0, 2, 2, 3, Qt.AlignTop)

        self.balsLayout = QGridLayout(w)
        self.balsLayout.setColumnMinimumWidth(35, 400)
        self.balsLayout.setHorizontalSpacing(10)
        # self.balsLayout.setFrameStyle(QFrame.VLine)

        row = 0
        balw = QLabel(_("<font size='5' style='bold'>Current Locks Balances</font>"))
        # balw.setBackgroundRole(QPalette_ColorRole=QPalette_ColorRole)
        balw.setBackgroundRole(QPalette.Midlight)
        balw.setAutoFillBackground(True)
        balw.setMinimumWidth(250)
        self.balsLayout.addWidget(balw, row, 0)
        row += 1
        for cur in LOCKS_CURRENCIES:
            if cur == 'XAU':
                disp_cur = "Gold oz"
            elif cur == 'XAG':
                disp_cur = "Silver oz"
            else:
                disp_cur = cur
            curw = QLabel(_("<font size='5'>- %s</font>" % disp_cur))
            curw.setBackgroundRole(QPalette.Light)
            curw.setAutoFillBackground(True)
            curw.setMinimumWidth(250)
            self.balsLayout.addWidget(curw, row, 0)
            row += 1
        self.tabLayout.addLayout(self.balsLayout, 0, 0, 2, 3, Qt.AlignTop)

        # self.tabLayout.addWidget(QLabel(_('Estimated Total BTC Value')), row, 0)
        # self.tabLayout.addWidget(QLabel(_('- BTC')), row, 1)
        # row += 1

        self.tabLayout.addWidget(QLabel(_('What do you want to do?')), 2, 0, Qt.AlignBottom)
        # row += 1
        self.tabLayout.addWidget(QLabel(_('Which Locks asset?')), 2, 1, Qt.AlignBottom)
        # row += 1
        # row += 1

        self.tabLayout.addWidget(QLabel(_('Amount')), 2, 2, 1, 2, Qt.AlignBottom)
        # self.tabLayout.addWidget(QLabel(_('')), row, 0)
        # self.tabLayout.addWidget(QLabel(_('How much of which?')), 2, 3, Qt.AlignBottom)
        row += 1

        combo_action = QComboBox()
        combo_action.currentIndexChanged.connect(on_change_action)
        combo_action.addItems(LOCK_ACTIONS)
        combo_action.setMaximumWidth(100)
        self.tabLayout.addWidget(combo_action, 3, 0, Qt.AlignTop)

        combo_currency = QComboBox()
        combo_currency.currentIndexChanged.connect(on_change_currency)
        combo_currency.addItems(LOCKS_CURRENCIES)
        combo_currency.setMaximumWidth(60)
        self.tabLayout.addWidget(combo_currency, 3, 1, Qt.AlignTop)

        btc_amount_edit = QLineEdit('0')
        btc_amount_edit.textChanged.connect(on_btc_amount_change)
        btc_amount_edit.setMaximumWidth(100)
        self.tabLayout.addWidget(btc_amount_edit, 3, 2, Qt.AlignRight)

        # self.specify_by_currency.currentIndexChanged.connect(on_change_specify_currency)
        self.specify_by_currency.addItems([''])
        self.specify_by_currency.setMaximumWidth(60)
        self.tabLayout.addWidget(self.specify_by_currency, 3, 3, Qt.AlignLeft)
        # row += 1

        self.quote_button = QPushButton(_('Get Quote'))
        self.quote_button.clicked.connect(get_quote)
        self.quote_button.setMaximumWidth(100)
        self.tabLayout.addWidget(self.quote_button, 5, 0, Qt.AlignBottom)
        return w
Exemplo n.º 9
0
class Plugin(BasePlugin):

    button_label = _("Coinapult Locks")

    def __init__(self, config, name):
        BasePlugin.__init__(self, config, name)
        self.balance_updater = None
        self.gui = None
        self.Locks_action = None
        self.Locks_currency = None
        self.Locks_amount = None
        self.btc_rate = decimal.Decimal("0.0")
        self.wallet = None
        self.tabLayout = None
        self.quote_button = None
        self.ecc_pub_key_edit = None
        self.ecc_priv_key_edit = None
        self.ca_ok_button = None
        self.unlock_address = None
        self.specify_by_currency = None

    @hook
    def init_qt(self, gui):
        self.gui = gui
        if not self.agreed_tos():
            if self.settings_dialog():
                self.enable()
                return True
            else:
                self.disable()
                return False
        else:
            self.gui.main_window.tabs.addTab(self.create_locks_tab(), "Locks")

    @hook
    def get_locks_balances(self, r):
        bals = self.config.get('Locks_balances', LOCKS_BALS)
        r[0] = bals

    @hook
    def load_wallet(self, wallet):
        self.wallet = wallet
        authmethod = self.config.get('coinapult_auth_method', 'REST')
        if authmethod == 'REST':
            self.client = CoinapultClient(credentials={'key': self.api_key(), 'secret': self.api_secret()})
        else:
            ecc_pub = self.wallet.storage.get("coinapult_ecc_public", '')
            ecc_priv = self.wallet.storage.get("coinapult_ecc_private", '')
            try:
                self.client = CoinapultClient(ecc={'pubkey': ecc_pub, 'privkey': ecc_priv}, authmethod='ecc')
            except (CoinapultError, CoinapultErrorECC):
                self.client = None
                QMessageBox.warning(None, _('Coinapult Connection failed'),
                                    _('Failed to connect to Coinapult. Locks disabled for this session.'), _('OK'))
                self.disable()
        self.init_balances()

    def init_balances(self):
        if self.balance_updater is None:
            self.balance_updater = Balance_updater(self)
            self.balance_updater.start()
            self.gui.balance_updater = self.balance_updater
        elif not self.balance_updater.is_running:
            self.balance_updater.is_running = True
        self.gui.main_window.connect(self.gui.main_window, SIGNAL("refresh_locks_account()"),
                                     self.gui.main_window.update_status)
        self.gui.main_window.connect(self.gui.main_window, SIGNAL("refresh_locks_account()"),
                                     self.update_locks_bal_display)

    def api_key(self):
        return self.config.get("plugin_coinapult_locks_api_key")

    def api_secret(self):
        return self.config.get("plugin_coinapult_locks_api_secret")

    def agreed_tos(self):
        return self.config.get("plugin_coinapult_locks_tos", False)

    def fullname(self):
        return 'Coinapult Locks'

    def description(self):
        return _("Coinapult's Locks service lets users tie the value of their bitcoins to USD, EUR, GBP, "
                 "gold or silver.")

    def update_locks_bal_display(self):
        lock_bals = self.config.get('Locks_balances', LOCKS_BALS)
        unlock_bals = self.config.get('Locks_unbalances', LOCKS_BALS)
        row = 1
        for cur in LOCKS_CURRENCIES:
            if cur == 'XAU':
                disp_cur = 'Gold oz'
            elif cur == 'XAG':
                disp_cur = 'Silver oz'
            else:
                disp_cur = cur
            widg = self.balsLayout.itemAtPosition(row, 0)
            if unlock_bals[cur] > 0:
                widg.widget().setText("<font size='5'>%s [+%s unconfirmed] %s</font>" %
                                      (floor(lock_bals[cur]*1000)/1000, floor(unlock_bals[cur] * 1000) / 1000,
                                       disp_cur))
            else:
                widg.widget().setText("<font size='5'>%s %s</font>" % (floor(lock_bals[cur]*1000)/1000, disp_cur))
            row += 1
        # widg = self.tabLayout.itemAtPosition(row, 1)
        # widg.widget().setText('%s BTC' % lock_bals['BTC'])

    def create_locks_tab(self):
        self.specify_by_currency = QComboBox()

        def on_change_currency(currency):
            if currency != self.Locks_currency:
                self.Locks_currency = LOCKS_CURRENCIES[currency]
            self.specify_by_currency.clear()
            otheri = 0 if self.specify_by_currency.findText('BTC') > 0 else 1
            self.specify_by_currency.removeItem(otheri)
            self.specify_by_currency.addItem(str(LOCKS_CURRENCIES[currency]))
            self.specify_by_currency.addItem('BTC')
            self.specify_by_currency.setMaximumWidth(60)

        def on_btc_amount_change(amount):
            if amount != self.Locks_amount:
                self.Locks_amount = amount

        def on_change_action(act):
            action = LOCK_ACTIONS[act]
            if action != self.Locks_action:
                self.Locks_action = action

        def get_quote():
            specifiedCurrency = self.specify_by_currency.currentText()
            def get_lock():
                if specifiedCurrency == 'BTC':
                    amount = float(self.Locks_amount)
                    outAmount = 0
                else:
                    amount = 0
                    outAmount = float(self.Locks_amount)
                try:
                    lock = self.client.lock(amount=amount, outAmount=outAmount, currency=self.Locks_currency)
                    # print json.dumps(lock, indent=4)
                    pending_locks = self.config.get('pending_locks', [])
                    pending_locks.append(lock)
                    self.config.set_key('pending_locks', pending_locks, True)
                    return lock
                except (CoinapultError, CoinapultErrorECC) as ce:
                    QMessageBox.warning(None, _('Lock Failed'),
                                        _('Lock action failed due to reason: %s') % ce, _('OK'))

            def get_unlock():
                if specifiedCurrency == 'BTC':
                    amount = 0
                    outAmount = float(self.Locks_amount)
                else:
                    amount = float(self.Locks_amount)
                    outAmount = 0

                for addr in self.wallet.addresses():
                    u, used = self.wallet.is_used(addr)
                    if not used and u == 0:
                        self.unlock_address = addr
                        break
                try:
                    unlock = self.client.unlock(amount=amount, outAmount=outAmount,
                                                currency=str(self.Locks_currency),
                                                address=str(self.unlock_address))
                    # print json.dumps(unlock, indent=4)
                    pending_unlocks = self.config.get('pending_unlocks', [])
                    pending_unlocks.append(unlock)
                    self.config.set_key('pending_unlocks', pending_unlocks, True)
                    return unlock
                except (CoinapultError, CoinapultErrorECC) as ce:
                    QMessageBox.warning(None, _('Unlock Failed'),
                                        _('Unlock action failed due to reason: %s') % ce, _('OK'))

            self.quote_button.setDisabled(True)
            if self.Locks_action == 'Lock':
                self.waiting_dialog = WaitingDialog(w, 'Requesting Lock Quote',
                                                    get_lock, self.lock_confirm_dialog)
                self.waiting_dialog.start()
            else:
                self.waiting_dialog = WaitingDialog(w, 'Requesting Unlock Quote',
                                                    get_unlock, self.unlock_confirm_dialog)
                self.waiting_dialog.start()

        w = QWidget()
        self.tabLayout = QGridLayout(w)
        self.tabLayout.setColumnMinimumWidth(3, 400)
        self.tabLayout.setColumnStretch(0, 5)
        self.tabLayout.setHorizontalSpacing(10)

        about_locks_label = QLabel(ABOUT_LOCKS)
        about_locks_label.setWordWrap(True)
        about_locks_label.setOpenExternalLinks(True)
        self.tabLayout.addWidget(about_locks_label, 0, 2, 2, 3, Qt.AlignTop)

        self.balsLayout = QGridLayout(w)
        self.balsLayout.setColumnMinimumWidth(35, 400)
        self.balsLayout.setHorizontalSpacing(10)
        # self.balsLayout.setFrameStyle(QFrame.VLine)

        row = 0
        balw = QLabel(_("<font size='5' style='bold'>Current Locks Balances</font>"))
        # balw.setBackgroundRole(QPalette_ColorRole=QPalette_ColorRole)
        balw.setBackgroundRole(QPalette.Midlight)
        balw.setAutoFillBackground(True)
        balw.setMinimumWidth(250)
        self.balsLayout.addWidget(balw, row, 0)
        row += 1
        for cur in LOCKS_CURRENCIES:
            if cur == 'XAU':
                disp_cur = "Gold oz"
            elif cur == 'XAG':
                disp_cur = "Silver oz"
            else:
                disp_cur = cur
            curw = QLabel(_("<font size='5'>- %s</font>" % disp_cur))
            curw.setBackgroundRole(QPalette.Light)
            curw.setAutoFillBackground(True)
            curw.setMinimumWidth(250)
            self.balsLayout.addWidget(curw, row, 0)
            row += 1
        self.tabLayout.addLayout(self.balsLayout, 0, 0, 2, 3, Qt.AlignTop)

        # self.tabLayout.addWidget(QLabel(_('Estimated Total BTC Value')), row, 0)
        # self.tabLayout.addWidget(QLabel(_('- BTC')), row, 1)
        # row += 1

        self.tabLayout.addWidget(QLabel(_('What do you want to do?')), 2, 0, Qt.AlignBottom)
        # row += 1
        self.tabLayout.addWidget(QLabel(_('Which Locks asset?')), 2, 1, Qt.AlignBottom)
        # row += 1
        # row += 1

        self.tabLayout.addWidget(QLabel(_('Amount')), 2, 2, 1, 2, Qt.AlignBottom)
        # self.tabLayout.addWidget(QLabel(_('')), row, 0)
        # self.tabLayout.addWidget(QLabel(_('How much of which?')), 2, 3, Qt.AlignBottom)
        row += 1

        combo_action = QComboBox()
        combo_action.currentIndexChanged.connect(on_change_action)
        combo_action.addItems(LOCK_ACTIONS)
        combo_action.setMaximumWidth(100)
        self.tabLayout.addWidget(combo_action, 3, 0, Qt.AlignTop)

        combo_currency = QComboBox()
        combo_currency.currentIndexChanged.connect(on_change_currency)
        combo_currency.addItems(LOCKS_CURRENCIES)
        combo_currency.setMaximumWidth(60)
        self.tabLayout.addWidget(combo_currency, 3, 1, Qt.AlignTop)

        btc_amount_edit = QLineEdit('0')
        btc_amount_edit.textChanged.connect(on_btc_amount_change)
        btc_amount_edit.setMaximumWidth(100)
        self.tabLayout.addWidget(btc_amount_edit, 3, 2, Qt.AlignRight)

        # self.specify_by_currency.currentIndexChanged.connect(on_change_specify_currency)
        self.specify_by_currency.addItems([''])
        self.specify_by_currency.setMaximumWidth(60)
        self.tabLayout.addWidget(self.specify_by_currency, 3, 3, Qt.AlignLeft)
        # row += 1

        self.quote_button = QPushButton(_('Get Quote'))
        self.quote_button.clicked.connect(get_quote)
        self.quote_button.setMaximumWidth(100)
        self.tabLayout.addWidget(self.quote_button, 5, 0, Qt.AlignBottom)
        return w

    def enable(self):
        self.set_enabled(True)
        if self.gui:
            self.init_balances(self.gui)
        return True

    def disable(self):
        length = self.gui.main_window.tabs.count()
        for i in range(0, length):
            if self.gui.main_window.tabs.tabText(i) == "Locks":
                self.gui.main_window.tabs.removeTab(i)
        self.set_enabled(False)
        self.balance_updater.stop()
        return True

    def is_available(self):
        return True

    def requires_settings(self):
        return True

    def settings_widget(self, window):
        return EnterButton(_('Settings'), self.settings_dialog)

    def settings_dialog(self):
        def check_for_api_key(api_key):
            if api_key and len(api_key) > 12:
                self.config.set_key("plugin_coinapult_locks_api_key", str(api_key))

        def check_for_api_secret(api_secret):
            if api_secret and len(api_secret) > 12:
                self.config.set_key("plugin_coinapult_locks_api_secret", str(api_secret))

        def check_for_ecc_pub_key(pub_key):
            if pub_key and len(pub_key) > 12:
                self.wallet.storage.put("coinapult_ecc_public", str(pub_key))

        def check_for_ecc_priv_key(priv_key):
            if priv_key and len(priv_key) > 12:
                self.wallet.storage.put("coinapult_ecc_private", str(priv_key))

        def ok_clicked():
            # check_for_api_key(self.api_key_edit.text())
            # check_for_api_secret(self.api_secret_edit.text())
            check_for_ecc_pub_key(self.ecc_pub_key_edit.toPlainText())
            check_for_ecc_priv_key(self.ecc_priv_key_edit.toPlainText())
            if self.agreed_tos():
                d.accept()
            else:
                self.disable()
                return False

        def on_change_auth_method(method):
            if method == 'REST':
                self.config.set_key('coinapult_auth_method', 'REST', True)
            else:
                self.config.set_key('coinapult_auth_method', 'ECC', True)

        d = QDialog()
        d.setMaximumWidth(600)
        d.setWindowTitle("Settings")
        layout = QGridLayout(d)
        layout.setColumnMinimumWidth(1, 200)
        layout.setHorizontalSpacing(20)

        about_locks_label = QLabel(ABOUT_LOCKS)
        about_locks_label.setWordWrap(True)
        about_locks_label.setOpenExternalLinks(True)
        layout.addWidget(about_locks_label, 0, 1, 5, 1, Qt.AlignRight)

        create_account_label = QLabel(_("If you wish to use Locks, and do not already have an account, "
                                        "click here to generate your ECC keys:"))
        create_account_label.setWordWrap(True)
        create_account_label.setOpenExternalLinks(True)
        layout.addWidget(create_account_label, 0, 0)

        create_account_button = QPushButton(_('Create Account'))
        create_account_button.setMaximumWidth(120)
        create_account_button.clicked.connect(self.create_account_dialog)
        layout.addWidget(create_account_button, 1, 0, Qt.AlignTop)

        warning_label = QLabel(_("If you already have a Coinapult account, simply paste your ECC credentials below."
                                 "<br><br>"
                                 "<font color='red'>WARNING Back up the keys below somewhere safe! If you overwrite "
                                 "them here, you could lose access to your Coinapult account.</font><br><br>"
                                 "ECC public key"))
        warning_label.setWordWrap(True)
        layout.addWidget(warning_label, 3, 0, Qt.AlignBottom)
        self.ecc_pub_key_edit = QTextEdit(self.wallet.storage.get("coinapult_ecc_public", ''))
        # self.ecc_pub_key_edit.textChanged.connect(check_for_ecc_pub_key)
        layout.addWidget(self.ecc_pub_key_edit, 4, 0, Qt.AlignTop)
        # layout.setRowStretch(2, 3)

        layout.addWidget(QLabel(_('ECC private key')), 5, 0, Qt.AlignBottom)
        self.ecc_priv_key_edit = QTextEdit("hidden")
        # self.ecc_priv_key_edit.textChanged.connect(check_for_ecc_priv_key)
        layout.addWidget(self.ecc_priv_key_edit, 6, 0, Qt.AlignTop)
        # layout.setRowStretch(2, 3)

        ## Rest Layout
        # layout.addWidget(QLabel(_('Coinapult API key: ')), 0, 0)
        # self.api_key_edit = QLineEdit(self.api_key())
        # self.api_key_edit.textChanged.connect(check_for_api_key)
        # layout.addWidget(self.api_key_edit, 0, 1, 1, 2)
        #
        # layout.addWidget(QLabel(_('Coinapult API secret: ')), 1, 0)
        # self.api_secret_edit = QLineEdit("hidden")
        # self.api_key_edit.textChanged.connect(check_for_api_secret)
        # layout.addWidget(self.api_secret_edit, 1, 1, 1, 2)

        ok_button = QPushButton(_("OK"))
        ok_button.setMaximumWidth(50)
        ok_button.clicked.connect(lambda: ok_clicked())
        layout.addWidget(ok_button, 7, 0)

        if d.exec_():
            return True
        else:
            return False

    def create_account_dialog(self):
        def coinapult_signup():
            try:
                self.client.createAccount(createLocalKeys=True, changeAuthMethod=True, tag="electrum-gfk36")
                self.client.activateAccount(agree=True)
            except (CoinapultError, CoinapultErrorECC) as ce:
                QMessageBox.warning(None, _("Unable to create Coinapult account because %s" % str(ce),
                                            QString(_("OK"))))

        def signup_done(result):
            self.ca_ok_button.setDisabled(False)
            self.wallet.storage.put("coinapult_ecc_public", str(self.client.ecc_pub_pem))
            self.ecc_pub_key_edit.setText(self.client.ecc_pub_pem)
            self.wallet.storage.put("coinapult_ecc_private", str(self.client.ecc['privkey'].to_pem()))
            self.ecc_priv_key_edit.setText(str(self.client.ecc['privkey'].to_pem()))
            self.config.set_key('coinapult_auth_method', 'ECC', True)
            ecc_pub = self.wallet.storage.get("coinapult_ecc_public", '')
            ecc_priv = self.wallet.storage.get("coinapult_ecc_private", '')
            try:
                self.client = CoinapultClient(ecc={'pubkey': ecc_pub, 'privkey': ecc_priv}, authmethod='ecc')
            except (CoinapultError, CoinapultErrorECC):
                self.client = None
                QMessageBox.warning(None, _('Coinapult Connection failed'),
                                    _('Failed to connect to Coinapult. Locks disabled for this session.'), _('OK'))
            d.accept()

        def on_change_tos(checked):
            if checked:
                self.config.set_key('plugin_coinapult_locks_tos', 'checked')
            else:
                self.config.set_key('plugin_coinapult_locks_tos', 'unchecked')

        def ok_clicked():
            if self.agreed_tos():
                self.ca_ok_button.setDisabled(True)
                self.waiting_dialog = WaitingDialog(d, 'Creating your Coinapult account. One moment please...',
                                                    coinapult_signup, signup_done)
                self.waiting_dialog.start()

        d = QDialog()
        d.setWindowTitle("Create Coinapult Account")
        layout = QGridLayout(d)

        # lable = None
        text_edit = QPlainTextEdit()
        text = open(os.path.dirname(__file__) + '/lib/TERMS.txt').read()
        text_edit.setPlainText(text)
        layout.addWidget(text_edit, 0, 0)
        layout.setRowStretch(0, 8)

        layout.addWidget(QLabel(_("Do you agree to Coinapult's Terms of Service (https://coinapult.com/terms)?: ")),
                         3, 0)
        tos_checkbox = QCheckBox()
        tos_checkbox.setEnabled(True)
        tos_checkbox.setChecked(self.config.get('plugin_coinapult_locks_tos', 'unchecked') != 'unchecked')
        tos_checkbox.stateChanged.connect(on_change_tos)
        layout.addWidget(tos_checkbox, 3, 1)

        layout.addWidget(
            QLabel(_("<font color='red'>This will overwrite any Coinapult API keys in your wallet.<br>"
                     "If you do not have backups of your API keys, this will lock you out of your "  # TODO This isn't actually stored in the wallet yet...
                     "account!</font>")), 4, 0)

        self.ca_ok_button = QPushButton(_("OK"))
        self.ca_ok_button.clicked.connect(ok_clicked)
        layout.addWidget(self.ca_ok_button, 5, 1)

        if d.exec_():
            return True
        else:
            return False

    def lock_confirm_dialog(self, lock):
        def lock_clicked():
            message = "Lock %s %s for cost of %s BTC" % (
                lock['out']['expected'], lock['out']['currency'],
                lock['in']['expected'])
            self.gui.main_window.pay_from_URI("bitcoin:%s?amount=%s&message=%s" % (lock['address'],
                                                                                   lock['in']['expected'],
                                                                                   message))
            self.gui.main_window.emit(SIGNAL("refresh_locks_account()"))
            d.accept()
            pass

        self.quote_button.setDisabled(False)

        d = QDialog()
        d.setWindowTitle("Confirm Lock")
        layout = QGridLayout(d)

        row = 0
        layout.addWidget(QLabel(_('Lock %s %s for a cost of %s BTC?' % (lock['out']['expected'],
                                                                        lock['out']['currency'],
                                                                        lock['in']['expected']))), row, 0)
        layout.addWidget(QLabel(_('Exchange rate: %s' % lock['quote']['bid'])), row, 1)
        row += 1

        layout.addWidget(QLabel(_("If you wish to complete this Lock, please click 'Lock', then send %s BTC to "
                                  "%s\n\nPlease note that this transaction will take 2 confirmations to complete." %
                                  (lock['in']['expected'], lock['address']))), row, 0)
        row += 1

        lock_button = QPushButton(_("Lock"))
        lock_button.clicked.connect(lock_clicked)
        layout.addWidget(lock_button, row, 1)

        if d.exec_():
            return True
        else:
            return False

    def unlock_confirm_dialog(self, unlock):
        def unlock_clicked():
            try:
                self.client.unlockConfirm(transaction_id=unlock['transaction_id'])
                self.gui.main_window.emit(SIGNAL("refresh_locks_account()"))
                d.accept()
            except (CoinapultError, CoinapultErrorECC) as ce:
                QMessageBox.warning(None, _('Unlock Failed'),
                                    _('Unlock action failed due to reason: %s') % ce, _('OK'))

        self.quote_button.setDisabled(False)

        d = QDialog()
        d.setWindowTitle("Confirm Unlock")
        layout = QGridLayout(d)

        row = 0
        layout.addWidget(QLabel(_('Unlock %s %s and reclaim %s BTC?' % (unlock['in']['expected'],
                                                                        unlock['in']['currency'],
                                                                        unlock['out']['expected']))), row, 0)
        layout.addWidget(QLabel(_('Exchange rate: %s' % unlock['quote']['ask'])), row, 1)
        row += 1

        layout.addWidget(QLabel(_("If you wish to complete this Unlock, please click 'Unlock' below, "
                                  "then we will send %s BTC to "
                                  "%s" % (unlock['out']['expected'], self.unlock_address))), row, 0)
        row += 1

        unlock_button = QPushButton(_("Unlock"))
        unlock_button.clicked.connect(unlock_clicked)
        layout.addWidget(unlock_button, row, 1)

        if d.exec_():
            return True
        else:
            return False
Exemplo n.º 10
0
class RegistrationViewWidget(FWidget):
    """ Shows the home page  """
    def __init__(self, parent=0, *args, **kwargs):
        super(RegistrationViewWidget, self).__init__(parent=parent,
                                                     *args,
                                                     **kwargs)
        self.parent = parent

        self.parentWidget().set_window_title("FORMULAIRE D’IMMATRICULATION")
        self.title = FLabel("<h3>FORMULAIRE D’IMMATRICULATION</h3>")
        self.office = Office.select().where(Office.id == 1).get()
        self.created_date_field = FormatDate(QDate.currentDate())
        self.created_date_field.setMaximumWidth(130)
        # self.created_date_field.setInputMask('##/##/####')
        self.rue_field = IntLineEdit()
        self.porte_field = IntLineEdit()
        self.tel_field = IntLineEdit()
        self.tel_field.setInputMask('## ## ## ##')
        self.tel2_field = IntLineEdit()
        self.tel2_field.setInputMask('## ## ## ##')
        self.bp_field = IntLineEdit()
        self.email_field = LineEdit()
        self.denomination_field = LineEdit()
        self.commercial_name_field = LineEdit()
        self.declaration_date_field = FormatDate(QDate.currentDate())
        self.declaration_date_field.setMaximumWidth(130)
        self.amount_capital_social_initial = FLabel()
        self.amount_part_social_field = IntLineEdit()
        self.apports_numeraire_field = IntLineEdit()
        self.apports_numeraire_field.textChanged.connect(self.cal_total)
        self.apports_nature_field = IntLineEdit()
        self.apports_nature_field.textChanged.connect(self.cal_total)
        self.apports_industrie_field = IntLineEdit()
        self.apports_industrie_field.textChanged.connect(self.cal_total)

        self.duree_statutaire_field = IntLineEdit()
        self.duree_statutaire_field.setMaximumWidth(80)
        self.spinneret_box = QComboBox()
        self.spinneret_box.setMaximumWidth(800)

        self.activites_box = QComboBox()
        self.activites_box.setMaximumWidth(800)
        self.activites_box.currentIndexChanged.connect(self.sp_change_select)
        self.activities_list = get_activities()
        for index, value in enumerate(self.activities_list):
            self.activites_box.addItem(
                "{}".format(self.activities_list.get(value).upper()), value)
            # if self.store and self.store.name == op.name:
            #     self.box_store.setCurrentIndex(index)

        self.formes_box = QComboBox()
        self.formes_box.setMaximumWidth(800)
        self.formes_list = get_formes()
        for index, value in enumerate(self.formes_list):
            self.formes_box.addItem(
                "{}".format(self.formes_list.get(value).upper()), value)

        self.commune_list = entity_children(self.office.slug_cercle).items()
        self.commune_box = ExtendedComboBox()
        for index, value in enumerate(self.commune_list):
            self.commune_box.addItem("{}".format(value[1].upper()), value[0])
        # self.commune_box.addItems(self.commune_list)
        self.commune_box.setToolTip("commune")
        self.commune_box.currentIndexChanged.connect(self.c_change_select)

        # self.vfq_list = self.get_vfq_list()
        self.vfq_box = ExtendedComboBox()
        self.vfq_list = self.get_vfq_list()
        for index, value in enumerate(self.vfq_list):
            self.vfq_box.addItem("{}".format(self.vfq_list.get(value).upper()),
                                 value)
        self.vfq_box.setToolTip("vfq")

        formbox = QFormLayout()
        formbox.addRow(FLabel(DATE_DEMANTE), self.declaration_date_field)
        formbox.addRow(FLabel("1. " + DENOMINATION_S_SC),
                       self.denomination_field)
        formbox.addRow(FLabel("2. " + NOM_COMMERCIAL),
                       self.commercial_name_field)
        formbox.addRow(FLabel("3. " + DATE_CREATION_SC),
                       self.created_date_field)
        formbox.addRow(FLabel("4. " + ACTIVITES_E), self.activites_box)
        formbox.addRow(FLabel("5. " + FILIERE), self.spinneret_box)
        formbox.addRow(FLabel("6. " + FORME_SC), self.formes_box)
        # Capital Social Initial
        capital_formbox = QFormLayout()
        capital_formbox.addRow(FLabel("7.1. " + MONTANT_PART_S),
                               self.amount_part_social_field)
        capital_formbox.addRow(FLabel("7.2. " + MONTANT_APPORTS_NUM),
                               self.apports_numeraire_field)
        capital_formbox.addRow(FLabel("7.3. " + MONTANT_APPORTS_NAT),
                               self.apports_nature_field)
        capital_formbox.addRow(FLabel("7.4. " + MONTANT_APPORTS_INDU),
                               self.apports_industrie_field)
        self.capitalSGroupBox = QGroupBox("7. " + MONTANT_CAPITAL_SI)
        self.capitalSGroupBox.setLayout(capital_formbox)
        self.capitalSGroupBox.setStyleSheet(CSS)
        # self.capitalSGroupBox.setMaximumWidth(1300)
        # Adresse du siège social

        self.vline = QFrame()
        self.vline.setFrameShape(QFrame.VLine)
        self.vline.setFrameShadow(QFrame.Sunken)

        self.addresGroupBox = QGroupBox("8. " + ADRESSE_SS)
        self.addresGroupBox.setStyleSheet(CSS)
        addres_gribox = QGridLayout()
        addres_gribox.addWidget(FRLabel(CERCLE), 0, 0)
        addres_gribox.addWidget(FLabel(self.office.cercle_name()), 0, 1)
        addres_gribox.addWidget(FRLabel(COMMUNE), 1, 0)
        addres_gribox.addWidget(self.commune_box, 1, 1)
        # addres_gribox.addWidget(self.vline, 0, 3, 2, 5)
        addres_gribox.addWidget(FRLabel(VFQ), 2, 0)
        addres_gribox.addWidget(self.vfq_box, 2, 1)
        addres_gribox.addWidget(FRLabel(RUE), 0, 2)
        addres_gribox.addWidget(self.rue_field, 0, 3)
        addres_gribox.addWidget(FRLabel(PORTE), 1, 2)
        addres_gribox.addWidget(self.porte_field, 1, 3)
        addres_gribox.addWidget(FRLabel(BP), 0, 4)
        addres_gribox.addWidget(self.bp_field, 0, 5)
        addres_gribox.addWidget(FRLabel(EMAIL), 1, 4)
        addres_gribox.addWidget(self.email_field, 1, 5)
        addres_gribox.addWidget(FRLabel(TEL), 2, 2)
        addres_gribox.addWidget(self.tel_field, 2, 3)
        addres_gribox.addWidget(FRLabel(TEL2), 2, 4)
        addres_gribox.addWidget(self.tel2_field, 2, 5)
        # addres_gribox.setColumnStretch(6, 5)
        self.addresGroupBox.setLayout(addres_gribox)
        # self.addresGroupBox.setMaximumWidth(1300)
        # Durée statutaire de la société coopérative
        duree_fbox = QFormLayout()
        duree_fbox.addRow(FLabel("9. " + DUREE_STATUTAIRE_SC),
                          self.duree_statutaire_field)
        butt = Button_save(SAVE)
        butt.clicked.connect(self.save_and_goto_manager)
        butt_and_continous = Button_save(SAVE_AND_CONTINNUES)
        butt_and_continous.clicked.connect(self.save_and_goto_add_member)

        butt_and_continous.setMaximumWidth(300)
        duree_fbox.addRow(FLabel(""), FLabel(""))
        duree_fbox.addRow(butt, butt_and_continous)

        vbox = QVBoxLayout()
        vbox.addLayout(formbox)
        vbox.addWidget(self.capitalSGroupBox)
        vbox.addWidget(self.addresGroupBox)
        vbox.addLayout(duree_fbox)
        self.setLayout(vbox)

    def get_vfq_list(self):
        # c_dic = {}
        co_select = self.commune_box.itemData(self.commune_box.currentIndex())
        return entity_children(co_select)

    def c_change_select(self):
        self.vfq_box.clear()
        self.vfq_list = self.get_vfq_list()
        for index, value in enumerate(self.vfq_list):
            self.vfq_box.addItem("{}".format(self.vfq_list.get(value).upper()),
                                 value)

    def get_spinneret_list(self):
        # c_dic = {}
        r_select = self.activites_box.itemData(
            self.activites_box.currentIndex())
        return get_spinneret_activites(r_select)

    def sp_change_select(self):
        self.spinneret_box.clear()
        self.spinneret_list = self.get_spinneret_list()

        for index, value in enumerate(self.spinneret_list):
            self.spinneret_box.addItem(
                "{}".format(self.spinneret_list.get(value).upper()), value)

    def is_valide(self):
        if check_is_empty(self.denomination_field):
            return False

        if CooperativeCompanie.select().where(
                CooperativeCompanie.denomination ==
                self.denomination_field.text()).exists():
            field_error(
                self.denomination_field,
                "Cette dénomination existe déjà dans la base de données !")
            return False
        if check_is_empty(self.commercial_name_field):
            return False
        if check_is_empty(self.created_date_field):
            return False
        if check_is_empty(self.denomination_field):
            return False
        if check_is_empty(self.apports_numeraire_field):
            return False
        if check_is_empty(self.apports_nature_field):
            return False
        if check_is_empty(self.apports_industrie_field):
            return False
        # if check_is_empty(self.rue_field):
        #     return False
        # if check_is_empty(self.porte_field):
        #     return False
        # print(len(self.tel_field.text()))
        if len(self.tel_field.text()) != 11:
            field_error(self.tel_field, "Numéro requis")
            return False
        # if check_is_empty(self.bp_field):
        #     return False
        # if check_is_empty(self.email_field):
        #     return False
        if check_is_empty(self.duree_statutaire_field):
            return False
        # print(int(self.duree_statutaire_field.text()))
        if int(self.duree_statutaire_field.text()) > 99:
            field_error(
                self.duree_statutaire_field,
                "La durée statutaire ne peut être supérieure à 99 ans")
            return False
        return True

    def save(self):
        if not self.is_valide():
            return
        self.scoop = CooperativeCompanie()
        self.scoop.office = self.office
        self.scoop.created_date = str(self.created_date_field.text())
        self.scoop.denomination = str(self.denomination_field.text())
        self.scoop.commercial_name = str(self.commercial_name_field.text())
        self.scoop.activity = self.activites_box.itemData(
            self.activites_box.currentIndex())
        self.scoop.spinneret = self.spinneret_box.itemData(
            self.spinneret_box.currentIndex())
        self.scoop.forme = self.formes_box.itemData(
            self.formes_box.currentIndex())
        self.scoop.amount_part_social = is_int(
            self.amount_part_social_field.text())
        self.scoop.apports_numeraire = is_int(
            self.apports_numeraire_field.text())
        self.scoop.apports_nature = is_int(self.apports_nature_field.text())
        self.scoop.apports_industrie = is_int(
            self.apports_industrie_field.text())
        self.scoop.region = self.office.slug_region
        self.scoop.cercle = self.office.slug_cercle
        self.scoop.commune = self.commune_box.itemData(
            self.commune_box.currentIndex())
        self.scoop.vfq = self.vfq_box.itemData(self.vfq_box.currentIndex())
        self.scoop.rue = is_int(self.rue_field.text())
        self.scoop.porte = is_int(self.porte_field.text())
        self.scoop.tel = is_int(self.tel_field.text())
        self.scoop.tel2 = is_int(self.tel2_field.text())
        self.scoop.bp = is_int(self.bp_field.text())
        self.scoop.email = self.email_field.text()
        self.scoop.duree_statutaire = is_int(
            self.duree_statutaire_field.text())
        self.scoop.save_()
        check_list = CheckList()
        check_list.save_()
        self.dmd = Demande()
        self.dmd.check_list = check_list
        self.dmd.declaration_date = str(self.declaration_date_field.text())
        self.dmd.scoop = self.scoop
        self.dmd.status = self.dmd.ADDMEMBER
        self.dmd.save_()
        return True

    def save_and_goto_add_member(self):
        if self.save():
            from ui.member_manager import MemberManagerWidget
            self.parent.change_context(MemberManagerWidget, dmd=self.dmd)

    def save_and_goto_manager(self):
        if self.save():
            self.parent.change_context(ResgistrationManagerWidget)

    def cal_total(self):
        total = is_int(self.apports_numeraire_field.text() or 0) + is_int(
            self.apports_nature_field.text() or 0) + is_int(
                self.apports_industrie_field.text() or 0)
        self.capitalSGroupBox.setTitle("7. {} :  {}".format(
            MONTANT_CAPITAL_SI, device_amount(total)))
Exemplo n.º 11
0
class NodeList(QWidget):
    def __init__(self, parent, mainWindow, dockBrowser):
        super(NodeList, self).__init__(parent)

        self.__browsers = dockBrowser
        # Necessary
        self.type = "views"
        self.icon = QIcon(":list.png")
        self.name = ""
        self.__mainWindow = mainWindow
        self.__parent = parent

        # Specific
        self.currentIndexDir = None
        self.currentNodeDir = None

        self.g_display()
        self.initCallback(dockBrowser)

        self.loader = loader.loader()
        self.lmodules = self.loader.modules
        self.taskmanager = TaskManager()
        self.env = env.env()

    def g_display(self):
        self.setMinimumSize(QSize(400, 300))
        self.createSubMenu()
        self.vlayout = QVBoxLayout(self)
        self.hlayout = QHBoxLayout()
        self.vlayout.addLayout(self.hlayout)

        self.initListView()
        self.initThumbsView()

        self.topButton = QPushButton(self)
        self.topButton.setFixedSize(QSize(32, 32))
        self.topButton.setFlat(True)
        self.topButton.setIcon(QIcon(":previous.png"))
        self.topButton.setIconSize(QSize(32, 32))
        self.hlayout.addWidget(self.topButton)

        self.listButton = QPushButton(self)
        self.listButton.setFixedSize(QSize(32, 32))
        self.listButton.setFlat(True)
        self.listButton.setIcon(QIcon(":list.png"))
        self.listButton.setIconSize(QSize(32, 32))
        self.hlayout.addWidget(self.listButton)

        self.thumButton = QPushButton(self)
        self.thumButton.setFixedSize(QSize(32, 32))
        self.thumButton.setFlat(True)
        self.thumButton.setIcon(QIcon(":image.png"))
        self.thumButton.setIconSize(QSize(32, 32))
        self.hlayout.addWidget(self.thumButton)

        self.thumSize = QComboBox()
        self.thumSize.setMaximumWidth(100)
        self.thumSize.addItem("Small")
        self.thumSize.addItem("Medium")
        self.thumSize.addItem("Large")
        self.connect(self.thumSize, SIGNAL("currentIndexChanged(QString)"),
                     self.sizeChanged)
        self.hlayout.addWidget(self.thumSize)

        self.thumButton.setEnabled(True)
        self.thumSize.setEnabled(False)
        self.listButton.setEnabled(False)

        self.comboBoxPath = NodeComboBox(self)
        self.comboBoxPath.setMinimumSize(QSize(251, 32))
        self.comboBoxPath.setMaximumSize(QSize(16777215, 32))
        self.hlayout.addWidget(self.comboBoxPath)

    def initListView(self):
        self.ListView = ListView(self, self.__mainWindow)
        self.ListModel = ListModel(self)
        self.ListModelFilter = QSortFilterProxyModel()
        self.ListModelFilter.setDynamicSortFilter(True)
        self.ListModelFilter.setSortCaseSensitivity(Qt.CaseInsensitive)
        self.ListModelFilter.setSourceModel(self.ListModel)
        self.ListView.setModels(self.ListModel, self.ListModelFilter)
        self.ListView.setModel(self.ListModelFilter)
        self.ListView.setSubMenu(self.submenuFile)

        self.vlayout.addWidget(self.ListView)

    def initThumbsView(self):
        self.ThumbsView = ThumbsView(self.__mainWindow, self)
        self.ThumbsItemModel = ThumbsItemModel(self.ThumbsView.thread)

        self.ThumbsView.setModels(self.ThumbsItemModel)
        self.ThumbsView.setSubMenu(self.submenuFile)
        self.vlayout.addWidget(self.ThumbsView)

    def initCallback(self, dockBrowser):
        self.connect(self.topButton, SIGNAL("clicked()"), self.moveToTop)

        self.connect(self.listButton, SIGNAL("clicked()"), self.listActivated)
        self.connect(self.thumButton, SIGNAL("clicked()"), self.thumbActivated)

        self.connect(self.comboBoxPath,
                     SIGNAL("currentIndexChanged(const QString & )"),
                     self.comboBoxPathChanged)
        self.connect(ConnectorCallback.instance, SIGNAL("reload"), self.reload,
                     Qt.BlockingQueuedConnection)
        self.connect(dockBrowser.treeView, SIGNAL("changeDirectory"),
                     self.loadFolder)
        self.connect(dockBrowser.treeView, SIGNAL("reloadNodeView"),
                     self.reload)
        dockBrowser.treeView.connect(self, SIGNAL("setIndexAndExpand"),
                                     dockBrowser.treeView.setIndexAndExpand)
        dockBrowser.treeView.connect(
            self, SIGNAL("setIndex"),
            dockBrowser.treeView.setCurrentIndexForChild)

    def moveToTop(self):
        if self.currentIndexDir <> None:
            index = self.__browsers.treeItemModel.indexWithNode(
                self.currentNodeDir)
            parent = self.__browsers.treeItemModel.parent(index)
            if parent:
                self.emit(SIGNAL("setIndexAndExpand"), self, parent)
                self.currentIndexDir = parent
            else:
                self.emit(SIGNAL("setIndexAndExpand"), self, index)
                self.currentIndexDir = index

    def comboBoxPathChanged(self, text):
        node = self.comboBoxPath.getNode(str(text))
        if node.this == self.currentNodeDir.this:
            return
        index = self.comboBoxPath.getBrowserIndex(str(text))
        self.loadFolder(node, index)
        self.emit(SIGNAL("setIndex"), self, self.currentIndexDir)

#    def comboBoxModeChanged(self, index):
#        if index == 0 :
#            self.ListView.setVisible(True)
#            self.ThumbsView.setVisible(False)
#        else :
#            self.ListView.setVisible(False)
#            self.ThumbsView.setVisible(True)
#        self.reloadChangedView()

    def listActivated(self):
        self.ListView.setVisible(True)
        self.ThumbsView.setVisible(False)
        self.reloadChangedView()

        #Desactivate thumb buttons
        self.thumButton.setEnabled(True)
        self.thumSize.setEnabled(False)
        self.listButton.setEnabled(False)

    def thumbActivated(self):
        self.ListView.setVisible(False)
        self.ThumbsView.setVisible(True)
        self.reloadChangedView()

        self.thumButton.setEnabled(False)
        self.thumSize.setEnabled(True)
        self.listButton.setEnabled(True)

    def reloadChangedView(self):
        if not self.visibleRegion().isEmpty():
            view = self.viewVisible()
            if view.getModel().currentNodeDir is not None and view.getModel(
            ).currentNodeDir.this == self.currentNodeDir.this:
                return
            self.loadFolder(self.currentNodeDir, self.currentIndexDir, 1)

    # Specific type views
    def loadFolder(self, node, indexFolder=None, force=None):
        if node is None:
            return
        if self.currentNodeDir is not None:
            if force is None and self.currentNodeDir.this == node.this:
                return
        if force <> 2 and str(self) <> str(self.__browsers.getChild()):
            return

        self.currentIndexDir = indexFolder
        self.currentNodeDir = node
        self.comboBoxPath.addPathAndSelect(node, indexFolder)

        if self.ThumbsView.isVisible():
            self.ThumbsView.loadFolder(node, force)
        if self.ListView.isVisible() or force == 2:
            self.ListView.loadFolder(node)
        if force == 2:
            self.emit(SIGNAL("setIndexAndExpand"), self, self.currentIndexDir)

    def setChildSelected(self):
        if str(self.__browsers.getChild()) <> str(self):
            index = self.__browsers.treeItemModel.indexWithNode(
                self.currentNodeDir)
            self.emit(SIGNAL("setIndexAndExpand"), self, index)

    def getListCurrentItems(self):
        view = self.viewVisible()
        return view.getListCurrentItems()

    def getListCurrentNode(self):
        view = self.viewVisible()
        return view.getListCurrentNode()

    def reload(self):
        self.loadFolder(self.currentNodeDir, self.currentIndexDir, 1)

    def refreshIndexBrowser(self):
        self.emit(SIGNAL("setIndex"), self, self.currentIndexDir)

    def viewVisible(self):
        if self.ListView.isVisible():
            return self.ListView
        if self.ThumbsView.isVisible():
            return self.ThumbsView
        return self.ListView

    def changeDirectoryBrowser(self, node):
        dockNodeTree = self.__mainWindow.dockNodeTree
        currentIndex = dockNodeTree.treeView.selectionModel().currentIndex()
        if currentIndex is None:
            return
        currentItem = dockNodeTree.treeItemModel.getItem(currentIndex)
        #if not node.next.empty():
        newcurrent = currentItem.childWithNode(node)
        if not newcurrent:
            return
        #
        index = dockNodeTree.treeItemModel.index(newcurrent.childNumber(), 0,
                                                 currentIndex)
        self.emit(SIGNAL("setIndexAndExpand"), self, index)
        #    #self.loadFolder(node, index)

    ###############
    ## CONTEXT  MENU ##
    ###############
    def createSubMenu(self):
        self.extractor = Extractor(self.__mainWindow)
        self.connect(self.extractor, SIGNAL("filled"), self.launchExtract)
        self.submenuFile = QMenu()
        self.submenuFile.addAction(QIcon(":exec.png"), "Open",
                                   self.openDefault, "Listview")
        self.menuModules = self.submenuFile.addMenu(QIcon(":exec.png"),
                                                    "Open With")
        self.menuTags = MenuTags(self, self.__mainWindow,
                                 self.getListCurrentNode)
        self.submenuFile.addSeparator()
        self.submenuFile.addAction(
            QIcon(":hexedit.png"),
            QApplication.translate("ListView", "Hexeditor", None,
                                   QApplication.UnicodeUTF8),
            self.launchHexedit, "Listview")
        self.submenuFile.addAction(
            QIcon(":extract.png"),
            QApplication.translate("ListView", "Extract", None,
                                   QApplication.UnicodeUTF8),
            self.extractNodes, "Listview")
        self.submenuFile.addSeparator()
        self.submenuFile.addAction(
            QIcon(":info.png"),
            QApplication.translate("ListView", "Property", None,
                                   QApplication.UnicodeUTF8),
            self.propertyNodes, "Listview")

    def launchExtract(self):
        res = self.extractor.getArgs()
        arg = self.env.libenv.argument("gui_input")
        lnodes = self.env.libenv.ListNode()
        lnodes.thisown = 0
        for node in res["nodes"]:
            lnodes.append(node)
        arg.thisown = 0
        arg.add_path("syspath", str(res["path"]))
        arg.add_lnode("files", lnodes)
        arg.add_bool("recursive", int(res["recurse"]))
        self.taskmanager.add("extract", arg, ["thread", "gui"])

    def extractNodes(self):
        self.extractor.launch(self.getListCurrentNode())

    def openDefault(self):
        nodes = self.getListCurrentNode()
        for node in nodes:
            arg = self.env.libenv.argument("gui_input")
            arg.thisown = 0
            ft = FILETYPE()
            try:
                mod = ft.findcompattype(node)[0]
                if self.lmodules[mod]:
                    conf = self.lmodules[mod].conf
                    cdl = conf.descr_l
                    for a in cdl:
                        if a.type == "node":
                            arg.add_node(a.name, node)
                self.taskmanager.add(mod, arg, ["thread", "gui"])
            except IndexError:
                arg.add_node("file", node)
                self.taskmanager.add("hexedit", arg, ["thread", "gui"])

    def launchHexedit(self):
        nodes = self.getListCurrentNode()
        for node in nodes:
            arg = self.env.libenv.argument("gui_input")
            arg.thisown = 0
            arg.add_node("file", node)
            self.taskmanager.add("hexedit", arg, ["thread", "gui"])

    def propertyNodes(self):
        if not self.__mainWindow.QPropertyDialog.isVisible():
            self.__mainWindow.QPropertyDialog.fillInfo(
                self.currentNodeDir, self.getListCurrentNode())
            iReturn = self.__mainWindow.QPropertyDialog.exec_()
            self.__mainWindow.QPropertyDialog.removeAttr()
        else:
            QMessageBox.critical(self, "Erreur", u"This box is already open")

# CALLBACK

    def sizeChanged(self, string):
        if string == "Small":
            self.ThumbsView.configure(64, 64)
        elif string == "Medium":
            self.ThumbsView.configure(96, 96)
        elif string == "Large":
            self.ThumbsView.configure(128, 128)
Exemplo n.º 12
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
            ldslog.debug('TRPfinish')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        ldslog.debug('TRPstart')
        self.tpr.start()
        
#     def quitProcessRunner(self):
#         self.tpr.join()
#         self.tpr.quit()
#         self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()