Ejemplo n.º 1
0
def test_completion_item_next_prev(tree, count, expected, completionview):
    """Test that on_next_prev_item moves the selection properly.

    Args:
        tree: Each list represents a completion category, with each string
              being an item under that category.
        count: Number of times to go forward (or back if negative).
        expected: item data that should be selected after going back/forward.
    """
    model = base.BaseCompletionModel()
    for catdata in tree:
        cat = QStandardItem()
        model.appendRow(cat)
        for name in catdata:
            cat.appendRow(QStandardItem(name))
    filtermodel = sortfilter.CompletionFilterModel(model,
                                                   parent=completionview)
    completionview.set_model(filtermodel)
    if count < 0:
        for _ in range(-count):
            completionview.completion_item_prev()
    else:
        for _ in range(count):
            completionview.completion_item_next()
    idx = completionview.selectionModel().currentIndex()
    assert filtermodel.data(idx) == expected
Ejemplo n.º 2
0
    def populate(self, info, clear=False):
        if clear:
            if self.rootNode.rowCount() > 0:
                self.rootNode.removeRows(0, self.rootNode.rowCount())
        if info == []:
            branch = QStandardItem("No packages found.")
        else:
            for package in info:
                branch = QStandardItem(package["id"])
                for key, value in package.items():
                    if key == "id":  # Already got it
                        continue
                    if isinstance(value, list):
                        p = QStandardItem(key)
                        branch.appendRow([p])
                        for item in value:
                            p.appendRow(item)
                    elif isinstance(value, dict):
                        p = QStandardItem(key)
                        branch.appendRow([p])
                        for key_, value_ in value.items():
                            p.appendRow(
                                [QStandardItem(key_),
                                 QStandardItem(value_)])
                    else:
                        p = QStandardItem(key)
                        q = QStandardItem(str(value))
                        branch.appendRow([p, q])

        self.rootNode.appendRow([branch])
Ejemplo n.º 3
0
    def __init__(self, dictionary):
        """Shows a dictionary as a tree view in a separate window.

        :param dictionary: the JSON-like dictionary that should be shown
        :type dictionary: dict
        """
        super().__init__()
        self.d = dictionary

        # Use a default tree structure with two columns
        model = QStandardItemModel()
        self.setModel(model)
        model.setColumnCount(2)
        model.setHorizontalHeaderLabels(["key", "value"])

        # For each main node
        for k, v in self.d.items():
            parent = QStandardItem(k)

            # If sub-nodes are available
            if type(v) is dict:
                for k1, v1 in v.items():
                    parent1 = QStandardItem(k1)
                    c1 = QStandardItem(str(v1))

                    parent.appendRow([parent1, c1])

            else:
                cs = [QStandardItem(v)]
                parent.appendRow(cs)

            model.appendRow(parent)
    def add_content(self, changes, root_text, is_server, changes_summary={}):
        """
        Adds rows with changes info
        :param changes: Dict of added/removed/updated/renamed changes
        :param root_text: Text for the root item
        :param is_server: True if changes are related to server file changes
        :param changes_summary: If given and non empty, extra rows are added from geodiff summary.
        :return:
        """
        if all(not changes[k] for k in changes):
            return

        root_item = QStandardItem(root_text)
        self.model.appendRow(root_item)
        for category in changes:
            for file in changes[category]:
                path = file["path"]
                item = self._get_icon_item(category, path)
                if is_versioned_file(path):
                    if path in changes_summary:
                        for sub_item in self._versioned_file_summary_items(changes_summary[path]["geodiff_summary"]):
                            item.appendRow(sub_item)
                    elif not is_server and category != "added":
                        item.appendRow(QStandardItem("Unable to detect changes"))
                        msg = f"Mergin plugin: Unable to detect changes for {path}"
                        QgsApplication.messageLog().logMessage(msg)
                        if self.mp is not None:
                            self.mp.log.warning(msg)
                root_item.appendRow(item)
Ejemplo n.º 5
0
    def _show_attrs(self):
        attrs = self.get_all_attrs()
        self.model.setHorizontalHeaderLabels(['Attribute', 'Value', 'DataType'])
        for attr, dv in attrs:
            if attr == ua.AttributeIds.DataType:
                string = data_type_to_string(dv)
            elif attr in (ua.AttributeIds.AccessLevel,
                          ua.AttributeIds.UserAccessLevel,
                          ua.AttributeIds.WriteMask,
                          ua.AttributeIds.UserWriteMask,
                          ua.AttributeIds.EventNotifier):
                attr_name = attr.name
                if attr_name.startswith("User"):
                    attr_name = attr_name[4:]
                attr_enum = getattr(ua, attr_name)
                string = ", ".join([e.name for e in attr_enum.parse_bitfield(dv.Value.Value)])
            else:
                string = variant_to_string(dv.Value)
            name_item = QStandardItem(attr.name)
            vitem = QStandardItem(string)
            vitem.setData((attr, dv), Qt.UserRole)
            self.model.appendRow([name_item, vitem, QStandardItem(dv.Value.VariantType.name)])

            # special case for Value, we want to show timestamps
            if attr == ua.AttributeIds.Value:
                string = val_to_string(dv.ServerTimestamp)
                name_item.appendRow([QStandardItem("Server Timestamp"), QStandardItem(string), QStandardItem(ua.VariantType.DateTime.name)])
                string = val_to_string(dv.SourceTimestamp)
                name_item.appendRow([QStandardItem("Source Timestamp"), QStandardItem(string), QStandardItem(ua.VariantType.DateTime.name)])
    def makeItems(self):
        # 아이템을 한개씩 만들어서 추가하는 식으로 보임.
        item = None
        rev = 0
        cur_poem_idx = 0
        cur_poem_title = ""
        self.inserted_cnt = 0
        childCnt = 0

        for row in self.data:
            print("{}, poem_idx{} , idx:{}".format(row, row['idx_mthx_poem'],
                                                   cur_poem_idx))
            # changing of index (new poem)
            if (row['idx_mthx_poem'] != cur_poem_idx):
                cur_poem_idx = row['idx_mthx_poem']
                cur_poem_title = row['curTitle']
                string_name = "{}_{}".format(cur_poem_idx, cur_poem_title)
                item = QStandardItem(string_name)
                childCnt = 0
                self.setItem(self.inserted_cnt, 0, item)
                self.inserted_cnt = self.inserted_cnt + 1
                print("setItem CntItem:{} {}".format(self.inserted_cnt,
                                                     cur_poem_title))
                # string_name = "{}_{} ({})".format(cur_poem_idx, curtitle, childCnt)
                # item.setText(string_name)

            # add child-item
            rev = row['revision']
            string_child_name = "{}_{}_rev{}".format(row['idx_mthx_poem'],
                                                     row['curTitle'], rev)
            child_1 = QStandardItem(string_child_name)
            child_2 = QStandardItem("{}".format(cur_poem_idx))
            child_3 = QStandardItem("{}".format(rev))
            item.appendRow([child_1, child_2, child_3])
            childCnt = childCnt + 1
Ejemplo n.º 7
0
def test_completion_show(show, rows, quick_complete, completionview,
                         config_stub):
    """Test that the completion widget is shown at appropriate times.

    Args:
        show: The completion show config setting.
        rows: Each entry represents a completion category with only one item.
        quick_complete: The completion quick-complete config setting.
    """
    config_stub.data['completion']['show'] = show
    config_stub.data['completion']['quick-complete'] = quick_complete

    model = base.BaseCompletionModel()
    for name in rows:
        cat = QStandardItem()
        model.appendRow(cat)
        cat.appendRow(QStandardItem(name))
    filtermodel = sortfilter.CompletionFilterModel(model,
                                                   parent=completionview)

    assert not completionview.isVisible()
    completionview.set_model(filtermodel)
    assert completionview.isVisible() == (show == 'always' and len(rows) > 0)
    completionview.completion_item_focus('next')
    expected = (show != 'never' and len(rows) > 0
                and not (quick_complete and len(rows) == 1))
    assert completionview.isVisible() == expected
    completionview.set_model(None)
    completionview.completion_item_focus('next')
    assert not completionview.isVisible()
Ejemplo n.º 8
0
    def addItem(self, item, header, mainheader=None, editable=True):
        """ Adds item to tree """
        if mainheader is None:
            finds = self.model.findItems(header)
            if not finds:
                itemheader = QStandardItem(header)
                self.model.appendRow(itemheader)
            else:
                itemheader = finds[0]
        else:
            finds = self.model.findItems(mainheader)
            if not finds:
                raise Exception('main header %s does not exist' % mainheader)
            main_itemheader = finds[0]

            for i in range(main_itemheader.rowCount()):
                itemheader = main_itemheader.child(i, 0)
                if itemheader:
                    if header is itemheader.data():
                        break

        standardItem = QStandardItem(item.name)
        standardItem.setEditable(editable)
        standardItem.setData(item)
        itemheader.appendRow(standardItem)
Ejemplo n.º 9
0
    def createEditor(self, widget, option, index):
        standards = index.model().data(index, StandardsRole)
        analogs = index.model().data(index, AnalogsRole)
        if standards or analogs:
            model = QStandardItemModel()
            editor = StandardsResultsEditor(widget)
            editor.setModel(model)
            for type_, items in enumerate((standards, analogs)):
                parent = QStandardItem()
                if type_ == ANALOGS:
                    parent.setText('Analogs')
                    parent.setIcon(
                        QIcon(":/icons/images/library-query-analogs.svg"))
                else:
                    parent.setText('Standards')
                    parent.setIcon(QIcon(":/icons/images/library-query.svg"))
                parent.setData(type_)
                parent.setSelectable(False)
                model.appendRow(parent)
                if items and not isinstance(items, str):
                    for i, result in enumerate(items):
                        if not isinstance(result, str):
                            item = QStandardItem()
                            if type_ == ANALOGS:
                                item.setSelectable(False)
                            item.setText(result.text)
                            item.setData(result.id)
                            parent.appendRow(item)

            # Connect events
            editor.button.clicked.connect(
                lambda: self.on_view_details(index, editor))

            return editor
Ejemplo n.º 10
0
 def _add_path(self, path: List[str], depth: int, parent_item: QStandardItem, path_str: str, path_len: int):
     is_file = False
     if depth == path_len:
         return
     if depth == path_len - 1:
         # 为文件
         is_file = True
     node_name_list = path[depth]
     for node_name in node_name_list:
         # 检查节点名在是否重复
         index = 0
         child_item = parent_item.child(index)
         while child_item:
             child_name = child_item.index().data()
             if child_name == node_name:
                 node_item = child_item
                 break
             index += 1
             child_item = parent_item.child(index)
         else:
             note_str = "文件" if is_file else "文件夹"
             icon = QIcon(self._root_abs_path + "\\resources\\folder.png") if not is_file else IconExtractor(
                 self._file_mgr.get_abs_path(node_name)).get_icon()
             node_item = QStandardItem(icon, node_name)
             path_str += "\\" + node_name
             path_item = QStandardItem(path_str)
             note_item = QStandardItem(note_str)
             parent_item.appendRow([node_item, path_item, note_item])
         self._add_path(path, depth + 1, node_item, path_str, path_len)
Ejemplo n.º 11
0
    def _from_xml(self, keywords):

        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(['Thesaurus', 'Keyword'])

        rootNode = model.invisibleRootItem()

        if keywords.xpath('place'):
            self.ui.rbtn_yes.setChecked(True)
        else:
            self.ui.rbtn_yes.setChecked(False)

        for place in keywords.xpath('place'):
            thesaurus_name = place.xpath('placekt')[0].text
            branch = QStandardItem(thesaurus_name)
            branch.setFont(QFont('Arial', 9))

            for kw in place.xpath('placekey'):
                childnode = QStandardItem(kw.text)
                childnode.setFont(QFont('Arial', 10))
                branch.appendRow([None, childnode])

            rootNode.appendRow([branch, None])

        self.ui.place.setModel(model)
        # self.ui.place.setColumnWidth(250, 150)
        self.ui.place.expandAll()
Ejemplo n.º 12
0
    def __update_tree_modules(self, current):
        modules = current['modules'] if 'modules' in current else {}
        model = QStandardItemModel()
        parent_item = model.invisibleRootItem()  # type: QStandardItem

        for m in sorted(modules):
            text_item = QStandardItem(m)
            text_item.setEditable(False)
            text_item.setCheckState(
                Qt.Checked if json.loads(modules[m].lower()) else Qt.Unchecked)

            # NOTE: some modules name their parameters differently than themselves
            if json.loads(modules[m].lower()) and m in current:
                for i in sorted(current[m]):
                    item = QStandardItem(i + " = " + current[m][i])
                    item.setEditable(False)
                    font = QFont()
                    font.setItalic(True)
                    item.setFont(font)
                    text_item.appendRow(item)

            parent_item.appendRow(text_item)

        model.setHeaderData(0, Qt.Horizontal, "Modules")
        self.ui.modules.setModel(model)
Ejemplo n.º 13
0
    def traverse_json_tree(self, root_node: dict) -> QStandardItem:
        """Traverses a JSON dictionary tree representation through recursion.

        Parameters
        ----------
        root_node : dict
            Dictionary which is the root of the tree. See notes for node
            representation.

        Returns
        -------
        QStandardItem
            Root of the tree as a QStandardItem.

        Notes
        -----
        The `root_node` and subsequent nodes has to be in the following format:
            node = {'node': str_name_of_node,
                    'children': list_of_nodes,
                    'description': str_tooltip_description_of_node}

        Where list_of_nodes is, literally, a list of nodes. Duh.

        """
        rn = QStandardItem(root_node['node'])
        rn.setEditable(False)
        if 'description' in root_node:
            rn.setToolTip(root_node['description'])

        if 'children' in root_node:
            for child in root_node['children']:
                rn.appendRow(self.traverse_json_tree(child))

        return rn
Ejemplo n.º 14
0
    def load_iso(self):
        self.ui.label_search_term.hide()
        self.ui.search_term.hide()
        self.ui.button_search.hide()
        self.ui.label_search_results.text = "ISO 19115 Topic Categories"

        self.populate_thesauri_lookup()

        iso_url = "https://www2.usgs.gov/science/term.php?thcode=15&text=ISO 19115 Topic Category"
        results = utils.requests_pem_get(iso_url).json()

        thesaurus_name = "ISO 19115 Topic Category"
        branch = QStandardItem(thesaurus_name)
        branch.setFont(QFont('Arial', 11))
        for item in results['nt']:
            childnode = QStandardItem(item['name'])
            childnode.setFont(QFont('Arial', 9))
            branch.appendRow([childnode])

        model = QStandardItemModel(0, 0)

        rootNode = model.invisibleRootItem()
        rootNode.appendRow(branch)

        self.ui.treeview_results.setModel(model)
        self.ui.treeview_results.expandAll()
Ejemplo n.º 15
0
    def test_tooltree(self):
        tree = ToolTree()
        role = tree.actionRole()
        model = QStandardItemModel()
        tree.setModel(model)
        item = QStandardItem("One")
        item.setData(QAction("One", tree), role)
        model.appendRow([item])

        cat = QStandardItem("A Category")
        item = QStandardItem("Two")
        item.setData(QAction("Two", tree), role)
        cat.appendRow([item])
        item = QStandardItem("Three")
        item.setData(QAction("Three", tree), role)
        cat.appendRow([item])

        model.appendRow([cat])

        def p(action):
            print("triggered", action.text())

        tree.triggered.connect(p)

        tree.show()

        self.app.exec_()
Ejemplo n.º 16
0
 def _show_attrs(self, node):
     try:
         attrs = self.uaclient.get_all_attrs(node)
     except Exception as ex:
         self.window.show_error(ex)
         raise
     self.model.setHorizontalHeaderLabels(['Attribute', 'Value', 'DataType'])
     for name, dv in attrs:
         if name == "DataType":
             if isinstance(dv.Value.Value.Identifier, int) and dv.Value.Value.Identifier < 63:
                 string = ua.DataType_to_VariantType(dv.Value.Value).name
             elif dv.Value.Value.Identifier in ua.ObjectIdNames:
                 string = ua.ObjectIdNames[dv.Value.Value.Identifier]
             else:
                 string = dv.Value.Value.to_string()
         elif name in ("AccessLevel", "UserAccessLevel"):
             string = ",".join([e.name for e in ua.int_to_AccessLevel(dv.Value.Value)])
         elif name in ("WriteMask", "UserWriteMask"):
             string = ",".join([e.name for e in ua.int_to_WriteMask(dv.Value.Value)])
         elif name in ("EventNotifier"):
             string = ",".join([e.name for e in ua.int_to_EventNotifier(dv.Value.Value)])
         else:
             string = variant_to_string(dv.Value)
         name_item = QStandardItem(name)
         vitem = QStandardItem(string)
         vitem.setData(dv.Value)
         self.model.appendRow([name_item, vitem, QStandardItem(dv.Value.VariantType.name)])
         if name == "Value":
             string = val_to_string(dv.ServerTimestamp)
             name_item.appendRow([QStandardItem("Server Timestamp"), QStandardItem(string), QStandardItem(ua.VariantType.DateTime.name)])
             string = val_to_string(dv.SourceTimestamp)
             name_item.appendRow([QStandardItem("Source Timestamp"), QStandardItem(string), QStandardItem(ua.VariantType.DateTime.name)])
Ejemplo n.º 17
0
    def model_populate(self, children, parent):
        """
        Function to work with the Model.
        You need to give 2 parameter, a dict with your Data you want show,
        and a parent to define the index.
        It's a recursive function, if your Data has a Dict inside a Dict,
        the function generate the Tree with all sub-node.
        :param children: It's only a Dict, included your Data
        :param parent: Define your first level, work with the Invisible Root
        :return: nothing returns.
        """
        for key, values in sorted(children.items()):
            item_object = QStandardItem(key)
            folder_icon = QtGui.QIcon()
            folder_icon.addPixmap(
                QtGui.QPixmap("Resources/Icons/file-submodule.png"))
            item_object.setIcon(folder_icon)
            parent.appendRow(item_object)

            if type(values) == list:
                for value in values:
                    if type(value) == str:
                        level_name = basename(value)
                        check = False
                        if self.settings.last_job_run():
                            if len(self.data.select_levels(name=level_name)):
                                check = 2
                        item_name = QStandardItem(level_name)
                        item_name.setCheckable(True)
                        item_name.setCheckState(check)
                        item_path = QStandardItem(value)
                        item_object.appendRow([item_name, item_path])
                    elif type(value) == dict:
                        self.model_populate(value, item_object)
Ejemplo n.º 18
0
 def importData(self, data):
     self.model.setRowCount(0)
     root = self.model.invisibleRootItem()
     for index, stack_values in enumerate(data):
         parent = QStandardItem(
             str(stack_values.f_code.co_name)
             + str(
                 inspect.signature(
                     types.FunctionType(stack_values.f_code, {})
                 )
             )
         )
         parent.setEditable(False)
         for key, value in stack_values.f_locals.items():
             keyWidget = QStandardItem(str(key))
             keyWidget.setEditable(False)
             try:
                 value_as_str = repr(value)
             except BaseException:
                 value_as_str = "Can't see"
             valueWidget = ValueWidget(
                 self.parent, value_as_str, str(key), str(index)
             )
             parent.appendRow([keyWidget, valueWidget])
         root.appendRow(parent)
Ejemplo n.º 19
0
def test_completion_show(show, rows, quick_complete, completionview,
                         config_stub):
    """Test that the completion widget is shown at appropriate times.

    Args:
        show: The completion show config setting.
        rows: Each entry represents a completion category with only one item.
        quick_complete: The completion quick-complete config setting.
    """
    config_stub.data['completion']['show'] = show
    config_stub.data['completion']['quick-complete'] = quick_complete

    model = base.BaseCompletionModel()
    for name in rows:
        cat = QStandardItem()
        model.appendRow(cat)
        cat.appendRow(QStandardItem(name))
    filtermodel = sortfilter.CompletionFilterModel(model,
                                                   parent=completionview)

    assert not completionview.isVisible()
    completionview.set_model(filtermodel)
    assert completionview.isVisible() == (show == 'always' and len(rows) > 0)
    completionview.completion_item_focus('next')
    expected = (show != 'never' and len(rows) > 0 and
                not (quick_complete and len(rows) == 1))
    assert completionview.isVisible() == expected
    completionview.set_model(None)
    completionview.completion_item_focus('next')
    assert not completionview.isVisible()
    def add_content(self, changes, root_text, is_server, changes_summary={}):
        """
        Adds rows with changes info
        :param changes: Dict of added/removed/updated/renamed changes
        :param root_text: Text for the root item
        :param is_server: True if changes are related to server file changes
        :param changes_summary: If given and non empty, extra rows are added from geodiff summary.
        :return:
        """
        if all(not changes[k] for k in changes):
            return

        root_item = QStandardItem(root_text)
        self.model.appendRow(root_item)
        for category in changes:
            for file in changes[category]:
                path = file['path']
                item = self._get_icon_item(category, path)
                if is_versioned_file(path):
                    if path in changes_summary:
                        for sub_item in self._versioned_file_summary_items(
                                changes_summary[path]['geodiff_summary']):
                            item.appendRow(sub_item)
                    elif not is_server:
                        item.appendRow(
                            QStandardItem("Unable to detect changes"))
                root_item.appendRow(item)
Ejemplo n.º 21
0
    def add_file_to_tree(self, filename):
        file = h5py.File(filename, 'a')
        self.file_dict.update({file.filename: file})
        item_dict = {}

        def add_to_item_list(name):
            name_list = name.split('/')
            short_name = name_list[-1]
            parent_name = '/'.join(
                name_list[:-1]) if len(name_list) > 1 else '__root__'
            item = QStandardItem(short_name)
            data = FileItemKeys(short_name, name, parent_name, file.filename)
            item.setData(data)
            item_dict.update({name: item})

        file.visit(add_to_item_list)
        file_short_name = file.filename.split('\\')[-1].split('/')[-1]
        file_item = QStandardItem(file_short_name)
        data = FileItemKeys(file_short_name, '__root__', '', file.filename)
        file_item.setData(data)
        self.model_.setItem(self.number_of_files, 0, file_item)
        self.number_of_files += 1
        for item in item_dict.values():
            data = item.data()
            if data.parent_name == '__root__':
                file_item.appendRow(item)
            else:
                item_dict[data.parent_name].appendRow(item)
        self.model().layoutChanged.emit()
Ejemplo n.º 22
0
def getItems(obj, level=0):
    exclude_keys = ('net', '_r', 'variables')
    retVal = []
    if level > 1 and isinstance(obj, BaseNode):
        return retVal
    if isinstance(obj, dict):
        for key, value in sorted(obj.items()):
            if key not in exclude_keys\
              and not (
                isinstance(key, str)\
                and key.startswith('_')
              ):
                keyItem = QStandardItem(str(key))
                children = []
                if hasattr(value, '__iter__'):
                    valueItem = typeValueItem(value)
                    for child in getItems(value, level + 1):
                        keyItem.appendRow(child)
                else:
                    valueItem = scalarValueItem(value)
                retVal.append([keyItem, valueItem])
    elif hasattr(obj, '__dict__'):
        retVal = getItems(obj.__dict__, level + 1)
    elif isinstance(obj, (set, list, tuple)):
        for item in sorted(obj):
            keyItem = QStandardItem(str(item))
            children = getItems(item, level + 1)
            valueItem = typeValueItem(item)
            for child in children:
                keyItem.appendRow(child)
            retVal.append([keyItem, valueItem])
    return retVal
Ejemplo n.º 23
0
def test_completion_item_focus(which, tree, expected, completionview, qtbot):
    """Test that on_next_prev_item moves the selection properly.

    Args:
        which: the direction in which to move the selection.
        tree: Each list represents a completion category, with each string
              being an item under that category.
        expected: expected argument from on_selection_changed for each
                  successive movement. None implies no signal should be
                  emitted.
    """
    model = base.BaseCompletionModel()
    for catdata in tree:
        cat = QStandardItem()
        model.appendRow(cat)
        for name in catdata:
            cat.appendRow(QStandardItem(name))
    filtermodel = sortfilter.CompletionFilterModel(model,
                                                   parent=completionview)
    completionview.set_model(filtermodel)
    for entry in expected:
        if entry is None:
            with qtbot.assertNotEmitted(completionview.selection_changed):
                completionview.completion_item_focus(which)
        else:
            with qtbot.waitSignal(completionview.selection_changed) as sig:
                completionview.completion_item_focus(which)
                assert sig.args == [entry]
Ejemplo n.º 24
0
def RefreshFileHookView():
    if mainWindowHelper.clvHooks.model() is QStandardItemModel:
        mainWindowHelper.clvHooks.model().destroyed()

    model_hooks = QStandardItemModel()

    for file in file_list:
        file_item = QStandardItem(file)

        for hook_name in file_hooks[file]:
            source_hook = file_hooks[file].get(hook_name)
            if source_hook != None:
                if IsShowSame() == False:
                    inj_hook = inj_hooks.get(hook_name)
                    if inj_hook == source_hook:
                        continue
                if IsShowAnnotated() == False and source_hook.annotated:
                    continue

            hook_item = QStandardItem(hook_name)
            file_item.appendRow(hook_item)
        
        if file_item.rowCount() > 0:
            model_hooks.appendRow(file_item)

    mainWindowHelper.clvHooks.setModel(model_hooks)
Ejemplo n.º 25
0
def test_completion_item_focus(which, tree, count, expected, completionview,
                               qtbot):
    """Test that on_next_prev_item moves the selection properly.

    Args:
        tree: Each list represents a completion category, with each string
              being an item under that category.
        count: Number of times to go forward (or back if negative).
        expected: item data that should be selected after going back/forward.
    """
    model = base.BaseCompletionModel()
    for catdata in tree:
        cat = QStandardItem()
        model.appendRow(cat)
        for name in catdata:
            cat.appendRow(QStandardItem(name))
    filtermodel = sortfilter.CompletionFilterModel(model,
                                                   parent=completionview)
    completionview.set_model(filtermodel)
    if expected is None:
        for _ in range(count):
            completionview.completion_item_focus(which)
    else:
        with qtbot.waitSignal(completionview.selection_changed):
            for _ in range(count):
                completionview.completion_item_focus(which)
    idx = completionview.selectionModel().currentIndex()
    assert filtermodel.data(idx) == expected
Ejemplo n.º 26
0
 def make_tree(self):
     self.model = QStandardItemModel()
     self.tree_files.setModel(self.model)
     info = req.get(url, data={'tree': self.parent.chat_id}).json()
     # self.timer = QtCore.QTimer()
     # self.timer.timeout.connect(self.make_tree)
     # self.timer.start(10000)
     if info.get('parent1'):
         for direc in info.get('parent1'):
             parent1 = QStandardItem(direc)
             # if direc == info.get('parent1')[-1]:
             if not '.' in direc:
                 # if os.path.isdir(os.path.join(directory, direc)):
                 for fil in info.get('parent2'):
                     parent2 = QStandardItem(fil)
                     parent1.appendRow(parent2)
                     if not '.' in fil:
                         # if fil == info.get('parent2')[-1]:
                         # if os.path.isdir(os.path.join(os.path.join(directory, direc), fil)):
                         for fil_1 in info.get('parent3'):
                             parent3 = QStandardItem(fil_1)
                             parent2.appendRow(parent3)
                             # if os.path.isdir(os.path.join(os.path.join(os.path.join(directory, direc), fil), fil_1)):
                             # for fil_2 in os.listdir(os.path.join(os.path.join(os.path.join(directory, direc), fil), fil_1)):
                             # parent4 = QStandardItem(fil_2)
                             # parent3.appendRow(parent4)
             self.model.appendRow(parent1)
Ejemplo n.º 27
0
 def createAttr(self, elem, key, value, parent: QStandardItem):
     item = QStandardItem('@' + key)
     item.setEditable(True and self.treeView.editable)
     item.setData(self.getItemData(elem, "property", key))
     val = QStandardItem(value)
     val.setEditable(True and self.treeView.editable)
     val.setData(self.getItemData(elem, "property-value", item))
     parent.appendRow([item, val])
Ejemplo n.º 28
0
 def addItems(self, parent, elements):
     for k in sorted(elements.keys()):
         item = QStandardItem(k)
         parent.appendRow(item)
         if type(elements[k]) == dict:
             self.addItems(item, elements[k])
         else:
             child = QStandardItem(str(elements[k]))
             item.appendRow(child)
Ejemplo n.º 29
0
 def update_combobox(self):
     for k, v in self.dic.items():
         service = QStandardItem(k)
         self.model.appendRow(service)
         for value in v:
             doctor = QStandardItem(value)
             service.appendRow(doctor)
     self.service.currentIndexChanged.connect(self.update_service)
     self.update_service(0)
Ejemplo n.º 30
0
    def generate_model(self) -> Tuple[QStandardItemModel, QModelIndex]:
        """Generate a Qt Model based on the project structure."""
        model = QStandardItemModel()
        root = model.invisibleRootItem()

        # TODO: Add these icon resources to library or something so they are not loaded every time
        dgs_ico = QIcon('ui/assets/DGSIcon.xpm')
        flt_ico = QIcon('ui/assets/flight_icon.png')

        prj_header = QStandardItem(
            dgs_ico, "{name}: {path}".format(name=self.name,
                                             path=self.projectdir))
        prj_header.setEditable(False)
        fli_header = QStandardItem(flt_ico, "Flights")
        fli_header.setEditable(False)
        # TODO: Add a human readable identifier to flights
        first_flight = None
        for uid, flight in self.flights.items():
            fli_item = QStandardItem(flt_ico, "Flight: {}".format(flight.name))
            if first_flight is None:
                first_flight = fli_item
            fli_item.setToolTip("UUID: {}".format(uid))
            fli_item.setEditable(False)
            fli_item.setData(flight, QtCore.Qt.UserRole)

            gps_path, gps_uid = flight.gps_file
            gps = QStandardItem("GPS: {}".format(gps_uid))
            gps.setToolTip("File Path: {}".format(gps_path))
            gps.setEditable(False)
            gps.setData(gps_uid)  # For future use

            grav_path, grav_uid = flight.gravity_file
            if grav_path is not None:
                _, grav_fname = os.path.split(grav_path)
            else:
                grav_fname = '<None>'
            grav = QStandardItem("Gravity: {}".format(grav_fname))
            grav.setToolTip("File Path: {}".format(grav_path))
            grav.setEditable(False)
            grav.setData(grav_uid)  # For future use

            fli_item.appendRow(gps)
            fli_item.appendRow(grav)

            for line in flight:
                line_item = QStandardItem("Line {}:{}".format(
                    line.start, line.end))
                line_item.setEditable(False)
                fli_item.appendRow(line_item)
            fli_header.appendRow(fli_item)
        prj_header.appendRow(fli_header)

        root.appendRow(prj_header)
        self.log.debug("Tree Model generated")
        first_index = model.indexFromItem(first_flight)
        return model, first_index
Ejemplo n.º 31
0
 def recurse_ds_to_item(self, ds, parent):
   for el in ds:
     item = QStandardItem(str(el))
     parent.appendRow(item)
     if el.VR == 'SQ':
       for i, dataset in enumerate(el.value):
         sq_item_description = el.name.replace(" Sequence", "")  # XXX not i18n
         item_text = QStandardItem("{0:s} {1:d}".format(sq_item_description, i + 1))
         item.appendRow(item_text)
         self.recurse_ds_to_item(dataset, item_text)
Ejemplo n.º 32
0
 def __init__(self):
     super().__init__()
     top = QStandardItem('Gadget')
     self.appendRow(top)
     for sub in Gadget.__subclasses__():
         row = QStandardItem(sub.__name__)
         for g in sub.getinstances():
             row.appendRow(QStandardItem(g.name))
         top.appendRow(row)
     self.top = top
 def __init__(self, data):
     QStandardItemModel.__init__(self)
     self._data = data
     for j, d in enumerate(data):
         item = QStandardItem(d["type"])
         for obj in d["objects"]:
             child = QStandardItem(obj)
             child.setData(d["picture"], Qt.DecorationRole)  # Role 이름의 키 값을 가지게 될 데이터 정의
             item.appendRow(child)
         self.setItem(j, 0, item)
Ejemplo n.º 34
0
 def build_custom_tree(result, index_item):
     if type(result) is not ParsedCustom:
         return
     parent_item = index_item.child(index_item.rowCount() - 1)
     # Custom nodes have tree representation of their data
     # For the size of custom node, add an index indicator (e.g. [1])
     for i, array_index in enumerate(result.data):
         index_item = QStandardItem("[%d]" % i)
         parent_item.appendRow([index_item])
         # In a level under index indicator, show data types
         for sub_result in array_index:
             index_item.appendRow(build_row(sub_result))
             build_custom_tree(sub_result, index_item)
         if i == 0:
             self.setExpanded(index_item.index(), True)
     self.setExpanded(parent_item.index(), True)
Ejemplo n.º 35
0
 def addComment(self, HNComment):
     self.currentCommentCount += 1
     if not 'deleted' in HNComment:
         authorItem = QStandardItem(
             '<style>#author { color: gray; font-size: 11pt; '
             'margin-bottom: 5px } </style><p id="author">' +
             HNComment['by'] + ' ' +
             format_time(HNComment['time']) + '</p>')
         authorItem.setData(HNComment['pos'], Qt.UserRole + 1337)
         textItem = QStandardItem(unescape(HNComment['text']))
         textItem.setData(HNComment['pos'], Qt.UserRole + 1337)
         authorItem.appendRow(textItem)
         self.commentsTree.rootItem.appendRow(authorItem)
     if self.currentCommentCount == self.maxCommentCount:
         self.commentsTree.sortByColumn(0, Qt.AscendingOrder)
         self.commentsTree.expandAll()
         self.stackedWidget.setCurrentWidget(self.commentsTree)
Ejemplo n.º 36
0
Archivo: main.py Proyecto: lordmauve/mu
 def update_debug_inspector(self, locals_dict):
     """
     Given the contents of a dict representation of the locals in the
     current stack frame, update the debug inspector with the new values.
     """
     excluded_names = ['__builtins__', '__debug_code__',
                       '__debug_script__', ]
     names = sorted([x for x in locals_dict if x not in excluded_names])
     self.debug_model.clear()
     self.debug_model.setHorizontalHeaderLabels([_('Name'), _('Value'), ])
     for name in names:
         try:
             # DANGER!
             val = eval(locals_dict[name])
         except Exception:
             val = None
         if isinstance(val, list):
             # Show a list consisting of rows of position/value
             list_item = QStandardItem(name)
             for i, i_val in enumerate(val):
                 list_item.appendRow([
                     QStandardItem(str(i)),
                     QStandardItem(repr(i_val))
                 ])
             self.debug_model.appendRow([
                 list_item,
                 QStandardItem(_('(A list of {} items.)').format(len(val)))
             ])
         elif isinstance(val, dict):
             # Show a dict consisting of rows of key/value pairs.
             dict_item = QStandardItem(name)
             for k, k_val in val.items():
                 dict_item.appendRow([
                     QStandardItem(repr(k)),
                     QStandardItem(repr(k_val))
                 ])
             self.debug_model.appendRow([
                 dict_item,
                 QStandardItem(_('(A dict of {} items.)').format(len(val)))
             ])
         else:
             self.debug_model.appendRow([
                 QStandardItem(name),
                 QStandardItem(locals_dict[name]),
             ])
Ejemplo n.º 37
0
 def populate(self, file_info=None, db_file=None):
     if file_info is not None:
         self.file_info = file_info
         db_file = FileInspectorHelper.get_or_insert_file(file_info)
     self.model.clear()
     if db_file:
         for classe in db_file.classes:
             parent = QStandardItem("{0}:".format(classe.name))
             for method in classe.methods:
                 parent.appendRow(QStandardItem("{0}()".\
                     format(method.name)))
             self.model.appendRow(parent)
         for function in db_file.functions:
             self.model.appendRow(QStandardItem("{0}()".\
                 format(function.name)))
     
     name = db_file.name if db_file else file_info.fileName()
     header = QStandardItem(name)
     self.model.setHorizontalHeaderItem(0, header)
     self.expandAll()
Ejemplo n.º 38
0
    def fill_tree(self, children: List[FsFileInfo]) -> None:

        self.item.removeRows(0, self.item.rowCount())
        for child in self.tree.sort_children(children):
            subitem = QStandardItem(child.get_label())
            if child.checkable():
                subitem.setCheckable(True)
                subitem.setCheckState(True)
                subitem.setTristate(True)
                subitem.setCheckState(child.state)
            subitem.setEnabled(child.enable())
            subitem.setSelectable(child.selectable())
            subitem.setEditable(False)
            subitem.setData(QVariant(child), Qt.UserRole)

            if child.folderish():
                # Add "Loading..." entry in advance for when the user
                # will click to expand it.
                loaditem = QStandardItem(Translator.get("LOADING"))
                loaditem.setSelectable(False)
                subitem.appendRow(loaditem)

            self.item.appendRow(subitem)
Ejemplo n.º 39
0
 def fillParameterTree(self):
     rows = self.parameterModel.rowCount()
     if rows:
         while self.parameterModel.rowCount() > 0:
             self.parameterModel.removeRow(0)
     self.parameterList = []
     parameterStr = 'self.stack['
     
     for i, layer in enumerate(self.stack):
         parameterStr += '{}].'.format(i)
         layerBranch = QStandardItem(layer.name)
         self.root.appendRow(layerBranch)
         self.addTreeEntry(layerBranch, 'thickness (nm)',  layer.thickness, self.changeThickness)
         if layer.srough:
             self.addTreeEntry(layerBranch, 'thickness roughness layer (nm)', layer.sroughThickness, self.changeSroughThickness)
             self.addTreeEntry(layerBranch, 'Haze R', layer.sroughHazeR, self.changeSroughHazeR)
             self.addTreeEntry(layerBranch, 'Haze T', layer.sroughHazeT, self.changeSroughHazeT)
         if layer.criSource=='constant':
             self.addTreeEntry(layerBranch, 'constant n', layer.criConstant[0], self.changeConstantn)
             self.addTreeEntry(layerBranch, 'constant k', layer.criConstant[1], self.changeConstantk)
         if layer.criSource=='graded' and layer.criGrading['mode']=='constant':
             self.addTreeEntry(layerBranch, 'constant grading', layer.criGrading['value'], self.changeConstantGrading)
         if layer.criSource=='dielectric function':
             criBranch = QStandardItem('dielectric function parameters')
             layerBranch.appendRow(criBranch)
             self.addTreeEntry(criBranch, 'e0', layer.dielectricFunction['e0'],  self.changeConstante, level = 2)
             for idx, oscillator in enumerate(layer.dielectricFunction['oscillators']):
                 osciBranch = QStandardItem('{} {}'.format(idx, oscillator['name']))
                 criBranch.appendRow(osciBranch)
                 parameterNames = MODELS[oscillator['name']]['parameter']
                 for i, value in enumerate(oscillator['values']):
                     self.addTreeEntry(osciBranch, parameterNames[i], value, self.changeOscillator, level = 3)
         if layer.collection['source'] == 'from collection function' and layer.collection['mode'] == 'constant':
             self.addTreeEntry(layerBranch, 'constant collection efficiency', layer.collection['value'], self.changeConstantCollection)
         if layer.collection['source'] == 'from diffusion length':
             collectionBranch = QStandardItem('collection model')
             layerBranch.appendRow(collectionBranch)
             self.addTreeEntry(collectionBranch, 'space charge region width (nm)', layer.collection['SCRwidth'],  self.changeSCR, level = 2)
             self.addTreeEntry(collectionBranch, 'diffusion length (nm)', layer.collection['diffLength'], self.changeDiffL, level = 2)
             self.addTreeEntry(collectionBranch, 'recombination velocity (cm/s)', layer.collection['recVel'], self.changerecVel, level = 2)
     
     self.parameterTreeView.setColumnWidth(1, 80)
     self.parameterTreeView.header().setSectionResizeMode(QHeaderView.ResizeToContents)
     self.parameterTreeView.expandAll()
Ejemplo n.º 40
0
    def populate(self, data):
        """Populate the data model using the data passed
        from the extensions object.

        The data model has up to three root-level items:
        - Invalid metadata
        - Failed to load
        - Failed dependencies
        """

        # font for use in various Items
        bold = QFont()
        bold.setWeight(QFont.Bold)

        root = self.invisibleRootItem()
        infos = data['infos']
        if infos:
            # Handle extensions with metadata errors
            infos_item = QStandardItem()
            infos_item.setFont(bold)
            infos_item.setText(_("Invalid metadata:"))
            infos_tooltip = (
                _("Extensions whose extension.cnf file has errors.\n"
                  "They will be loaded nevertheless."))
            infos_item.setToolTip(infos_tooltip)

            root.appendRow(infos_item)
            for info in infos:
                name_item = QStandardItem(info)
                name_item.setToolTip(infos_tooltip)
                icon = self.extensions.icon(info)
                if icon:
                    name_item.setIcon(icon)
                details_item = QStandardItem(infos[info])
                details_item.setToolTip(infos_tooltip)
                infos_item.appendRow([name_item, details_item])

        exceptions = data['exceptions']
        if exceptions:
            # Handle extensions that failed to load properly
            import traceback
            exceptions_item = self.exceptions_item = QStandardItem()
            exceptions_item.setFont(bold)
            exceptions_item.setText(_("Failed to load:"))
            extensions_tooltip = (
                _("Extensions that failed to load properly.\n"
                  "Double click on name to show the stacktrace.\n"
                  "Please contact the extension maintainer."))
            exceptions_item.setToolTip(extensions_tooltip)

            root.appendRow(exceptions_item)
            for ext in exceptions:
                extension_info = self.extensions.infos(ext)
                name = (extension_info.get('extension-name', ext)
                    if extension_info
                    else ext)
                name_item = QStandardItem(name)
                name_item.setToolTip(extensions_tooltip)
                icon = self.extensions.icon(ext)
                if icon:
                    name_item.setIcon(icon)
                exc_info = exceptions[ext]
                # store exception information in the first item
                name_item.exception_info = exc_info
                message = '{}: {}'.format(exc_info[0].__name__, exc_info[1])
                details_item = QStandardItem(message)
                details_item.setToolTip(extensions_tooltip)
                exceptions_item.appendRow([name_item, details_item])

        dependencies = data['dependencies']
        if dependencies:
            # Handle extensions with dependency issues
            dep_item = QStandardItem(_("Failed dependencies:"))
            dep_item.setFont(bold)
            dep_tooltip = (
                _("Extensions with failed or circular dependencies.\n"
                  "They are not loaded."))
            dep_item.setToolTip(dep_tooltip)

            root.appendRow(dep_item)
            missing = dependencies.get('missing', None)
            if missing:
                missing_item = QStandardItem(_("Missing:"))
                missing_item.setFont(bold)
                missing_item.setToolTip(dep_tooltip)
                dep_item.appendRow(missing_item)
                for m in missing:
                    item = QStandardItem(m)
                    item.setToolTip(dep_item)
                    missing_item.appendRow(item)
            inactive = dependencies.get('inactive', None)
            if inactive:
                inactive_item = QStandardItem(_("Inactive:"))
                inactive_item.setFont(bold)
                inactive_item.setToolTip(dep_tooltip)
                dep_item.appendRow(inactive_item)
                for i in inactive:
                    item = QStandardItem(i)
                    item.setToolTip(dep_tooltip)
                    inactive_item.appendRow(item)
            circular = dependencies.get('circular', None)
            if circular:
                circular_item = QStandardItem(_("Circular:"))
                circular_item.setFont(bold)
                circular_item.setToolTip(dep_tooltip)
                dep_item.appendRow(circular_item)
                item = QStandardItem(' | '.join(circular))
                item.setToolTip(dep_tooltip)
                circular_item.appendRow(item)
Ejemplo n.º 41
0
    def add_device_to_tree(self, device):
        # check if device is already added
        if len(device['uid']) > 0:
            for row in range(self.model_devices.rowCount()):
                existing_name = self.model_devices.item(row, 0).text()
                exisitng_uid = self.tree_devices.indexWidget(self.model_devices.item(row, 1).index()).text()

                if device['name'] == existing_name and device['uid'] == exisitng_uid:
                    EventLogger.info('Ignoring duplicate device "{0}" with UID "{1}"'
                                     .format(device['name'], device['uid']))
                    return

        # add device
        name_item = QStandardItem(device['name'])
        uid_item = QStandardItem('')

        self.model_devices.appendRow([name_item, uid_item])

        edit_uid = QLineEdit()
        edit_uid.setPlaceholderText('Enter UID')
        edit_uid.setValidator(QRegExpValidator(QRegExp('^[{0}]{{1,6}}$'.format(BASE58)))) # FIXME: use stricter logic
        edit_uid.setText(device['uid'])

        self.tree_devices.setIndexWidget(uid_item.index(), edit_uid)

        value_specs = device_specs[device['name']]['values']
        parent_item = QStandardItem('Values')

        name_item.appendRow([parent_item, QStandardItem('')])
        self.tree_devices.expand(parent_item.index())

        # add values
        for value_spec in value_specs:
            value_name_item = QStandardItem(value_spec['name'])
            value_interval_item = QStandardItem('')

            parent_item.appendRow([value_name_item, value_interval_item])

            spinbox_interval = IntervalWidget()
            spinbox_interval.set_interval(device['values'][value_spec['name']]['interval'])

            self.tree_devices.setIndexWidget(value_interval_item.index(), spinbox_interval)

            if value_spec['subvalues'] != None:
                for subvalue_name in value_spec['subvalues']:
                    subvalue_name_item = QStandardItem(subvalue_name)
                    subvalue_check_item = QStandardItem('')

                    value_name_item.appendRow([subvalue_name_item, subvalue_check_item])

                    check_subvalue = QCheckBox()
                    check_subvalue.setChecked(device['values'][value_spec['name']]['subvalues'][subvalue_name])

                    self.tree_devices.setIndexWidget(subvalue_check_item.index(), check_subvalue)

        self.tree_devices.expand(name_item.index())

        # add options
        option_specs = device_specs[device['name']]['options']

        if option_specs != None:
            parent_item = QStandardItem('Options')

            name_item.appendRow([parent_item, QStandardItem('')])

            for option_spec in option_specs:
                option_name_item = QStandardItem(option_spec['name'])
                option_widget_item = QStandardItem('')

                parent_item.appendRow([option_name_item, option_widget_item])

                if option_spec['type'] == 'choice':
                    widget_option_value = QComboBox()

                    for option_value_spec in option_spec['values']:
                        widget_option_value.addItem(option_value_spec[0], option_value_spec[1])

                    widget_option_value.setCurrentIndex(widget_option_value.findText(device['options'][option_spec['name']]['value']))
                elif option_spec['type'] == 'int':
                    widget_option_value = QSpinBox()
                    widget_option_value.setRange(option_spec['minimum'], option_spec['maximum'])
                    widget_option_value.setSuffix(option_spec['suffix'])
                    widget_option_value.setValue(device['options'][option_spec['name']]['value'])
                elif option_spec['type'] == 'bool':
                    widget_option_value = QCheckBox()
                    widget_option_value.setChecked(device['options'][option_spec['name']]['value'])

                self.tree_devices.setIndexWidget(option_widget_item.index(), widget_option_value)
Ejemplo n.º 42
0
    def populate(self):
        """Populate the tree view with data from the installed extensions.
        """

        # TODO/Question:
        # Would it make sense to move this to a dedicated model class
        # complementing the FailedModel?

        root = self.tree.model().invisibleRootItem()
        extensions = app.extensions()
        for ext in extensions.installed_extensions():
            ext_infos = extensions.infos(ext)
            display_name = ext_infos.get(ext, ext) if ext_infos else ext.name()
            loaded_extension = extensions.get(ext)
            if loaded_extension:
                display_name += ' ({})'.format(loaded_extension.load_time())

            name_item = QStandardItem(display_name)
            name_item.extension_name = ext
            name_item.setCheckable(True)
            self.name_items[ext] = name_item
            icon = extensions.icon(ext)
            if icon:
                name_item.setIcon(icon)
            root.appendRow([name_item])
            for entry in [
                'extension-name',
                'short-description',
                'description',
                'version',
                'api-version',
                'dependencies',
                'maintainers',
                'repository',
                'website',
                'license'
            ]:
                label_item = QStandardItem('{}:'.format(
                    self.config_labels[entry]))
                label_item.setTextAlignment(Qt.AlignTop)
                bold = QFont()
                bold.setWeight(QFont.Bold)
                label_item.setFont(bold)
                details = ext_infos.get(entry, "") if ext_infos else ""
                if type(details) == list:
                    details = '\n'.join(details)
                details_item = QStandardItem(details)
                details_item.setTextAlignment(Qt.AlignTop)
                if entry == 'api-version':
                    # Check for correct(ly formatted) api-version entry
                    # and highlight it in case of mismatch
                    api_version = appinfo.extension_api
                    if not details:
                        details_item.setFont(bold)
                        details_item.setText(
                            _("Misformat: {api}").format(details))
                    elif not details == api_version:
                            details_item.setFont(bold)
                            details_item.setText('{} ({}: {})'.format(
                                details,
                                appinfo.appname,
                                api_version))
                name_item.appendRow([label_item, details_item])
    model = QStandardItemModel(None)

    rootItem = model.invisibleRootItem()

    # Defining a couple of items
    americaItem = QStandardItem("America")
    canadaItem = QStandardItem("Canada")
    europeItem = QStandardItem("Europe")
    franceItem = QStandardItem("France")
    brittanyItem = QStandardItem("Brittany")

    # Building up the hierarchy
    rootItem.appendRow(americaItem)
    rootItem.appendRow(europeItem)
    americaItem.appendRow(canadaItem)
    europeItem.appendRow(franceItem)
    franceItem.appendRow(brittanyItem)

    tree_view.setModel(model)

    # Bind selection to the print_selection function (must be after the model setup)
    selection_model = tree_view.selectionModel()
    selection_model.selectionChanged.connect(print_selection)

    tree_view.expandAll()      # expand all (this is not the case by default)
    tree_view.show()

    # The mainloop of the application. The event handling starts from this point.
    # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
    exit_code = app.exec_()
Ejemplo n.º 44
0
 def __get_db_tables(self, db_name) -> QStandardItem:
     item = QStandardItem(db_name)
     for (v,) in self.__dbAccess.get_tables(db_name):
         item.appendRow(QStandardItem(str(v)))
     return item
Ejemplo n.º 45
0
def loadProject(project, zip=None):
    """
    Loads a project.
    @param project: the filename of the project to open.
    @param zip: whether the project is a zipped or not.
    @return: an array of errors, empty if None.
    """

    mw = mainWindow()
    errors = []

    ####################################################################################################################
    # Read and store everything in a dict

    log("\nLoading {} ({})".format(project, "ZIP" if zip else "not zip"))
    if zip:
        files = loadFilesFromZip(project)

        # Decode files
        for f in files:
            if f[-4:] not in [".xml", "opml"]:
                files[f] = files[f].decode("utf-8")

    else:
        # Project path
        dir = os.path.dirname(project)

        # Folder containing file: name of the project file (without .msk extension)
        folder = os.path.splitext(os.path.basename(project))[0]

        # The full path towards the folder containing files
        path = os.path.join(dir, folder, "")

        files = {}
        for dirpath, dirnames, filenames in os.walk(path):
            p = dirpath.replace(path, "")
            for f in filenames:
                # mode = "r" + ("b" if f[-4:] in [".xml", "opml"] else "")
                if f[-4:] in [".xml", "opml"]:
                    with open(os.path.join(dirpath, f), "rb") as fo:
                        files[os.path.join(p, f)] = fo.read()
                else:
                    with open(os.path.join(dirpath, f), "r", encoding="utf8") as fo:
                        files[os.path.join(p, f)] = fo.read()

        # Saves to cache (only if we loaded from disk and not zip)
        global cache
        cache = files
        
        # FIXME: watch directory for changes

    # Sort files by keys
    files = OrderedDict(sorted(files.items()))

    ####################################################################################################################
    # Settings

    if "settings.txt" in files:
        settings.load(files["settings.txt"], fromString=True, protocol=0)
    else:
        errors.append("settings.txt")

    # Just to be sure
    settings.saveToZip = zip

    ####################################################################################################################
    # Labels

    mdl = mw.mdlLabels
    mdl.appendRow(QStandardItem(""))  # Empty = No labels
    if "labels.txt" in files:
        log("\nReading labels:")
        for s in files["labels.txt"].split("\n"):
            if not s:
                continue

            m = re.search(r"^(.*?):\s*(.*)$", s)
            txt = m.group(1)
            col = m.group(2)
            log("* Add status: {} ({})".format(txt, col))
            icon = iconFromColorString(col)
            mdl.appendRow(QStandardItem(icon, txt))

    else:
        errors.append("labels.txt")

    ####################################################################################################################
    # Status

    mdl = mw.mdlStatus
    mdl.appendRow(QStandardItem(""))  # Empty = No status
    if "status.txt" in files:
        log("\nReading Status:")
        for s in files["status.txt"].split("\n"):
            if not s:
                continue
            log("* Add status:", s)
            mdl.appendRow(QStandardItem(s))
    else:
        errors.append("status.txt")

    ####################################################################################################################
    # Infos

    mdl = mw.mdlFlatData
    if "infos.txt" in files:
        md, body = parseMMDFile(files["infos.txt"], asDict=True)

        row = []
        for name in ["Title", "Subtitle", "Serie", "Volume", "Genre", "License", "Author", "Email"]:
            row.append(QStandardItem(md.get(name, "")))

        mdl.appendRow(row)

    else:
        errors.append("infos.txt")

    ####################################################################################################################
    # Summary

    mdl = mw.mdlFlatData
    if "summary.txt" in files:
        md, body = parseMMDFile(files["summary.txt"], asDict=True)

        row = []
        for name in ["Situation", "Sentence", "Paragraph", "Page", "Full"]:
            row.append(QStandardItem(md.get(name, "")))

        mdl.appendRow(row)

    else:
        errors.append("summary.txt")

    ####################################################################################################################
    # Plots

    mdl = mw.mdlPlots
    if "plots.xml" in files:
        log("\nReading plots:")
        # xml = bytearray(files["plots.xml"], "utf-8")
        root = ET.fromstring(files["plots.xml"])

        for plot in root:
            # Create row
            row = getStandardItemRowFromXMLEnum(plot, Plot)

            # Log
            log("* Add plot: ", row[0].text())

            # Characters
            if row[Plot.characters.value].text():
                IDs = row[Plot.characters.value].text().split(",")
                item = QStandardItem()
                for ID in IDs:
                    item.appendRow(QStandardItem(ID.strip()))
                row[Plot.characters.value] = item

            # Subplots
            for step in plot:
                row[Plot.steps.value].appendRow(
                    getStandardItemRowFromXMLEnum(step, PlotStep)
                )

            # Add row to the model
            mdl.appendRow(row)

    else:
        errors.append("plots.xml")

    ####################################################################################################################
    # World

    mdl = mw.mdlWorld
    if "world.opml" in files:
        log("\nReading World:")
        # xml = bytearray(files["plots.xml"], "utf-8")
        root = ET.fromstring(files["world.opml"])
        body = root.find("body")

        for outline in body:
            row = getOutlineItem(outline, World)
            mdl.appendRow(row)

    else:
        errors.append("world.opml")

    ####################################################################################################################
    # Characters

    mdl = mw.mdlCharacter
    log("\nReading Characters:")
    for f in [f for f in files if "characters" in f]:
        md, body = parseMMDFile(files[f])
        c = mdl.addCharacter()
        c.lastPath = f

        color = False
        for desc, val in md:

            # Base infos
            if desc in characterMap.values():
                key = [key for key, value in characterMap.items() if value == desc][0]
                index = c.index(key.value)
                mdl.setData(index, val)

            # Character color
            elif desc == "Color" and not color:
                c.setColor(QColor(val))
                # We remember the first time we found "Color": it is the icon color.
                # If "Color" comes a second time, it is a Character's info.
                color = True

            # Character's infos
            else:
                c.infos.append(CharacterInfo(c, desc, val))

        log("* Adds {} ({})".format(c.name(), c.ID()))

    ####################################################################################################################
    # Texts
    # We read outline form the outline folder. If revisions are saved, then there's also a revisions.xml which contains
    # everything, but the outline folder takes precedence (in cases it's been edited outside of manuksript.

    mdl = mw.mdlOutline
    log("\nReading outline:")
    paths = [f for f in files if "outline" in f]
    outline = OrderedDict()

    # We create a structure of imbricated OrderedDict to store the whole tree.
    for f in paths:
        split = f.split(os.path.sep)[1:]
        # log("* ", split)

        last = ""
        parent = outline
        parentLastPath = "outline"
        for i in split:
            if last:
                parent = parent[last]
                parentLastPath = os.path.join(parentLastPath, last)
            last = i

            if not i in parent:
                # If not last item, then it is a folder
                if i != split[-1]:
                    parent[i] = OrderedDict()

                # If file, we store it
                else:
                    parent[i] = files[f]

                # We store f to add it later as lastPath
                parent[i + ":lastPath"] = os.path.join(parentLastPath, i)



    # We now just have to recursively add items.
    addTextItems(mdl, outline)

    # Adds revisions
    if "revisions.xml" in files:
        root = ET.fromstring(files["revisions.xml"])
        appendRevisions(mdl, root)

    # Check IDS
    mdl.rootItem.checkIDs()

    return errors
Ejemplo n.º 46
0
 def __updateSlotsModel(self):
     """
     Private slot to update the slots tree display.
     """
     self.filterEdit.clear()
     
     try:
         dlg = uic.loadUi(
             self.formFile, package=self.project.getProjectPath())
         objects = dlg.findChildren(QWidget) + dlg.findChildren(QAction)
         
         signatureList = self.__signatures()
         
         self.slotsModel.clear()
         self.slotsModel.setHorizontalHeaderLabels([""])
         for obj in objects:
             name = obj.objectName()
             if not name or name.startswith("qt_"):
                 # ignore un-named or internal objects
                 continue
             
             metaObject = obj.metaObject()
             className = metaObject.className()
             itm = QStandardItem("{0} ({1})".format(name, className))
             self.slotsModel.appendRow(itm)
             for index in range(metaObject.methodCount()):
                 metaMethod = metaObject.method(index)
                 if metaMethod.methodType() == QMetaMethod.Signal:
                     if qVersion() >= "5.0.0":
                         itm2 = QStandardItem("on_{0}_{1}".format(
                             name,
                             bytes(metaMethod.methodSignature()).decode()))
                     else:
                         itm2 = QStandardItem("on_{0}_{1}".format(
                             name, metaMethod.signature()))
                     itm.appendRow(itm2)
                     if self.__module is not None:
                         if qVersion() >= "5.0.0":
                             method = "on_{0}_{1}".format(
                                 name,
                                 bytes(metaMethod.methodSignature())
                                 .decode().split("(")[0])
                         else:
                             method = "on_{0}_{1}".format(
                                 name, metaMethod.signature().split("(")[0])
                         method2 = "{0}({1})".format(
                             method, ", ".join(
                                 [self.__mapType(t)
                                  for t in metaMethod.parameterTypes()]))
                         
                         if method2 in signatureList or \
                                 method in signatureList:
                             itm2.setFlags(Qt.ItemFlags(Qt.ItemIsEnabled))
                             itm2.setCheckState(Qt.Checked)
                             itm2.setForeground(QBrush(Qt.blue))
                             continue
                     
                     returnType = self.__mapType(
                         metaMethod.typeName().encode())
                     if returnType == 'void':
                         returnType = ""
                     parameterTypesList = [
                         self.__mapType(t)
                         for t in metaMethod.parameterTypes()]
                     pyqtSignature = ", ".join(parameterTypesList)
                     
                     parameterNames = metaMethod.parameterNames()
                     if parameterNames:
                         for index in range(len(parameterNames)):
                             if not parameterNames[index]:
                                 parameterNames[index] = \
                                     QByteArray("p{0:d}".format(index)
                                                .encode("utf-8"))
                     parameterNamesList = [bytes(n).decode()
                                           for n in parameterNames]
                     methNamesSig = ", ".join(parameterNamesList)
                     
                     if methNamesSig:
                         if qVersion() >= "5.0.0":
                             pythonSignature = \
                                 "on_{0}_{1}(self, {2})".format(
                                     name,
                                     bytes(metaMethod.methodSignature())
                                     .decode().split("(")[0],
                                     methNamesSig)
                         else:
                             pythonSignature = \
                                 "on_{0}_{1}(self, {2})".format(
                                     name,
                                     metaMethod.signature().split("(")[0],
                                     methNamesSig)
                     else:
                         if qVersion() >= "5.0.0":
                             pythonSignature = "on_{0}_{1}(self)".format(
                                 name,
                                 bytes(metaMethod.methodSignature())
                                 .decode().split("(")[0])
                         else:
                             pythonSignature = "on_{0}_{1}(self)".format(
                                 name,
                                 metaMethod.signature().split("(")[0])
                     itm2.setData(pyqtSignature, pyqtSignatureRole)
                     itm2.setData(pythonSignature, pythonSignatureRole)
                     itm2.setData(returnType, returnTypeRole)
                     itm2.setData(parameterTypesList,
                                  parameterTypesListRole)
                     itm2.setData(parameterNamesList,
                                  parameterNamesListRole)
                     
                     itm2.setFlags(Qt.ItemFlags(
                         Qt.ItemIsUserCheckable |
                         Qt.ItemIsEnabled |
                         Qt.ItemIsSelectable)
                     )
                     itm2.setCheckState(Qt.Unchecked)
         
         self.slotsView.sortByColumn(0, Qt.AscendingOrder)
     except (AttributeError, ImportError,
             xml.etree.ElementTree.ParseError) as err:
         E5MessageBox.critical(
             self,
             self.tr("uic error"),
             self.tr(
                 """<p>There was an error loading the form <b>{0}</b>"""
                 """.</p><p>{1}</p>""").format(self.formFile, str(err)))