コード例 #1
0
    def selectFile(self, fileLink=None):
        if fileLink == False:
            linetext = QFileDialog.getOpenFileName(
                self, self.tr("Select File"),
                QStandardPaths.displayName(QStandardPaths.HomeLocation),
                self.tr("Files (*.*)"))[0]
        else:
            linetext = fileLink
        if linetext != "":
            self.setWindowTitle(linetext)
            self.ui.dataFileLineEdit.setText(linetext)
            self.ui.dataTypeText.setText(linetext.split(".")[1].upper())
            if self.ui.fileParserCombo.findText(
                    linetext.split(".")[1].upper() + " Parser") != -1:
                headerDict = {}
                self.ui.fileParserCombo.setCurrentIndex(
                    self.ui.fileParserCombo.findText(
                        linetext.split(".")[1].upper() + " Parser"))
            if linetext.split(".")[1].upper() == "CTF":
                headerDict = ctf.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "ANG":
                headerDict = ang.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "XML":
                print("XML Parser used")

            self.createtablemodel = TableModelC(headerDict, self)
            self.filterModel.displayed = []
            self.filterModel.setSourceModel(self.createtablemodel)
            self.filterModel.fileType.append(linetext)
            self.createTableSearchFilterModel = QSortFilterProxyModel(self)
            self.createTableSearchFilterModel.setSourceModel(self.filterModel)
            self.createTableSearchFilterModel.setFilterKeyColumn(1)
            self.createTableSearchFilterModel.setDynamicSortFilter(True)
            self.ui.metadataTableView.setModel(
                self.createTableSearchFilterModel)
            self.treeModel = TreeModel(["Available File Metadata"], headerDict,
                                       self.createtablemodel)

            if len(self.customInputs) != 0:
                for i in range(len(self.customInputs)):
                    self.createtablemodel.beginInsertRows(
                        self.createtablemodel.index(
                            len(self.createtablemodel.metadataList), 0), i, i)
                    self.createtablemodel.metadataList.append(
                        self.customInputs[i])
                    self.createtablemodel.endInsertRows()

            self.createTreeSearchFilterModel = QSortFilterProxyModel(self)
            self.createTreeSearchFilterModel.setSourceModel(self.treeModel)
            self.createTreeSearchFilterModel.setFilterKeyColumn(0)
            self.createTreeSearchFilterModel.setDynamicSortFilter(True)
            self.createTreeSearchFilterModel.setRecursiveFilteringEnabled(True)
            self.ui.metadataTreeView.setModel(self.createTreeSearchFilterModel)
            self.treeModel.checkChanged.connect(self.filterModel.checkList)
            self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)

        self.toggleButtons()
        return True
コード例 #2
0
ファイル: mainwindow.py プロジェクト: nsmgr8/BLUsage-qt4
    def fetched_usages(self, reply):
        self.updateButton.setEnabled(True)
        self.progressBar.setHidden(True)

        if reply.error() == QNetworkReply.NoError:
            if not self.usage_model.parse(str(reply.readAll())):
                title = "Parsing error"
                message = self.usage_model.error
            else:
                title = None
                self.tree_model.deleteLater()
                self.tree_model = TreeModel(self.usage_model.usage)
                self.treeView.setModel(self.tree_model)
                self.show_lastupdate()
                self.write_usage()
        elif reply.error() in [QNetworkReply.AuthenticationRequiredError,
                               QNetworkReply.ContentAccessDenied]:
            title = "Authentication error"
            message = "Please check your account credentials."
        else:
            title = "An error occured"
            message = reply.errorString() \
                    + ".\nPlease check your internet connection."

        if title:
            QMessageBox.critical(self, title, message)
        reply.deleteLater()
コード例 #3
0
ファイル: mainwindow.py プロジェクト: nsmgr8/BLUsage-qt4
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.invoice_form = InvoiceForm(self)

        self.action_Account.triggered.connect(self.show_account_editor)
        self.action_Update.triggered.connect(self.update_usage)
        self.action_About.triggered.connect(self.about)
        self.actionInvoice.triggered.connect(self.invoice_form.show)

        self.network_access_manager = QNetworkAccessManager()
        self.network_access_manager.finished.connect(self.fetched_usages)
        self.network_access_manager.sslErrors.connect(self.allow_connection)

        self.settings = QSettings('Nasim', 'BLUsage')
        self.file_name = os.path.expanduser('~/.BLUsage.dat')

        self.usage_model = BLUsage()
        self.read_usage()
        self.tree_model = TreeModel(self.usage_model.usage)

        self.treeView.setModel(self.tree_model)
        self.treeView.resizeColumnToContents(0)

        if not self.usage_model.username:
            self.show_account_editor()

        self.treeView.header().setResizeMode(QHeaderView.Stretch)
        self.treeView.header().setResizeMode(0, QHeaderView.ResizeToContents)
        self.treeView.setAlternatingRowColors(True)
        self.accountName.setText(self.usage_model.name)
        self.progressBar.setHidden(True)
        self.show_lastupdate()
コード例 #4
0
    def restoreTemplate(self):
        #Clear data on create side
        self.createtablemodel.metadataList = []
        self.createtablemodel.hiddenList = []
        self.filterModel.displayed = []
        #open template
        linetext = QFileDialog.getOpenFileName(
            self, self.tr("Select File"),
            QStandardPaths.displayName(QStandardPaths.HomeLocation),
            self.tr("Files (*.ez)"))[0]
        if linetext != "":
            infile = open(linetext, "r")
            infile.readline()
            fileType = infile.readline()
            self.fileType = json.loads(fileType)
            infile.readline()
            newList = infile.readline()
            newList = json.loads(newList)
            newDict = infile.readline()
            newDict = json.loads(newDict)
            self.ui.dataTypeText.setText(self.fileType[0][-3:].upper())
            self.ui.fileParserCombo.setCurrentIndex(
                self.ui.fileParserCombo.findText(
                    self.fileType[0][-3:].upper() + " Parser"))
            self.ui.dataFileLineEdit.setText(self.fileType[0])
            self.createtablemodel = TableModelC(newDict, self)
            self.filterModel.displayed = []
            self.filterModel.setSourceModel(self.createtablemodel)
            self.filterModel.fileType = self.fileType
            self.createTableSearchFilterModel = QSortFilterProxyModel(self)
            self.createTableSearchFilterModel.setSourceModel(self.filterModel)
            self.createTableSearchFilterModel.setFilterKeyColumn(1)
            self.createTableSearchFilterModel.setDynamicSortFilter(True)
            self.ui.metadataTableView.setModel(
                self.createTableSearchFilterModel)
            self.treeModel = TreeModelR(["Available File Metadata"], newDict,
                                        self.createtablemodel, newList,
                                        self.filterModel)

            for i in range(len(newList)):
                if "Custom Input" in newList[i]["Source"]:
                    self.numCustoms += 1
                    self.customInputs.append(newList[i])
                    self.createtablemodel.beginInsertRows(
                        self.createtablemodel.index(
                            len(self.createtablemodel.metadataList), 0), i, i)
                    self.createtablemodel.metadataList.append(newList[i])
                    self.createtablemodel.endInsertRows()

            self.createTreeSearchFilterModel = QSortFilterProxyModel(self)
            self.createTreeSearchFilterModel.setSourceModel(self.treeModel)
            self.createTreeSearchFilterModel.setFilterKeyColumn(0)
            self.createTreeSearchFilterModel.setDynamicSortFilter(True)
            self.createTreeSearchFilterModel.setRecursiveFilteringEnabled(True)
            self.ui.metadataTreeView.setModel(self.createTreeSearchFilterModel)
            self.treeModel.checkChanged.connect(self.filterModel.checkList)
            self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)
            self.ui.TabWidget.setCurrentIndex(0)
コード例 #5
0
    def _openWorkDir(self, wd=None, reopen=False):
        '''打开工作目录'''
        if wd is None:
            wd = fs.FS.getRecentDirs()[-1]
        if wd == self.basedir:
            return
        print("--openWorkDir:" + wd)
        tree = self.tree
        self.basedir = wd  #
        self.fs = fs.FS(self.basedir)
        model = TreeModel(None, self.fs.loadDir())
        tree.setModel(model)
        for i in range(1, model.columnCount()):
            tree.setColumnHidden(i, True)  # 隐藏其它列

        fs.FS.addRecentDir(wd)

        if not reopen:
            has_pass = self.fs.getConf("has_pass")
            if has_pass == "True":
                self.pswd = de.inputPassword(self)
                self.has_pass = True
            else:
                self.pswd = ""
                self.has_pass = False

        last_open = self.fs.getConf("last_open")
        if last_open != "":
            self.__openNote(self.fs.apath(last_open))
        win_geo = self.fs.getConf("window_geometry")
        if win_geo != "":
            v = [int(i) for i in win_geo.split(",")]
            self.win_geo = QtCore.QRect(v[0], v[1], v[2], v[3])

        self.last_sel = self._expand_opened_tree(last_open, tree)
        if not hasattr(self, 'selchangedevent'):
            self.tree.selectionModel().selectionChanged.connect(
                self.treeSelChg)  #这个放在上个语句前, 有打不开的情况
            self.selchangedevent = True
コード例 #6
0
    def __init__(self):
        QMainWindow.__init__(self)

        items = []
        items.append(TreeNode("Root"))
        items[0].addChild(TreeNode(["Leaf A", "a", "b"]))
        items[0].addChild(TreeNode(["Leaf B", "c", "d"]))
        items[0].child(1).addChild(TreeNode(["Sub Leaf", "e", "f"]))

        self.setWindowTitle("Qt Demo")
        tree = QTreeView()
        tree.setModel(TreeModel(items))
        tree.setHeaderHidden(True)
        tree.setColumnWidth(0, 150)
        self.setCentralWidget(tree)
コード例 #7
0
ファイル: treecontroller.py プロジェクト: REC17/cadnano2
    def __init__(self, treeview):
        super(TreeController, self).__init__()
        self.treeview = treeview
        self.treeview.setSelectionBehavior(QTreeView.SelectItems)
        self.treeview.setUniformRowHeights(True)
        headers = ["item", "visible", "lock"]
        self.treemodel = TreeModel(self.treeview)
        self.treemodel.headers = headers
        self.treeview.setDragDropMode(QAbstractItemView.InternalMove)
        #self.win.treeview.setItemDelegateForColumn(0, QString())
        self.treeview.setAllColumnsShowFocus(True)
        self.treeview.setModel(self.treemodel)

        # insert the base level assembly
        index = self.treeview.currentIndex()
        nodeparent = self.treemodel.nodeFromIndex(index)
        node = AssemblyNode("Assembly", Assembly(), None, None)

        if self.treemodel.insertRow(0, index, node):
            # set index to the inserted child
            index = self.treemodel.index(0, 0, index)
            self.setCurrentIndex(index)
        # end if
        self.createConnections()
コード例 #8
0
    def read_file(self):
        """Build tree = treelib.Tree() to facilitate displaying the CAD model and

        constructing the tree view showing the assembly/component relationships.
        Each node of self.tree contains the following:
        (Name, UID, ParentUID, {Data}) where the Data keys are:
        'a' (isAssy?), 'l' (TopLoc_Location), 'c' (Quantity_Color), 's' (TopoDS_Shape)
        """
        logger.info("Reading STEP file")
        tmodel = TreeModel("STEP")
        self.shape_tool = tmodel.shape_tool
        self.color_tool = tmodel.color_tool

        step_reader = STEPCAFControl_Reader()
        step_reader.SetColorMode(True)
        step_reader.SetLayerMode(True)
        step_reader.SetNameMode(True)
        step_reader.SetMatMode(True)

        status = step_reader.ReadFile(self.filename)
        if status == IFSelect_RetDone:
            logger.info("Transfer doc to STEPCAFControl_Reader")
            step_reader.Transfer(tmodel.doc)

        labels = TDF_LabelSequence()
        self.shape_tool.GetShapes(labels)
        logger.info('Number of labels at root : %i', labels.Length())
        try:
            rootlabel = labels.Value(1) # First label at root
        except RuntimeError:
            return
        name = self.getName(rootlabel)
        logger.info('Name of root label: %s', name)
        isAssy = self.shape_tool.IsAssembly(rootlabel)
        logger.info("First label at root holds an assembly? %s", isAssy)
        if isAssy:
            # If first label at root holds an assembly, it is the Top Assembly.
            # Through this label, the entire assembly is accessible.
            # there is no need to examine other labels at root explicitly.
            topLoc = TopLoc_Location()
            topLoc = self.shape_tool.GetLocation(rootlabel)
            self.assyLocStack.append(topLoc)
            entry = rootlabel.EntryDumpToString()
            logger.debug("Entry: %s", entry)
            logger.debug("Top assy name: %s", name)
            # Create root node for top assy
            newAssyUID = self.getNewUID()
            self.tree.create_node(name, newAssyUID, None,
                                  {'a': True, 'l': None, 'c': None, 's': None})
            self.assyUidStack.append(newAssyUID)
            topComps = TDF_LabelSequence() # Components of Top Assy
            subchilds = False
            isAssy = self.shape_tool.GetComponents(rootlabel, topComps, subchilds)
            logger.debug("Is Assembly? %s", isAssy)
            logger.debug("Number of components: %s", topComps.Length())
            logger.debug("Is Reference? %s", self.shape_tool.IsReference(rootlabel))
            if topComps.Length():
                self.findComponents(rootlabel, topComps)
        else:
            # Labels at root can hold solids or compounds (which are 'crude' assemblies)
            # Either way, we will need to create a root node in self.tree
            newAssyUID = self.getNewUID()
            self.tree.create_node(os.path.basename(self.filename),
                                  newAssyUID, None,
                                  {'a': True, 'l': None, 'c': None, 's': None})
            self.assyUidStack = [newAssyUID]
            for j in range(labels.Length()):
                label = labels.Value(j+1)
                name = self.getName(label)
                isAssy = self.shape_tool.IsAssembly(label)
                logger.debug("Label %i is assembly?: %s", j+1, isAssy)
                shape = self.shape_tool.GetShape(label)
                color = self.getColor(shape)
                isSimpleShape = self.shape_tool.IsSimpleShape(label)
                logger.debug("Is Simple Shape? %s", isSimpleShape)
                shapeType = shape.ShapeType()
                logger.debug("The shape type is: %i", shapeType)
                if shapeType == 0:
                    logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_COMPOUND")
                    topo = TopologyExplorer(shape)
                    #topo = aocutils.topology.Topo(shape)
                    logger.debug("Nb of compounds : %i", topo.number_of_compounds())
                    logger.debug("Nb of solids : %i", topo.number_of_solids())
                    logger.debug("Nb of shells : %i", topo.number_of_shells())
                    newAssyUID = self.getNewUID()
                    for i, solid in enumerate(topo.solids()):
                        name = "P%s" % str(i+1)
                        self.tree.create_node(name, self.getNewUID(),
                                              self.assyUidStack[-1],
                                              {'a': False, 'l': None,
                                               'c': color, 's': solid})
                elif shapeType == 2:
                    logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_SOLID")
                    self.tree.create_node(name, self.getNewUID(),
                                          self.assyUidStack[-1],
                                          {'a': False, 'l': None,
                                           'c': color, 's': shape})
                elif shapeType == 3:
                    logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_SHELL")
                    self.tree.create_node(name, self.getNewUID(),
                                          self.assyUidStack[-1],
                                          {'a': False, 'l': None,
                                           'c': color, 's': shape})

        return tmodel.doc  # <class 'OCC.Core.TDocStd.TDocStd_Document'>
コード例 #9
0
ファイル: mainwindow.py プロジェクト: nsmgr8/BLUsage-qt4
class MainWindow(QMainWindow, Ui_MainWindow):

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

        self.invoice_form = InvoiceForm(self)

        self.action_Account.triggered.connect(self.show_account_editor)
        self.action_Update.triggered.connect(self.update_usage)
        self.action_About.triggered.connect(self.about)
        self.actionInvoice.triggered.connect(self.invoice_form.show)

        self.network_access_manager = QNetworkAccessManager()
        self.network_access_manager.finished.connect(self.fetched_usages)
        self.network_access_manager.sslErrors.connect(self.allow_connection)

        self.settings = QSettings('Nasim', 'BLUsage')
        self.file_name = os.path.expanduser('~/.BLUsage.dat')

        self.usage_model = BLUsage()
        self.read_usage()
        self.tree_model = TreeModel(self.usage_model.usage)

        self.treeView.setModel(self.tree_model)
        self.treeView.resizeColumnToContents(0)

        if not self.usage_model.username:
            self.show_account_editor()

        self.treeView.header().setResizeMode(QHeaderView.Stretch)
        self.treeView.header().setResizeMode(0, QHeaderView.ResizeToContents)
        self.treeView.setAlternatingRowColors(True)
        self.accountName.setText(self.usage_model.name)
        self.progressBar.setHidden(True)
        self.show_lastupdate()

    def show_account_editor(self):
        AccountDialog(self.usage_model, self).exec_()
        self.accountName.setText(self.usage_model.name)
        self.show_lastupdate()
        self.write_usage()

    def about(self):
        QMessageBox.about(self, "BLUsage",
"""Bangla Lion bandwidth usage viewer.

    Version 2.0
    Author: M. Nasimul Haque
    email: [email protected]
    Web: http://www.nasim.me.uk""")

    def update_usage(self):
        if not all([self.usage_model.username, self.usage_model.password]):
            QMessageBox.critical(self, 'No account',
                                 'Please enter your account details first.')
            return

        request = QNetworkRequest(QUrl(self.usage_model.user_endpoint))
        self.network_access_manager.post(request, self.usage_model.post_data)

        self.updateButton.setEnabled(False)
        self.progressBar.setHidden(False)
        self.progressBar.setValue(0)
        self.statusBar.showMessage("Please wait...")

    def fetched_usages(self, reply):
        self.updateButton.setEnabled(True)
        self.progressBar.setHidden(True)

        if reply.error() == QNetworkReply.NoError:
            if not self.usage_model.parse(str(reply.readAll())):
                title = "Parsing error"
                message = self.usage_model.error
            else:
                title = None
                self.tree_model.deleteLater()
                self.tree_model = TreeModel(self.usage_model.usage)
                self.treeView.setModel(self.tree_model)
                self.show_lastupdate()
                self.write_usage()
        elif reply.error() in [QNetworkReply.AuthenticationRequiredError,
                               QNetworkReply.ContentAccessDenied]:
            title = "Authentication error"
            message = "Please check your account credentials."
        else:
            title = "An error occured"
            message = reply.errorString() \
                    + ".\nPlease check your internet connection."

        if title:
            QMessageBox.critical(self, title, message)
        reply.deleteLater()

    def allow_connection(self, reply):
        reply.ignoreSslErrors()

    def read_usage(self):
        self.usage_model.name = self.settings.value('name')
        self.usage_model.username = self.settings.value('username')
        self.usage_model.password = self.settings.value('password')
        self.usage_model.last_update = self.settings.value('last_update')
        self.usage_model.capKB = int(self.settings.value('cap') or 0)
        self.usage_model.totalKB = int(self.settings.value('total') or 0)

        start = self.settings.value('start')
        if not start:
            today = QDate.currentDate()
            start = QDate(today.year(), today.month(), 1)
        self.usage_model.start = start
        end = self.settings.value('end')
        if not end:
            end = start.addDays(29)
        self.usage_model.end = end

    def write_usage(self):
        self.settings.setValue('name', self.usage_model.name)
        self.settings.setValue('username', self.usage_model.username)
        self.settings.setValue('password', self.usage_model.password)
        self.settings.setValue('start', self.usage_model.start)
        self.settings.setValue('end', self.usage_model.end)
        self.settings.setValue('last_update', self.usage_model.last_update)
        self.settings.setValue('cap', self.usage_model.capKB)
        self.settings.setValue('total', self.usage_model.totalKB)

    def show_lastupdate(self):
        self.totalLabel.setText("Totals usage: <b>%s</b>" %
                (self.usage_model.smart_bytes(self.usage_model.totalKB),))
        remaining = self.usage_model.remaining()
        if isinstance(remaining, int):
            self.remainingLabel.setText("Remaining: <b>%s</b>" %
                    (self.usage_model.smart_bytes(remaining),))
        else:
            self.remainingLabel.setText("Remaining: <b>Unlimited</b>")

        try:
            if not self.usage_model.last_update:
                self.statusBar.showMessage("Ready")
            else:
                self.statusBar.showMessage("Last updated on: " +
                    self.usage_model.last_update.toString())
        except:
            pass
コード例 #10
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.hyperthoughtui = HyperthoughtDialogImpl()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.TabWidget.setCurrentWidget(self.ui.CreateTemplateTab)
        self.ui.actionHelp.triggered.connect(self.help)
        self.ui.actionOpenPackage.triggered.connect(self.openPackage)
        self.ui.actionSave_Package.triggered.connect(self.savePackageAs)
        self.ui.actionClose.triggered.connect(self.close)
        self.ui.actionSave_Template.triggered.connect(self.saveTemplate)
        self.ui.actionOpen_Template.triggered.connect(self.restoreTemplate)
        self.ui.dataFileSelect.clicked.connect(self.selectFile)
        self.ui.hyperthoughtTemplateSelect.clicked.connect(self.selectTemplate)
        self.ui.saveTemplateButton.clicked.connect(self.saveTemplate)
        self.ui.otherDataFileSelect.clicked.connect(self.extractFile)
        self.ui.hyperthoughtUploadButton.clicked.connect(
            self.uploadToHyperthought)
        self.setAcceptDrops(True)
        self.numCustoms = 0
        self.customInputs = []
        self.templateFilePath = ""

        aTree = {}
        self.createtablemodel = TableModelC(aTree, self)
        self.filterModel = FilterModel(self)
        self.filterModel.setSourceModel(self.createtablemodel)
        self.ui.metadataTableView.setModel(self.filterModel)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_SOURCE_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_HTNAME_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_SOURCEVAL_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_HTVALUE_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.setColumnWidth(
            self.createtablemodel.K_USESOURCE_COL_INDEX,
            self.width() * .1)

        self.checkboxDelegate = CheckBoxDelegate()
        self.createtrashDelegate = TrashDelegate()
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_USESOURCE_COL_INDEX, self.checkboxDelegate)
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_EDITABLE_COL_INDEX, self.checkboxDelegate)
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_REMOVE_COL_INDEX, self.createtrashDelegate)
        self.ui.metadataTableView.setColumnWidth(
            self.createtablemodel.K_REMOVE_COL_INDEX,
            self.width() * .05)

        self.treeModel = TreeModel(["Available File Metadata"], aTree,
                                   self.createtablemodel)
        self.ui.metadataTreeView.setModel(self.treeModel)
        self.treeModel.checkChanged.connect(self.filterModel.checkList)
        self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)
        self.editableKeys = []

        self.usetablemodel = TableModelU(self, [], self.editableKeys)
        self.usefilterModel = FilterModelU(self)
        self.usefilterModel.setSourceModel(self.usetablemodel)
        self.ui.useTemplateTableView.setModel(self.usefilterModel)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTKEY_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTVALUE_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_SOURCE_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_USESOURCE_COL_INDEX,
            self.width() * .1)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTANNOTATION_COL_INDEX,
            self.width() * .1)
        self.usetrashDelegate = TrashDelegate()
        self.ui.useTemplateTableView.setItemDelegateForColumn(
            self.usetablemodel.K_USESOURCE_COL_INDEX, self.checkboxDelegate)
        self.ui.useTemplateTableView.setItemDelegateForColumn(
            self.usetablemodel.K_REMOVE_COL_INDEX, self.usetrashDelegate)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_REMOVE_COL_INDEX,
            self.width() * .075)
        self.usetrashDelegate.pressed.connect(self.handleRemoveUse)

        self.uselistmodel = ListModel(self, self.usetablemodel, [])
        self.ui.useTemplateListView.setModel(self.uselistmodel)
        self.uselistmodel.rowRemoved.connect(self.toggleButtons)
        self.uselistmodel.rowAdded.connect(self.toggleButtons)

        self.useFileDelegate = UseFileDelegate(self)
        self.ui.useTemplateListView.setItemDelegate(self.useFileDelegate)

        self.ui.useTemplateListView.clicked.connect(
            self.removeRowfromUsefileType)

        self.addAppendButton()
        self.ui.TabWidget.currentChanged.connect(self.movethedamnbutton)
        self.appendSourceFilesButton.clicked.connect(self.addFile)
        self.ui.appendCreateTableRowButton.clicked.connect(
            self.addCreateTableRow)
        self.ui.appendUseTableRowButton.clicked.connect(self.addUseTableRow)
        self.ui.hyperthoughtLocationButton.clicked.connect(
            self.hyperthoughtui.exec)
        self.ui.usetableSearchBar.textChanged.connect(self.filterUseTable)
        self.ui.createTemplateListSearchBar.textChanged.connect(
            self.filterCreateTable)
        self.ui.createTemplateTreeSearchBar.textChanged.connect(
            self.filterCreateTree)
        self.ui.addMetadataFileCheckBox.stateChanged.connect(
            self.checkFileList)

        self.fileType = ""
        self.accessKey = ""
        self.folderuuid = ""
        self.mThread = QThread()
        self.uploader = Uploader()
        self.uploader.moveToThread(self.mThread)
        self.mThread.start()

        self.createUpload.connect(self.uploader.performUpload)
        self.hyperthoughtui.apiSubmitted.connect(self.acceptKey)
        self.hyperthoughtui.finished.connect(self.getLocation)
        self.ui.hyperthoughtTemplateLineEdit.installEventFilter(self)
        self.ui.otherDataFileLineEdit.installEventFilter(self)
        self.ui.dataFileLineEdit.installEventFilter(self)
コード例 #11
0
class MainWindow(QMainWindow):
    createUpload = Signal(list, htauthcontroller.HTAuthorizationController,
                          str, list)

    def __init__(self):
        super(MainWindow, self).__init__()
        self.hyperthoughtui = HyperthoughtDialogImpl()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.TabWidget.setCurrentWidget(self.ui.CreateTemplateTab)
        self.ui.actionHelp.triggered.connect(self.help)
        self.ui.actionOpenPackage.triggered.connect(self.openPackage)
        self.ui.actionSave_Package.triggered.connect(self.savePackageAs)
        self.ui.actionClose.triggered.connect(self.close)
        self.ui.actionSave_Template.triggered.connect(self.saveTemplate)
        self.ui.actionOpen_Template.triggered.connect(self.restoreTemplate)
        self.ui.dataFileSelect.clicked.connect(self.selectFile)
        self.ui.hyperthoughtTemplateSelect.clicked.connect(self.selectTemplate)
        self.ui.saveTemplateButton.clicked.connect(self.saveTemplate)
        self.ui.otherDataFileSelect.clicked.connect(self.extractFile)
        self.ui.hyperthoughtUploadButton.clicked.connect(
            self.uploadToHyperthought)
        self.setAcceptDrops(True)
        self.numCustoms = 0
        self.customInputs = []
        self.templateFilePath = ""

        aTree = {}
        self.createtablemodel = TableModelC(aTree, self)
        self.filterModel = FilterModel(self)
        self.filterModel.setSourceModel(self.createtablemodel)
        self.ui.metadataTableView.setModel(self.filterModel)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_SOURCE_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_HTNAME_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_SOURCEVAL_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.horizontalHeader().setSectionResizeMode(
            self.createtablemodel.K_HTVALUE_COL_INDEX,
            QHeaderView.ResizeToContents)
        self.ui.metadataTableView.setColumnWidth(
            self.createtablemodel.K_USESOURCE_COL_INDEX,
            self.width() * .1)

        self.checkboxDelegate = CheckBoxDelegate()
        self.createtrashDelegate = TrashDelegate()
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_USESOURCE_COL_INDEX, self.checkboxDelegate)
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_EDITABLE_COL_INDEX, self.checkboxDelegate)
        self.ui.metadataTableView.setItemDelegateForColumn(
            self.createtablemodel.K_REMOVE_COL_INDEX, self.createtrashDelegate)
        self.ui.metadataTableView.setColumnWidth(
            self.createtablemodel.K_REMOVE_COL_INDEX,
            self.width() * .05)

        self.treeModel = TreeModel(["Available File Metadata"], aTree,
                                   self.createtablemodel)
        self.ui.metadataTreeView.setModel(self.treeModel)
        self.treeModel.checkChanged.connect(self.filterModel.checkList)
        self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)
        self.editableKeys = []

        self.usetablemodel = TableModelU(self, [], self.editableKeys)
        self.usefilterModel = FilterModelU(self)
        self.usefilterModel.setSourceModel(self.usetablemodel)
        self.ui.useTemplateTableView.setModel(self.usefilterModel)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTKEY_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTVALUE_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_SOURCE_COL_INDEX,
            self.width() * .25)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_USESOURCE_COL_INDEX,
            self.width() * .1)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_HTANNOTATION_COL_INDEX,
            self.width() * .1)
        self.usetrashDelegate = TrashDelegate()
        self.ui.useTemplateTableView.setItemDelegateForColumn(
            self.usetablemodel.K_USESOURCE_COL_INDEX, self.checkboxDelegate)
        self.ui.useTemplateTableView.setItemDelegateForColumn(
            self.usetablemodel.K_REMOVE_COL_INDEX, self.usetrashDelegate)
        self.ui.useTemplateTableView.setColumnWidth(
            self.usetablemodel.K_REMOVE_COL_INDEX,
            self.width() * .075)
        self.usetrashDelegate.pressed.connect(self.handleRemoveUse)

        self.uselistmodel = ListModel(self, self.usetablemodel, [])
        self.ui.useTemplateListView.setModel(self.uselistmodel)
        self.uselistmodel.rowRemoved.connect(self.toggleButtons)
        self.uselistmodel.rowAdded.connect(self.toggleButtons)

        self.useFileDelegate = UseFileDelegate(self)
        self.ui.useTemplateListView.setItemDelegate(self.useFileDelegate)

        self.ui.useTemplateListView.clicked.connect(
            self.removeRowfromUsefileType)

        self.addAppendButton()
        self.ui.TabWidget.currentChanged.connect(self.movethedamnbutton)
        self.appendSourceFilesButton.clicked.connect(self.addFile)
        self.ui.appendCreateTableRowButton.clicked.connect(
            self.addCreateTableRow)
        self.ui.appendUseTableRowButton.clicked.connect(self.addUseTableRow)
        self.ui.hyperthoughtLocationButton.clicked.connect(
            self.hyperthoughtui.exec)
        self.ui.usetableSearchBar.textChanged.connect(self.filterUseTable)
        self.ui.createTemplateListSearchBar.textChanged.connect(
            self.filterCreateTable)
        self.ui.createTemplateTreeSearchBar.textChanged.connect(
            self.filterCreateTree)
        self.ui.addMetadataFileCheckBox.stateChanged.connect(
            self.checkFileList)

        self.fileType = ""
        self.accessKey = ""
        self.folderuuid = ""
        self.mThread = QThread()
        self.uploader = Uploader()
        self.uploader.moveToThread(self.mThread)
        self.mThread.start()

        self.createUpload.connect(self.uploader.performUpload)
        self.hyperthoughtui.apiSubmitted.connect(self.acceptKey)
        self.hyperthoughtui.finished.connect(self.getLocation)
        self.ui.hyperthoughtTemplateLineEdit.installEventFilter(self)
        self.ui.otherDataFileLineEdit.installEventFilter(self)
        self.ui.dataFileLineEdit.installEventFilter(self)

    def acceptKey(self, apikey):
        self.accessKey = apikey

    def addCreateTableRow(self):
        self.createtablemodel.addEmptyRow(self.numCustoms)
        self.numCustoms += 1

    def addFile(self):
        linetexts = QFileDialog.getOpenFileNames(
            self, self.tr("Select File"),
            QStandardPaths.displayName(QStandardPaths.HomeLocation),
            self.tr("Files (*.ctf *.xml *.ang)"))[0]
        for line in linetexts:
            self.uselistmodel.addRow(line)
        self.toggleButtons()

    def addAppendButton(self):
        self.appendSourceFilesButton = QToolButton(self.ui.useTemplateListView)
        icon = QApplication.style().standardIcon(QStyle.SP_FileIcon)

    def addUseTableRow(self):
        self.usetablemodel.addEmptyRow()

    def checkFileList(self, checked):
        if checked == Qt.Checked:
            if self.ui.otherDataFileLineEdit.text() != "":
                self.uselistmodel.addRow(self.ui.otherDataFileLineEdit.text())
        elif checked == Qt.Unchecked:
            if self.ui.otherDataFileLineEdit.text(
            ) in self.uselistmodel.metadataList:
                rowIndex = self.uselistmodel.metadataList.index(
                    self.ui.otherDataFileLineEdit.text())
                self.uselistmodel.removeRow(rowIndex)

    def closeEvent(self, event):
        self.mThread.quit()
        self.mThread.wait(250)

    def extractFile(self, fileLink=False):
        if fileLink == False:
            linetext = QFileDialog.getOpenFileName(
                self, self.tr("Select File"),
                QStandardPaths.displayName(QStandardPaths.HomeLocation),
                self.tr("Files (*" + self.fileType + ")"))[0]
        else:
            linetext = fileLink
        if linetext != "":
            self.setWindowTitle(linetext)
            self.ui.dataTypeText.setText(linetext.split(".")[1].upper())
            self.ui.otherDataFileLineEdit.setText(linetext)
            if self.ui.addMetadataFileCheckBox.checkState() == Qt.Checked:
                self.uselistmodel.removeAllRows()
                self.uselistmodel.addRow(linetext)
                self.toggleButtons()
            if self.ui.fileParserCombo.findText(
                    linetext.split(".")[1].upper() + " Parser") != -1:
                headerDict = {}
                self.ui.fileParserCombo.setCurrentIndex(
                    self.ui.fileParserCombo.findText(
                        linetext.split(".")[1].upper() + " Parser"))
            if linetext.split(".")[1].upper() == "CTF":
                headerDict = ctf.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "ANG":
                headerDict = ang.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "XML":
                print("XML Parser used")

            if self.templatedata:
                self.usetablemodel.metadataList = []
                self.usefilterModel = FilterModelU(self)
                self.usefilterModel.setSourceModel(self.usetablemodel)
                self.unusedTreeModel = TreeModelU(["Available File Metadata"],
                                                  headerDict,
                                                  self.usetablemodel,
                                                  self.editableKeys)
                self.templatelist = []
                self.templatesources = []
                for i in range(len(self.templatedata)):
                    self.templatelist.append(self.templatedata[i])
                    if "Custom Input" not in self.templatedata[i]["Source"]:
                        self.templatesources.append("/".join(
                            self.templatedata[i]['Source'].split("/")[1:]))
                    else:
                        self.usetablemodel.addExistingRow(self.templatedata[i])
                self.usesearchFilterModel = QSortFilterProxyModel(self)
                self.usesearchFilterModel.setSourceModel(self.usefilterModel)
                self.usesearchFilterModel.setFilterKeyColumn(0)
                self.usesearchFilterModel.setDynamicSortFilter(True)
                self.ui.useTemplateTableView.setModel(
                    self.usesearchFilterModel)

        self.toggleButtons()

    def eventFilter(self, object, event):
        if object == self.ui.hyperthoughtTemplateLineEdit:
            if event.type() == QEvent.DragEnter:
                if str(event.mimeData().urls()[0])[-5:-2] == ".ez":
                    event.acceptProposedAction()
            if (event.type() == QEvent.Drop):
                if str(event.mimeData().urls()[0])[-5:-2] == ".ez":
                    event.acceptProposedAction()
                    self.loadTemplateFile(
                        event.mimeData().urls()[0].toLocalFile())
        if object == self.ui.otherDataFileLineEdit:
            if event.type() == QEvent.DragEnter:
                if str(event.mimeData().urls()[0])[-6:-2] == self.fileType:
                    event.acceptProposedAction()
            if (event.type() == QEvent.Drop):
                if str(event.mimeData().urls()[0])[-6:-2] == self.fileType:
                    event.acceptProposedAction()
                    self.extractFile(event.mimeData().urls()[0].toLocalFile())
        if object == self.ui.dataFileLineEdit:
            if event.type() == QEvent.DragEnter:
                if str(event.mimeData().urls()[0])[-6:-2] == ".ctf" or str(
                        event.mimeData().urls()[0])[-6:-2] == ".ang":
                    event.acceptProposedAction()
            if (event.type() == QEvent.Drop):
                if str(event.mimeData().urls()[0])[-6:-2] == ".ctf" or str(
                        event.mimeData().urls()[0])[-6:-2] == ".ang":
                    event.acceptProposedAction()
                    self.selectFile(event.mimeData().urls()[0].toLocalFile())

        return QMainWindow.eventFilter(self, object, event)

    def filterCreateTable(self):
        self.createTableSearchFilterModel.invalidate()
        self.createTableSearchFilterModel.setFilterCaseSensitivity(
            Qt.CaseInsensitive)
        self.createTableSearchFilterModel.setFilterWildcard(
            "*" + self.ui.createTemplateListSearchBar.text() + "*")

    def filterCreateTree(self):
        self.createTreeSearchFilterModel.invalidate()
        self.createTreeSearchFilterModel.setFilterCaseSensitivity(
            Qt.CaseInsensitive)
        self.createTreeSearchFilterModel.setFilterWildcard(
            "*" + self.ui.createTemplateTreeSearchBar.text() + "*")

    def filterUseTable(self):
        self.usesearchFilterModel.invalidate()
        self.usesearchFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.usesearchFilterModel.setFilterWildcard(
            "*" + self.ui.usetableSearchBar.text() + "*")

    def getLocation(self):
        remoteDirPath = self.hyperthoughtui.getUploadDirectory()
        self.folderuuid = ht_requests.get_ht_id_path_from_ht_path(
            self.hyperthoughtui.authcontrol, ht_path=remoteDirPath)
        self.ui.hyperthoughtLocationLineEdit.setText(remoteDirPath)
        self.toggleButtons()

    def handleRemoveCreate(self, source, filterIndex, tableIndex):
        if "Custom Input" in source:
            for i in range(len(self.createtablemodel.metadataList)):
                if self.createtablemodel.metadataList[i]["Source"] == source:
                    self.createtablemodel.beginRemoveRows(QModelIndex(), i, i)
                    del self.createtablemodel.metadataList[i]
                    self.createtablemodel.endRemoveRows()
                    break
        else:
            self.treeModel.changeLeafCheck(source)

    def handleRemoveUse(self, source, listIndex, filterIndex):
        self.usetablemodel.beginRemoveRows(QModelIndex(), listIndex.row(),
                                           listIndex.row())
        del self.usetablemodel.metadataList[listIndex.row()]
        self.usetablemodel.endRemoveRows()

    def help(self):
        QDesktopServices.openUrl("http://www.bluequartz.net/")

    def movethedamnbutton(self):
        self.appendSourceFilesButton.move(
            self.ui.useTemplateListView.width() -
            self.appendSourceFilesButton.width() - 15,
            self.ui.useTemplateListView.height() -
            self.appendSourceFilesButton.height())

    def openPackage(self):
        linetext = QFileDialog.getOpenFileName(
            self, self.tr("Select File"),
            QStandardPaths.displayName(QStandardPaths.HomeLocation),
            self.tr("Files (*.ezpak)"))[0]
        if linetext != "":

            infile = open(linetext, "r")
            self.loadTemplateFile(infile.readline()[1:-2])
            extractedFile = infile.readline()[1:-2]
            fileList = infile.readline()
            fileList = json.loads(fileList)
            self.fileList = fileList[:]
            self.uselistmodel = ListModel(self, self.usetablemodel,
                                          self.fileList)
            self.ui.useTemplateListView.setModel(self.uselistmodel)
            self.extractFile(extractedFile)
            self.uselistmodel.removeAllRows()
            for i in range(len(fileList)):
                self.uselistmodel.addRow(fileList[i])
            self.toggleButtons()
            infile.close()
            self.ui.TabWidget.setCurrentIndex(1)

    def restoreTemplate(self):
        #Clear data on create side
        self.createtablemodel.metadataList = []
        self.createtablemodel.hiddenList = []
        self.filterModel.displayed = []
        #open template
        linetext = QFileDialog.getOpenFileName(
            self, self.tr("Select File"),
            QStandardPaths.displayName(QStandardPaths.HomeLocation),
            self.tr("Files (*.ez)"))[0]
        if linetext != "":
            infile = open(linetext, "r")
            infile.readline()
            fileType = infile.readline()
            self.fileType = json.loads(fileType)
            infile.readline()
            newList = infile.readline()
            newList = json.loads(newList)
            newDict = infile.readline()
            newDict = json.loads(newDict)
            self.ui.dataTypeText.setText(self.fileType[0][-3:].upper())
            self.ui.fileParserCombo.setCurrentIndex(
                self.ui.fileParserCombo.findText(
                    self.fileType[0][-3:].upper() + " Parser"))
            self.ui.dataFileLineEdit.setText(self.fileType[0])
            self.createtablemodel = TableModelC(newDict, self)
            self.filterModel.displayed = []
            self.filterModel.setSourceModel(self.createtablemodel)
            self.filterModel.fileType = self.fileType
            self.createTableSearchFilterModel = QSortFilterProxyModel(self)
            self.createTableSearchFilterModel.setSourceModel(self.filterModel)
            self.createTableSearchFilterModel.setFilterKeyColumn(1)
            self.createTableSearchFilterModel.setDynamicSortFilter(True)
            self.ui.metadataTableView.setModel(
                self.createTableSearchFilterModel)
            self.treeModel = TreeModelR(["Available File Metadata"], newDict,
                                        self.createtablemodel, newList,
                                        self.filterModel)

            for i in range(len(newList)):
                if "Custom Input" in newList[i]["Source"]:
                    self.numCustoms += 1
                    self.customInputs.append(newList[i])
                    self.createtablemodel.beginInsertRows(
                        self.createtablemodel.index(
                            len(self.createtablemodel.metadataList), 0), i, i)
                    self.createtablemodel.metadataList.append(newList[i])
                    self.createtablemodel.endInsertRows()

            self.createTreeSearchFilterModel = QSortFilterProxyModel(self)
            self.createTreeSearchFilterModel.setSourceModel(self.treeModel)
            self.createTreeSearchFilterModel.setFilterKeyColumn(0)
            self.createTreeSearchFilterModel.setDynamicSortFilter(True)
            self.createTreeSearchFilterModel.setRecursiveFilteringEnabled(True)
            self.ui.metadataTreeView.setModel(self.createTreeSearchFilterModel)
            self.treeModel.checkChanged.connect(self.filterModel.checkList)
            self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)
            self.ui.TabWidget.setCurrentIndex(0)

    def removeRowfromUsefileType(self, index):
        if self.ui.useTemplateListView.width(
        ) - 64 < self.ui.useTemplateListView.mapFromGlobal(QCursor.pos()).x():
            #this is where to remove the row
            self.uselistmodel.removeRow(index.row())

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.movethedamnbutton()

    def savePackageAs(self):
        fileName = QFileDialog.getSaveFileName(self, "Save File", "/Packages/",
                                               "Packages (*.ezpak)")[0]
        if fileName != "":
            myDir = QDir()
            myDir.mkpath(fileName)
            for file in self.uselistmodel.metadataList:
                QFile.copy(file, fileName + "/" + file.split("/")[-1])

            oldtemplate = open(self.templateFilePath, 'r')
            oldtemplatelist = oldtemplate.readline()
            filetype = oldtemplate.readline()
            oldtemplate.readline()
            oldlist = oldtemplate.readline()
            oldtree = oldtemplate.readline()
            oldtemplate.close()
            with open(fileName + "/" + self.currentTemplate, 'w') as outfile:
                outfile.write(oldtemplatelist)
                outfile.write(filetype)
                json.dump(self.editableKeys, outfile)
                outfile.write("\n")
                outfile.write(oldlist)
                outfile.write(oldtree)

            with open(fileName + "/" + self.currentTemplate + "pak",
                      'w') as outfile:
                json.dump(fileName + "/" + self.currentTemplate, outfile)
                outfile.write("\n")
                json.dump(self.ui.otherDataFileLineEdit.text(), outfile)
                outfile.write("\n")
                json.dump(self.uselistmodel.metadataList, outfile)

    def saveTemplate(self):
        dialog = QFileDialog(self, "Save File", "", "Templates (*.ez)")
        dialog.setDefaultSuffix(".ez")
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        fileName = ""
        if dialog.exec():
            fileName = dialog.selectedFiles()[0]
        if fileName != "":
            with open(fileName, 'w') as outfile:
                json.dump(self.filterModel.displayed, outfile)
                outfile.write("\n")
                json.dump(self.filterModel.fileType, outfile)
                outfile.write("\n")
                self.createtablemodel.editableList = []
                for i in range(len(self.createtablemodel.metadataList)):
                    if self.createtablemodel.metadataList[i][
                            "Editable"] == 2 and (
                                self.createtablemodel.metadataList[i]
                                ["Checked"] == 2 or self.createtablemodel.
                                metadataList[i]["Checked"] == 1):
                        self.createtablemodel.editableList.append(
                            self.createtablemodel.metadataList[i]["Key"])
                json.dump(self.createtablemodel.editableList, outfile)
                outfile.write("\n")
                json.dump(self.createtablemodel.metadataList, outfile)
                outfile.write("\n")
                json.dump(self.treeModel.treeDict, outfile)

    def selectFile(self, fileLink=None):
        if fileLink == False:
            linetext = QFileDialog.getOpenFileName(
                self, self.tr("Select File"),
                QStandardPaths.displayName(QStandardPaths.HomeLocation),
                self.tr("Files (*.*)"))[0]
        else:
            linetext = fileLink
        if linetext != "":
            self.setWindowTitle(linetext)
            self.ui.dataFileLineEdit.setText(linetext)
            self.ui.dataTypeText.setText(linetext.split(".")[1].upper())
            if self.ui.fileParserCombo.findText(
                    linetext.split(".")[1].upper() + " Parser") != -1:
                headerDict = {}
                self.ui.fileParserCombo.setCurrentIndex(
                    self.ui.fileParserCombo.findText(
                        linetext.split(".")[1].upper() + " Parser"))
            if linetext.split(".")[1].upper() == "CTF":
                headerDict = ctf.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "ANG":
                headerDict = ang.parse_header_as_dict(linetext)
            elif linetext.split(".")[1].upper() == "XML":
                print("XML Parser used")

            self.createtablemodel = TableModelC(headerDict, self)
            self.filterModel.displayed = []
            self.filterModel.setSourceModel(self.createtablemodel)
            self.filterModel.fileType.append(linetext)
            self.createTableSearchFilterModel = QSortFilterProxyModel(self)
            self.createTableSearchFilterModel.setSourceModel(self.filterModel)
            self.createTableSearchFilterModel.setFilterKeyColumn(1)
            self.createTableSearchFilterModel.setDynamicSortFilter(True)
            self.ui.metadataTableView.setModel(
                self.createTableSearchFilterModel)
            self.treeModel = TreeModel(["Available File Metadata"], headerDict,
                                       self.createtablemodel)

            if len(self.customInputs) != 0:
                for i in range(len(self.customInputs)):
                    self.createtablemodel.beginInsertRows(
                        self.createtablemodel.index(
                            len(self.createtablemodel.metadataList), 0), i, i)
                    self.createtablemodel.metadataList.append(
                        self.customInputs[i])
                    self.createtablemodel.endInsertRows()

            self.createTreeSearchFilterModel = QSortFilterProxyModel(self)
            self.createTreeSearchFilterModel.setSourceModel(self.treeModel)
            self.createTreeSearchFilterModel.setFilterKeyColumn(0)
            self.createTreeSearchFilterModel.setDynamicSortFilter(True)
            self.createTreeSearchFilterModel.setRecursiveFilteringEnabled(True)
            self.ui.metadataTreeView.setModel(self.createTreeSearchFilterModel)
            self.treeModel.checkChanged.connect(self.filterModel.checkList)
            self.createtrashDelegate.pressed.connect(self.handleRemoveCreate)

        self.toggleButtons()
        return True

    def selectTemplate(self):
        startLocation = self.ui.hyperthoughtTemplateLineEdit.text()
        if startLocation == "":
            startLocation = QStandardPaths.writableLocation(
                QStandardPaths.HomeLocation)

        templateFilePath = QFileDialog.getOpenFileName(
            self, self.tr("Select File"), startLocation,
            self.tr("Files (*.ez)"))[0]
        self.loadTemplateFile(templateFilePath)

    def loadTemplateFile(self, templateFilePath=None):
        if templateFilePath == "":
            return False
        self.templateFilePath = templateFilePath
        self.usetablemodel.metadataList = []
        self.usefilterModel.displayed = []
        self.currentTemplate = templateFilePath.split("/")[-1]
        self.ui.displayedFileLabel.setText(templateFilePath.split("/")[-1])
        self.ui.hyperthoughtTemplateLineEdit.setText(templateFilePath)
        self.ui.otherDataFileLineEdit.setText("")
        infile = open(templateFilePath, "r")
        data = infile.readline()
        fileType = infile.readline()
        fileType = json.loads(fileType)
        self.fileType = fileType[0][-4:]
        editables = infile.readline()
        self.editableKeys = json.loads(editables)
        self.usetablemodel.editableKeys = self.editableKeys
        self.toggleButtons()
        self.templatedata = json.loads(data)
        self.usetablemodel.addTemplateList(self.templatedata)
        self.usefilterModel.setFilterRegExp(QRegExp())
        infile.close()

        return True

    def showEvent(self, event):
        super().showEvent(event)
        self.movethedamnbutton()

    def toggleButtons(self):
        if (self.ui.hyperthoughtTemplateLineEdit.text() != ""
                and self.ui.otherDataFileLineEdit.text() != ""
                and self.ui.useTemplateListView.model().rowCount() > 0
                and self.ui.hyperthoughtLocationLineEdit.text() != ""):

            self.ui.hyperthoughtUploadButton.setEnabled(True)

    def uploadToHyperthought(self):
        auth_control = htauthcontroller.HTAuthorizationController(
            self.accessKey)
        metadataJson = ht_utilities.dict_to_ht_metadata(
            self.usefilterModel.displayed)
        progress = QProgressDialog("Uploading files...", "Abort Upload", 0,
                                   len(self.uselistmodel.metadataList), self)

        progress.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint
                                | Qt.WindowTitleHint)
        progress.setAttribute(Qt.WA_DeleteOnClose)
        self.createUpload.emit(self.uselistmodel.metadataList, auth_control,
                               self.folderuuid, metadataJson)
        self.uploader.currentUploadDone.connect(progress.setValue)
        self.uploader.currentlyUploading.connect(progress.setLabelText)
        self.uploader.allUploadsDone.connect(progress.accept)
        progress.canceled.connect(lambda: self.uploader.interruptUpload())
        progress.setFixedSize(500, 100)
        progress.exec()
コード例 #12
0
ファイル: treecontroller.py プロジェクト: REC17/cadnano2
class TreeController(QObject):

    def __init__(self, treeview):
        super(TreeController, self).__init__()
        self.treeview = treeview
        self.treeview.setSelectionBehavior(QTreeView.SelectItems)
        self.treeview.setUniformRowHeights(True)
        headers = ["item", "visible", "lock"]
        self.treemodel = TreeModel(self.treeview)
        self.treemodel.headers = headers
        self.treeview.setDragDropMode(QAbstractItemView.InternalMove)
        #self.win.treeview.setItemDelegateForColumn(0, QString())
        self.treeview.setAllColumnsShowFocus(True)
        self.treeview.setModel(self.treemodel)

        # insert the base level assembly
        index = self.treeview.currentIndex()
        nodeparent = self.treemodel.nodeFromIndex(index)
        node = AssemblyNode("Assembly", Assembly(), None, None)

        if self.treemodel.insertRow(0, index, node):
            # set index to the inserted child
            index = self.treemodel.index(0, 0, index)
            self.setCurrentIndex(index)
        # end if
        self.createConnections()
    # end def

    def createConnections(self):
        # QItemSelectionModel.currentChange emits the previous and current
        # selected QModelIndex, but we don't use those values
        #self.treeview.selectionModel().currentChanged.connect(self.updateUi)
        #self.treeview.activated.connect()
        # 
        #self.treemodel.dataChanged.connect(self.setDirty_ind)
        #self.treemodel.rowsRemoved.connect(self.setDirty)
        #self.treemodel.modelReset.connect(self.setDirty)

        # clicked is a QAbstractItemView signal
        self.treeview.clicked.connect(self.activated)
    # end def

    def setCurrentIndex(self,index):
        if index.isValid():
            self.treeview.scrollTo(index)
            self.treeview.setCurrentIndex(index)
        # end if
    # end def

    def addPartNode(self,name,partInst):
        """
        Adds a part to the tree model
        Makes sure it adds to the closest parent assembly if a part is the 
        current selected item
        """
        index = self.treeview.currentIndex()    # this is a QModelIndex
        nodeparent = self.treemodel.nodeFromIndex(index)

        # must make it an assembly that we insert at
        if nodeparent.ntype != AssemblyNode.ntype:                                     
            index = index.parent()              # returns the parent model index
            nodeparent = nodeparent.parent      # go to the parent
        # end if

        #node = PartNode(name, partInst,None, nodeparent)
        node = PartNode(name, partInst,None, None)

        # currently we insert the new node first in the list but 
        # treemodel handles keeping things alphabetical
        if self.treemodel.insertRow(0, index,node):
            # set index to the inserted child
            index = self.treemodel.index(self.treemodel.lastrow, 0, index)
            self.setCurrentIndex(index)
            #self.treeview.edit(index)
            #self.treemodel.reset()
        # end if
    # end def

    def cut(self):
        """
        returns if the treemodel was able to cut something
        """
        index = self.treeview.currentIndex()
        self.setCurrentIndex(self.treemodel.cut(index))
        return self.treemodel.hasCutItem()
    # end def

    def paste(self):
        index = self.treeview.currentIndex()
        self.setCurrentIndex(self.treemodel.paste(index))
    # end def

    def moveUp(self):
        index = self.treeview.currentIndex()
        self.setCurrentIndex(self.treemodel.moveUp(index))
    # end def

    def moveDown(self):
        index = self.treeview.currentIndex()
        self.setCurrentIndex(self.treemodel.moveDown(index))
    # end def

    def promote(self):
        index = self.treeview.currentIndex()
        self.setCurrentIndex(self.treemodel.promote(index))
    #end def

    def demote(self):
        index = self.win.treeview.currentIndex()
        self.setCurrentIndex(self.treemodel.demote(index))
    #end def

    def hideOrShowNode(self,hide, index):
        """"""
        hideThisOne = hide #and self.treemodel.isChecked(index)
        if index.isValid():
            self.treeview.setRowHidden(index.row(), index.parent(), hideThisOne)
        # end if
        if not hideThisOne:
            for row in range(self.treemodel.rowCount(index)):
                self.hideOrShowNode(hide, self.treemodel.index(row, 0, index))
            # end for
        # end if
    # end def

    def activated(self, index):
        """"""
        node = self.treemodel.nodeFromIndex(index)
        if node.ntype==PartNode.ntype:
            node.object_instance.partselected.emit()
コード例 #13
0
import sys
from treeitem import TreeItem
from treemodel import TreeModel
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QTreeView
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)
with open('view/default.txt', 'r', encoding='utf8') as f:
    model = TreeModel(f.read())
view = QTreeView()
view.setModel(model)
view.setWindowTitle("Simple Tree Model")
view.show()
sys.exit(app.exec())