Пример #1
0
 def __init__(self, path, treewidget, is_python=True):
     QTreeWidgetItem.__init__(self, treewidget, QTreeWidgetItem.Type)
     self.path = path
     self.setIcon(
         0, ima.icon('python') if is_python else ima.icon('TextFileIcon'))
     self.setToolTip(0, path)
     set_item_user_text(self, path)
Пример #2
0
 def create_dir_item(dirname, parent):
     if dirname not in root_path_list:
         displayed_name = osp.basename(dirname)
     else:
         displayed_name = dirname
     item = QTreeWidgetItem(parent, [displayed_name],
                            QTreeWidgetItem.Type)
     item.setIcon(0, ima.icon('DirClosedIcon'))
     return item
Пример #3
0
    def set_equation(self, eq_name=None, eq_expression=None):
        """Place equation in main dialog."""

        current_item = self.list_derived_components.currentItem()
        if current_item and eq_name == current_item.text(0):
            current_item.setText(1, eq_expression)
        else:
            new_row = QTreeWidgetItem()
            new_row.setText(0, eq_name)
            new_row.setText(1, eq_expression)

            self.list_derived_components.addTopLevelItem(new_row)
Пример #4
0
    def __init__(self, parent, filename, sorting):

        self.sorting = sorting
        self.filename = osp.basename(filename)

        title_format = to_text_string('<b>{0}</b><br>'
                                      '<small><em>{1}</em>'
                                      '</small>')
        title = (title_format.format(osp.basename(filename),
                                     osp.dirname(filename)))
        QTreeWidgetItem.__init__(self, parent, [title], QTreeWidgetItem.Type)

        self.setToolTip(0, filename)
Пример #5
0
 def methodSelected(self, action, collec):
     # print(action.text()) #Choice
     # if (self.ui.treewidget.count() == 5):
     #   self.ui.label.setText("Maximum number of queries")
     #   return
     # self.ui.label.setText("")
     Choice = action.text()
     Stock = collec
     # print(collec)  #Stock Name
     # print(db_origin)  #DataBase name
     # list1 = [self.tr(Stock+"-"+Choice+"-"+db_origin)]
     # self.ui.treewidget.addItems(list1)
     parent = QTreeWidgetItem(self.ui.treeWidget_2)
     parent.setText(0, Stock.decode("utf-8") + "-" + Choice)
Пример #6
0
 def update(self, data):
     """
     Update the gui elements.
     :param data: Data in format of AlgorithmProgressModel.get_running_algorithm_data()
     """
     self.tree.clear()
     for alg_data in data:
         name, id, properties = alg_data
         item = QTreeWidgetItem([name])
         self.tree.addTopLevelItem(item)
         progress_bar = QProgressBar()
         progress_bar.setAlignment(Qt.AlignHCenter)
         self.presenter.add_progress_bar(id, progress_bar)
         cancel_button = CancelButton(self.presenter, id)
         self.tree.setItemWidget(item, 1, progress_bar)
         self.tree.setItemWidget(item, 2, cancel_button)
         for prop in properties:
             item.addChild(QTreeWidgetItem(prop))
Пример #7
0
 def code_sort_tree(self, companies):
     self.ui.treeWidget.clear()
     sorted_comps = companies.sort_values(["code"])
     code_list = sorted_comps["code"].tolist()
     name_list = sorted_comps["name"].tolist()
     shares_parent = QTreeWidgetItem(self.ui.treeWidget)
     shares_parent.setText(0, "个股行情")
     for idx, val in enumerate(code_list):
         child = QTreeWidgetItem(shares_parent)
         child.setText(0, name_list[idx] + "-" + str(val))
     self.ui.treeWidget.expandToDepth(0)
Пример #8
0
 def init_treeWidget(self, list1, series):
     self.ui.treeWidget.clear()
     for j in list1:
         parent = QTreeWidgetItem(self.ui.treeWidget)  #populate treewidget with names
         parent.setText(0,j)
         var = series.loc[series["c_name"] == j]
         list2 = var["code"].tolist()
         name = var["name"].tolist()
         #var = showcollection(i) #Display database items
         for idx,val in enumerate(list2):
             child = QTreeWidgetItem(parent)
             child.setText(0, name[idx]+"-"+str(val))
Пример #9
0
 def search_comp(self, companies):
     self.ui.treeWidget.clear()
     text = self.ui.search_lineEdit.text()
     filtered_codes = companies[companies['code'].str.contains(text)]
     filtered_names = companies[companies['name'].str.contains(text)]
     filtered_comps = filtered_codes.append(filtered_names)
     code_list = filtered_comps["code"].tolist()
     name_list = filtered_comps["name"].tolist()
     parent = QTreeWidgetItem(self.ui.treeWidget)
     parent.setText(0, "搜索结果")
     for idx, val in enumerate(code_list):
         child = QTreeWidgetItem(parent)
         child.setText(0, name_list[idx] + "-" + str(val))
     self.ui.treeWidget.expandToDepth(0)
Пример #10
0
 def __init__(self, name, line, parent, preceding):
     if preceding is None:
         QTreeWidgetItem.__init__(self, parent, QTreeWidgetItem.Type)
     else:
         if preceding is not parent:
             # Preceding must be either the same as item's parent
             # or have the same parent as item
             while preceding.parent() is not parent:
                 preceding = preceding.parent()
                 if preceding is None:
                     break
         if preceding is None:
             QTreeWidgetItem.__init__(self, parent, QTreeWidgetItem.Type)
         else:
             QTreeWidgetItem.__init__(self, parent, preceding,
                                      QTreeWidgetItem.Type)
     self.setText(0, name)
     parent_text = from_qvariant(parent.data(0, Qt.UserRole),
                                 to_text_string)
     set_item_user_text(self, parent_text+'/'+name)
     self.line = line
Пример #11
0
 def _add_tree_items(self, item_list, algorithm_data):
     """
     Recursively adds QTreeWidgetItems to item_list. Data for the items
     are taken from algorithm_data
     :param item_list: A list of QTreeWidgetItem
     :param algorithm_data: A dict of algorithm descriptors as returned from
         Model.get_algorithm_data()
     :return: None
     """
     for key, sub_tree in sorted(algorithm_data.items()):
         if key == self.algorithm_key:
             for name, versions in sub_tree.items():
                 versions = sorted(versions)
                 default_version_item = QTreeWidgetItem(['{0} v.{1}'.format(name, versions[-1])])
                 item_list.append(default_version_item)
                 if len(versions) > 1:
                     for v in versions[:-1]:
                         default_version_item.addChild(QTreeWidgetItem(['{0} v.{1}'.format(name, v)]))
         else:
             cat_item = QTreeWidgetItem([key])
             item_list.append(cat_item)
             cat_item_list = []
             self._add_tree_items(cat_item_list, sub_tree)
             cat_item.addChildren(cat_item_list)
Пример #12
0
 def refresh(self):
     title = _('Results for ')+self.filename
     self.set_title(title)
     self.clear()
     self.data = {}
     # Populating tree
     results = ((_('Convention'),
                ima.icon('convention'), self.results['C:']),
                (_('Refactor'),
                ima.icon('refactor'), self.results['R:']),
                (_('Warning'),
                ima.icon('warning'), self.results['W:']),
                (_('Error'),
                ima.icon('error'), self.results['E:']))
     for title, icon, messages in results:
         title += ' (%d message%s)' % (len(messages),
                                       's' if len(messages) > 1 else '')
         title_item = QTreeWidgetItem(self, [title], QTreeWidgetItem.Type)
         title_item.setIcon(0, icon)
         if not messages:
             title_item.setDisabled(True)
         modules = {}
         for module, lineno, message, msg_id in messages:
             basename = osp.splitext(osp.basename(self.filename))[0]
             if not module.startswith(basename):
                 # Pylint bug
                 i_base = module.find(basename)
                 module = module[i_base:]
             dirname = osp.dirname(self.filename)
             if module.startswith('.') or module == basename:
                 modname = osp.join(dirname, module)
             else:
                 modname = osp.join(dirname, *module.split('.'))
             if osp.isdir(modname):
                 modname = osp.join(modname, '__init__')
             for ext in ('.py', '.pyw'):
                 if osp.isfile(modname+ext):
                     modname = modname + ext
                     break
             if osp.isdir(self.filename):
                 parent = modules.get(modname)
                 if parent is None:
                     item = QTreeWidgetItem(title_item, [module],
                                            QTreeWidgetItem.Type)
                     item.setIcon(0, ima.icon('python'))
                     modules[modname] = item
                     parent = item
             else:
                 parent = title_item
             if len(msg_id) > 1:
                 text = "[%s] %d : %s" % (msg_id, lineno, message)
             else:
                 text = "%d : %s" % (lineno, message)
             msg_item = QTreeWidgetItem(parent, [text],
                                        QTreeWidgetItem.Type)
             msg_item.setIcon(0, ima.icon('arrow'))
             self.data[id(msg_item)] = (modname, lineno)
Пример #13
0
    def populate_tree(self):
        """Create each item (and associated data) in the tree"""
        if not len(self.data):
            warn_item = QTreeWidgetItem(self)
            warn_item.setData(0, Qt.DisplayRole, "No results to show.")
            warn_item.setFirstColumnSpanned(True)
            warn_item.setTextAlignment(0, Qt.AlignCenter)
            font = warn_item.font(0)
            font.setStyle(QFont.StyleItalic)
            warn_item.setFont(0, font)
            return

        try:
            monospace_font = self.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            monospace_font = QFont("Courier New")
            monospace_font.setPointSize(10)

        for testcase in self.data:
            testcase_item = QTreeWidgetItem(self)
            testcase_item.setData(
                1, Qt.DisplayRole, "{0}.{1}".format(
                    testcase.get("classname"), testcase.get("name")))
            testcase_item.setData(
                3, Qt.DisplayRole, float(testcase.get("time")) * 1e3)

            if len(testcase):
                test_error = testcase[0]

                status = test_error.tag
                testcase_item.setData(0, Qt.DisplayRole, status)
                color = COLORS[status]
                for col in range(self.columnCount()):
                    testcase_item.setBackground(col, color)

                type_ = test_error.get("type")
                message = test_error.get("message")
                if type_ and message:
                    text = "{0}: {1}".format(type_, message)
                elif type_:
                    text = type_
                else:
                    text = message
                testcase_item.setData(2, Qt.DisplayRole, text)

                text = test_error.text
                if text:
                    for line in text.rstrip().split("\n"):
                        error_content_item = QTreeWidgetItem(testcase_item)
                        error_content_item.setData(
                            0, Qt.DisplayRole, line)
                        error_content_item.setFirstColumnSpanned(True)
                        error_content_item.setFont(0, monospace_font)
            else:
                testcase_item.setData(0, Qt.DisplayRole, "ok")
Пример #14
0
    def load_dq_flags(self, layer_item=None, layer=None):
        self.tree_widget_dq.clear()
        if layer_item is None and layer is None:
            return

        layer = layer_item.data(0, Qt.UserRole)
        if layer is not None:
            if layer.meta.get('mask_def') is not None:
                for row in layer.meta['mask_def'].filled():
                    new_item = QTreeWidgetItem()
                    new_item.setFlags(new_item.flags()
                                      | Qt.ItemIsUserCheckable)
                    new_item.setCheckState(0, Qt.Checked)
                    new_item.setText(0, str(row['BIT']))
                    new_item.setData(0, Qt.UserRole, row['BIT'])
                    new_item.setText(1, row['NAME'])
                    new_item.setText(2, row['DESCRIPTION'])
                    self.tree_widget_dq.addTopLevelItem(new_item)
            else:
                new_item = QTreeWidgetItem()
                new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
                new_item.setCheckState(0, Qt.Checked)
                new_item.setText(0, str(0))
                new_item.setData(0, Qt.UserRole, 0)
                new_item.setText(1, 'BAD_PIXEL')
                new_item.setText(2, 'A bad pixel')
                self.tree_widget_dq.addTopLevelItem(new_item)
Пример #15
0
 def __init__(self, parent, ref, name, kind, position, status, selected):
     QTreeWidgetItem.__init__(self, parent, QTreeWidgetItem.Type)
     self.parent = parent
     self.ref = ref
     self.num_children = 0
     self.update_info(name, kind, position, status, selected)
Пример #16
0
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        cwd = os.getcwd()
        cwd = str(cwd)
        if os.path.isfile(cwd+"/time"):
            with open("time","r") as outfile:#reads current time
                history = cPickle.load(outfile)
            if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours
                print("Less than 12 hours. Loading previously saved Json...")
                #with open("time","w") as infile: #update time
                    #cPickle.dump(datetime.now(),infile)

            else:
                print("More than 12 hours. Updating Json...")
                data = ts.get_industry_classified()
                #data.to_json(cwd + "/class.json", orient="columns")#writes class data so no need to call Tushare agian
                with open("class.json","w+") as outfile:
                    cPickle.dump(data,outfile)
                now = datetime.now()
                with open("time", "w+") as outfile: #update time
                    cPickle.dump(now, outfile)

        else:
            print("No json found!") #If this is first time using tuchart in this directory
            data = df()
            data = ts.get_industry_classified()
            #var = data.to_json(cwd+"/class.json",orient="columns")
            with open('class.json', 'w+') as outfile: #records json
                cPickle.dump(data, outfile)
            now = datetime.now()
            with open("time", "w+") as outfile:
                cPickle.dump(now,outfile)

        with open("class.json", "r") as infile:  # reads current time
            series = cPickle.load(infile)
        #series = pd.read_json(cwd + "\\class.json")
        #series = ts.get_industry_classified()
        series = pd.DataFrame(series)
        curdate = time.strftime("%Y/%m/%d") #gets current time to put into dateedit
        dateobj = datetime.strptime(curdate, "%Y/%m/%d")#converts to datetime object
        past = dateobj - timedelta(days = 7)  #minus a week to start date
        pasttime = datetime.strftime(past, "%Y/%m/%d")
        QPast = QDate.fromString(pasttime,"yyyy/MM/dd") #convert to qtime so that widget accepts the values
        Qcurdate = QDate.fromString(curdate,"yyyy/MM/dd")
        list1 = series["c_name"].tolist()  #Get industry categories. Filters out redundant ones
        list1 = list(set(list1))
        #w = database()
        #zsparent = QTreeWidgetItem(self.ui.treeWidget)
        #zsparent.setText(0,"股票指数")
        #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]
        zsparent = QTreeWidgetItem(self.ui.treeWidget)
        zsparent.setText(0, "股票指数")
        zsnames = ["上证指数-sh", "深圳成指-sz", "沪深300指数-hs300", "上证50-sz50", "中小板-zxb", "创业板-cyb"]
        for k in zsnames:
            child = QTreeWidgetItem(zsparent)
            child.setText(0, k)

        for j in list1:
            parent = QTreeWidgetItem(self.ui.treeWidget)  #populate treewidget with names
            parent.setText(0,j)
            var = series.loc[series["c_name"] == j]
            list2 = var["code"].tolist()
            name = var["name"].tolist()


            #var = showcollection(i) #Display database items
            for idx,val in enumerate(list2):
                child = QTreeWidgetItem(parent)
                child.setText(0, name[idx]+"-"+str(val))
                #for i in Drag:
                    #grandson = QTreeWidgetItem(child)     #Commented out because increases program response time
                    #grandson.setText(0, i)
        #self.ui.treeWidget.itemDoubleClicked.connect(self.onClickItem) #Display Collection items
        self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #self.ui.widget.setGeometry(QtCore.QRect(0, 30,1550, 861))
        file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "render.html")) #path to read html file
        local_url = QUrl.fromLocalFile(file_path)
        self.ui.widget.load(local_url)
        self.ui.commandLinkButton.setFixedSize(50, 50)
        self.ui.commandLinkButton.clicked.connect(self.classify)  #when the arrow button is clicked, trigger events


        #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
        #  QSizePolicy
        try:
            retain_size = self.ui.dateEdit_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.dateEdit_2.setSizePolicy(retain_size)
            retain_size = self.ui.comboBox.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.comboBox.setSizePolicy(retain_size)
            retain_size = self.ui.label_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.label_2.setSizePolicy(retain_size)
        except AttributeError:
            print("No PYQT5 Binding! Widgets might be deformed")



        self.ui.dateEdit.setDate(QPast)
        self.ui.dateEdit_2.setDate(Qcurdate)#populate widgets
        self.ui.dateEdit.setCalendarPopup(True)
        self.ui.dateEdit_2.setCalendarPopup(True)
        self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])
        self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
        self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget_2.customContextMenuRequested.connect(self.openWidgetMenu)
        #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
        self.ui.combobox.currentIndexChanged.connect(self.modifycombo)
Пример #17
0
    def showEvent(self, event):
        super().showEvent(event)
        ok_icon = QIcon(os.path.join(icons_dir, "task-accepted.png"))
        bad_icon = QIcon(os.path.join(icons_dir, "task-reject.png"))
        warn_icon = QIcon(os.path.join(icons_dir, "task-attempt.png"))
        all_prefix = os.path.commonprefix(self.file_list)
        if not os.path.exists(all_prefix):
            all_prefix = os.path.dirname(all_prefix)
        for file_num, file_path in enumerate(self.file_list):
            widget = QTreeWidgetItem(self.file_list_widget)
            widget.setText(0, os.path.relpath(file_path, all_prefix))
            if not os.path.exists(file_path):
                widget.setIcon(0, bad_icon)
                widget.setToolTip(0, "File do not exists")
                sub_widget = QTreeWidgetItem(widget)
                sub_widget.setText(0, "File do not exists")
                continue
            for mask_num, mask_mapper in enumerate(self.mask_mapper_list):
                if mask_mapper.is_ready():
                    mask_path = mask_mapper.get_mask_path(file_path)
                    exist = os.path.exists(mask_path)
                    if exist:
                        sub_widget = QTreeWidgetItem(widget)
                        sub_widget.setText(
                            0, "Mask {} ok".format(mask_mapper.name))
                        sub_widget.setIcon(0, ok_icon)
                        self.state_list[file_num, mask_num] = 0
                    else:
                        sub_widget = QTreeWidgetItem(widget)
                        sub_widget.setText(
                            0,
                            "Mask {} do not exists (path: {})".format(
                                mask_mapper.name,
                                os.path.relpath(mask_path, all_prefix)),
                        )
                        sub_widget.setIcon(0, bad_icon)
                        self.state_list[file_num, mask_num] = 2
                else:
                    sub_widget = QTreeWidgetItem(widget)
                    sub_widget.setText(
                        0, "Mask {} unknown".format(mask_mapper.name))
                    sub_widget.setIcon(0, warn_icon)
                    self.state_list[file_num, mask_num] = 1
            if self.state_list.shape[1] == 0:
                state = 0
            else:
                state = self.state_list[file_num].max()

            if state == 0:
                widget.setIcon(0, ok_icon)
            elif state == 1:
                widget.setIcon(0, warn_icon)
            else:
                widget.setIcon(0, bad_icon)
Пример #18
0
    def add_model_item(self, layer=None, model=None, unique=True):
        """
        Adds an `astropy.modeling.Model` to the loaded model tree widget.

        Parameters
        ----------
        """
        if layer is not None:
            self.contents.tree_widget_current_models.clear()

            if hasattr(layer.model, '_submodels'):
                models = layer.model._submodels
            else:
                models = [layer.model]
        elif model is not None:
            models = [model]
        else:
            return

        self.contents.tree_widget_current_models.clear()

        for model in models:
            if model is None:
                continue

            if unique:
                if self.get_model_item(model) is not None:
                    continue

            name = model.name

            if not name:
                count = 0

                root = self.contents.tree_widget_current_models.invisibleRootItem()

                for i in range(root.childCount()):
                    child = root.child(i)
                    pre_mod = child.data(0, Qt.UserRole)
                    pre_name = child.text(0)

                    if isinstance(model, pre_mod.__class__):
                        cur_num = next(iter([int(x) for x in re.findall(r'\d+', pre_name)]), 0) + 1

                        if cur_num > count:
                            count = cur_num

                name = model.__class__.__name__.replace('1D', '') + str(count)
                model._name = name

            new_item = QTreeWidgetItem()
            new_item.setFlags(new_item.flags() | Qt.ItemIsEditable)

            new_item.setText(0, name)
            new_item.setData(0, Qt.UserRole, model)

            for i, para in enumerate(model.param_names):
                new_para_item = QTreeWidgetItem(new_item)
                new_para_item.setText(0, para)
                new_para_item.setData(0, Qt.UserRole, para)
                new_para_item.setData(1, Qt.UserRole, model.parameters[i])
                new_para_item.setText(1, "{:g}".format(model.parameters[i]))
                new_para_item.setFlags(new_para_item.flags() |
                                       Qt.ItemIsEditable |
                                       Qt.ItemIsUserCheckable)

                new_para_item.setCheckState(2, Qt.Checked if model.fixed.get(para)
                                                          else Qt.Unchecked)

            self.contents.tree_widget_current_models.addTopLevelItem(new_item)
            self.contents.tree_widget_current_models.expandItem(new_item)

        self._update_arithmetic_text(layer)
Пример #19
0
    def set_data_view(self, data_dic: Dict[str, object], root: 'QTreeWidgetItem'):
        """
        递归方式显示json。
        显示的时候要注意层级。
        :param data_dic:
        :param root:
        :return:
        """
        for k in data_dic.keys():
            if isinstance(data_dic[k], dict):
                child = QTreeWidgetItem(root)
                child.setText(0, str(k))
                child.item_id = root.item_id + '-' + child.text(0)
                self.nodes[child.item_id] = child
                self.set_data_view(data_dic[k], child)
            else:
                child = QTreeWidgetItem(root)
                child.setText(0, str(k))
                child.item_id = root.item_id + '-' + child.text(0)
                self.nodes[child.item_id] = child

                child.setText(1, self.autorepr(data_dic[k]))
            self.try_expand_item(child)
Пример #20
0
 def update_view(self):
     # this part of the code is a hack - re-create tree every time
     # self.ui.treeWidget_stations.clear()
     # for group in self.file_handler.get_groups():
     #     node = QtGui.QTreeWidgetItem(self.ui.treeWidget_stations)
     #     node.setText(0, group)
     #     for ref in self.file_handler.get_group_members(group):
     #         mt_obj = self.file_handler.get_MT_obj(ref)
     #         child_node = QtGui.QTreeWidgetItem(node)
     #         child_node.setText(0, mt_obj.station)
     #         child_node.setText(1, ref)
     root = self.ui.treeWidget_stations.invisibleRootItem()
     groups = set()
     to_delete = []
     existing_groups = set(self.file_handler.get_groups())
     for i in range(root.childCount()):
         group_item = root.child(i)
         group_id = str(group_item.text(0))
         if group_id in existing_groups:
             groups.add(group_id)
             refs = set()
             # check station items
             for j in range(group_item.childCount()):
                 station_item = group_item.child(j)
                 station_ref = str(station_item.text(1))
                 mt_obj = self.file_handler.get_MT_obj(station_ref)
                 if mt_obj:
                     refs.add(station_ref)
                 else:
                     to_delete.append(station_item)
             # add new children
             for ref in self.file_handler.get_group_members(group_id):
                 if ref not in refs:
                     child_node = QTreeWidgetItem(group_item)
                     child_node.setText(
                         0,
                         self.file_handler.get_MT_obj(ref).station)
                     child_node.setText(1, ref)
         else:
             to_delete.append(group_item)
     # delete all non existed items
     for item in to_delete:
         (item.parent() or root).removeChild(item)
     # add now groups
     for group_id in existing_groups:
         if group_id not in groups:
             # create new node
             node = QTreeWidgetItem(self.ui.treeWidget_stations)
             node.setText(0, group_id)
             for ref in self.file_handler.get_group_members(group_id):
                 child_node = QTreeWidgetItem(node)
                 child_node.setText(
                     0,
                     self.file_handler.get_MT_obj(ref).station)
                 child_node.setText(1, ref)
     # self.ui.treeWidget_stations.updateGeometry()
     self.selection_changed.emit()
Пример #21
0
class FindWidget(BaseWidget):
    def __init__(self, main_window):

        super(FindWidget,
              self).__init__(main_window,
                             ui=u'extensions.FindInFiles.find_in_files')
        try:
            self._ide = self.extension_manager['OpenSesameIDE']
        except Exception:
            self.ui.find_in_files.disable()
            self.extension_manager.fire(
                u'notify',
                message=_(u'FindInFiles requires the OpenSesameIDE extension'))
            return

        self.ui.button_find.clicked.connect(self._find)
        self.ui.lineedit_needle.returnPressed.connect(self._find)
        self.ui.lineedit_filter.returnPressed.connect(self._find)
        self.ui.button_cancel.clicked.connect(self._cancel)
        self.ui.button_cancel.hide()
        self.ui.treewidget_results.itemActivated.connect(self._open_result)
        self._finder = None

    def setFocus(self):

        super(FindWidget, self).setFocus()
        selection = self.extension_manager.provide('ide_current_selection')
        if selection and u'\n' not in selection:
            self.ui.lineedit_needle.setText(selection)
        self.ui.lineedit_needle.setFocus()

    def _open_result(self, item, column):

        path, line_number = item.result
        self.extension_manager.fire(u'ide_open_file',
                                    path=path,
                                    line_number=line_number)
        self.extension_manager.fire(
            u'ide_search_text',
            needle=self.ui.lineedit_needle.text().strip(),
        )
        self.tabwidget.switch(u'OpenSesameIDE')

    def _find(self):

        needle = self.ui.lineedit_needle.text().strip()
        self._canceled = False
        if not needle:
            return
        filter = self.ui.lineedit_filter.text().strip()
        self.ui.button_cancel.show()
        self.ui.button_find.hide()
        self.ui.treewidget_results.clear()
        self._last_path = None
        self._queue = multiprocessing.Queue()
        self._finder = multiprocessing.Process(
            target=find_text_in_files,
            args=(self._queue, needle, list(self._ide.project_files()),
                  filter))
        self._n_matches = 0
        self._n_files = 0
        self._finder.start()
        oslogger.debug(u'finding {} (PID={})'.format(needle, self._finder.pid))
        self.extension_manager.fire(
            'register_subprocess',
            pid=self._finder.pid,
            description='find_text_in_files:{}'.format(needle))
        QTimer.singleShot(1000, self._check_finder)

    def _check_finder(self):

        if self._queue.empty():
            try:
                oslogger.debug(u'no results yet for finder (PID={})'.format(
                    self._finder.pid))
            except ValueError:
                # Is raised when getting the pid of a closed process
                return
            QTimer.singleShot(1000, self._check_finder)
            return
        path, line_number, matching_line = self._queue.get()
        if path is None or self._canceled:
            self.ui.button_cancel.hide()
            self.ui.button_find.show()
            self._finder.join()
            oslogger.debug(u'finder done (PID={})'.format(self._finder.pid))
            try:
                self._finder.close()
            except AttributeError:
                # Process.close() was introduced only in Python 3.7
                pass
            self.extension_manager.fire(
                u'notify',
                message=_('Found {} match(es) in {} file(s)').format(
                    self._n_matches, self._n_files)
                if self._n_matches else _('No matches found'))
            return
        if path != self._last_path:
            self._path_item = QTreeWidgetItem(self.ui.treewidget_results,
                                              [path])
            self._path_item.result = path, 1
            self.ui.treewidget_results.addTopLevelItem(self._path_item)
            self._last_path = path
            self._n_files += 1
        self._n_matches += 1
        line_item = QTreeWidgetItem(
            self._path_item, [u'{}: {}'.format(line_number, matching_line)])
        line_item.result = path, line_number
        self._path_item.addChild(line_item)
        QTimer.singleShot(10, self._check_finder)

    def _cancel(self):

        self._canceled = True
        try:
            alive = self._finder is not None and self._finder.is_alive()
        except ValueError:  # process is closed
            return
        if alive:
            oslogger.debug(u'terminating finder (PID={})'.format(
                self._finder.pid))
            self._finder.terminate()
 def __init__(self, parent, lineno, colno, match):
     self.lineno = lineno
     self.colno = colno
     self.match = match
     QTreeWidgetItem.__init__(self, parent, [self.__repr__()],
                              QTreeWidgetItem.Type)
Пример #23
0
 def add_metabolite(self, metabolite):
     item = QTreeWidgetItem(self.metabolite_list)
     item.setText(0, metabolite.id)
     item.setText(1, metabolite.name)
     item.setData(2, 0, metabolite)
Пример #24
0
 def LstSlots(self, Lst):
     for i in range(len(Lst)):
         names = QTreeWidgetItem([Lst[i]])
         self.treeWidget.addTopLevelItem(names)
Пример #25
0
    def __init__(self, import_dict, local_dict, viewer):
        """
        :type import_dict: dict[str, object]
        :type local_dict: dict[str, object]
        :param import_dict:
        :param local_dict:
        :param viewer:
        """
        super(ImportDialog, self).__init__()
        self.setWindowTitle("Import")
        self.viewer = viewer()
        self.local_viewer = viewer()
        self.import_dict = import_dict
        self.local_dict = local_dict
        conflicts = set(local_dict.keys()) & set(import_dict.keys())
        # print(conflicts)

        self.list_view = QTreeWidget()
        self.list_view.setColumnCount(4)
        self.radio_group_list = []
        self.checked_num = len(import_dict)

        def rename_func(ob_name, new_name_field, rename_radio):
            end_reg = re.compile(r"(.*) \((\d+)\)$")

            def in_func():
                if rename_radio.isChecked() and str(
                        new_name_field.text()).strip() == "":
                    match = end_reg.match(ob_name)
                    if match:
                        new_name_format = match.group(1) + " ({})"
                        i = int(match.group(2)) + 1
                    else:
                        new_name_format = ob_name + " ({})"
                        i = 1
                    while new_name_format.format(i) in self.local_dict:
                        i += 1
                    new_name_field.setText(new_name_format.format(i))

            return in_func

        def block_import(radio_btn, name_field):
            def inner_func():
                text = str(name_field.text()).strip()
                if text == "" and radio_btn.isChecked():
                    self.import_btn.setDisabled(True)
                else:
                    self.import_btn.setEnabled(True)

            return inner_func

        for name in sorted(import_dict.keys()):
            item = QTreeWidgetItem()
            item.setText(0, name)
            # noinspection PyTypeChecker
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(0, Qt.Checked)
            self.list_view.addTopLevelItem(item)
            if name in conflicts:
                group = QButtonGroup()
                overwrite = QRadioButton("Overwrite")
                overwrite.setChecked(True)
                rename = QRadioButton("Rename")
                new_name = QLineEdit()
                new_name.textChanged.connect(block_import(rename, new_name))
                rename.toggled.connect(block_import(rename, new_name))
                overwrite.toggled.connect(block_import(rename, new_name))

                rename.toggled.connect(rename_func(name, new_name, rename))
                group.addButton(overwrite)
                group.addButton(rename)
                self.radio_group_list.append(group)
                self.list_view.setItemWidget(item, 1, overwrite)
                self.list_view.setItemWidget(item, 2, rename)
                self.list_view.setItemWidget(item, 3, new_name)

        self.import_btn = QPushButton("Import")
        self.cancel_btn = QPushButton("Cancel")
        self.check_btn = QPushButton("Check all")
        self.uncheck_btn = QPushButton("Uncheck all")

        self.cancel_btn.clicked.connect(self.close)
        self.import_btn.clicked.connect(self.accept)
        self.check_btn.clicked.connect(self.check_all)
        self.uncheck_btn.clicked.connect(self.uncheck_all)

        self.list_view.itemSelectionChanged.connect(self.preview)
        self.list_view.itemChanged.connect(self.checked_change)

        layout = QVBoxLayout()
        info_layout = QHBoxLayout()
        info_layout.addWidget(self.list_view, 2)
        v1_lay = QVBoxLayout()
        v1_lay.addWidget(QLabel("Import:"))
        v1_lay.addWidget(self.viewer)
        info_layout.addLayout(v1_lay, 1)
        # info_layout.addWidget(self.local_viewer, 1)
        v2_lay = QVBoxLayout()
        v2_lay.addWidget(QLabel("Local:"))
        v2_lay.addWidget(self.local_viewer)
        info_layout.addLayout(v2_lay, 1)
        layout.addLayout(info_layout)
        btn_layout = QHBoxLayout()
        btn_layout.addWidget(self.check_btn)
        btn_layout.addWidget(self.uncheck_btn)
        btn_layout.addStretch()
        btn_layout.addWidget(self.import_btn)
        btn_layout.addWidget(self.cancel_btn)
        layout.addLayout(btn_layout)
        self.setLayout(layout)
Пример #26
0
    def populate_tree(self):
        """Create each item (and associated data) in the tree."""
        if not len(self.testresults):
            return _('No results to show.')

        try:
            monospace_font = self.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            monospace_font = QFont("Courier New")
            monospace_font.setPointSize(10)

        for testresult in self.testresults:
            testcase_item = QTreeWidgetItem(self)
            testcase_item.setData(0, Qt.DisplayRole, testresult.status)
            testcase_item.setData(1, Qt.DisplayRole, testresult.name)
            fullname = '{0}.{1}'.format(testresult.module, testresult.name)
            testcase_item.setToolTip(1, fullname)
            testcase_item.setData(2, Qt.DisplayRole, testresult.message)
            testcase_item.setData(3, Qt.DisplayRole, testresult.time * 1e3)
            color = COLORS[testresult.category]
            for col in range(self.columnCount()):
                testcase_item.setBackground(col, color)
            if testresult.extra_text:
                for line in testresult.extra_text.rstrip().split("\n"):
                    error_content_item = QTreeWidgetItem(testcase_item)
                    error_content_item.setData(0, Qt.DisplayRole, line)
                    error_content_item.setFirstColumnSpanned(True)
                    error_content_item.setFont(0, monospace_font)

        counts = Counter(res.category for res in self.testresults)
        if counts[Category.FAIL] == 1:
            test_or_tests = _('test')
        else:
            test_or_tests = _('tests')
        failed_txt = '{} {} failed'.format(counts[Category.FAIL],
                                           test_or_tests)
        passed_txt = '{} passed'.format(counts[Category.OK])
        other_txt = '{} other'.format(counts[Category.SKIP])
        msg = '<b>{}, {}, {}</b>'.format(failed_txt, passed_txt, other_txt)
        return msg
Пример #27
0
 def update_count(item: QTreeWidgetItem, count: int) -> None:
     """Update the number of graphs."""
     item.setText(1, f"{count}")
Пример #28
0
    def generate_context_menu(self, pos: QPoint):
        """
        Generate a context menu for contextMenuEvent

        Parameters
        ----------
        pos : QPoint
            The point where the context menu was requested
        """
        model_menu = QMenu()
        skip_text = "skip me"

        # Add filterbox to the context menu
        txt_box = QLineEdit(model_menu)
        txt_box.setPlaceholderText("Filter")
        txt_box.setClearButtonEnabled(True)
        txt_box_action = QWidgetAction(model_menu)
        txt_box_action.setDefaultWidget(txt_box)
        model_menu.addAction(txt_box_action)

        # Add result treeview to the context menu
        tree_view = QTreeWidget(model_menu)
        tree_view.header().close()
        tree_view_action = QWidgetAction(model_menu)
        tree_view_action.setDefaultWidget(tree_view)
        model_menu.addAction(tree_view_action)

        top_level_items = {}
        for cat in self._scene.registry.categories():
            item = QTreeWidgetItem(tree_view)
            item.setText(0, cat)
            item.setData(0, Qt.UserRole, skip_text)
            top_level_items[cat] = item

        registry = self._scene.registry
        for model, category in registry.registered_models_category_association(
        ).items():
            self.parent = top_level_items[category]
            item = QTreeWidgetItem(self.parent)
            item.setText(0, model)
            item.setData(0, Qt.UserRole, model)

        tree_view.expandAll()

        def click_handler(item):
            model_name = item.data(0, Qt.UserRole)
            if model_name == skip_text:
                return

            type_ = self._scene.registry.create(model_name)
            if type_:
                node = self._scene.create_node(type_)
                pos_view = self.mapToScene(pos)
                node.graphics_object.setPos(pos_view)
                self._scene.node_placed.emit(node)
            else:
                logger.debug("Model not found")

            model_menu.close()

        tree_view.itemClicked.connect(click_handler)

        # Setup filtering
        def filter_handler(text):
            for name, top_lvl_item in top_level_items.items():
                for i in range(top_lvl_item.childCount()):
                    child = top_lvl_item.child(i)
                    model_name = child.data(0, Qt.UserRole)
                    child.setHidden(text not in model_name)

        txt_box.textChanged.connect(filter_handler)

        # make sure the text box gets focus so the user doesn't have to click on it
        txt_box.setFocus()
        return model_menu
Пример #29
0
    def update_dependencies(self, dependencies):
        self.clear()
        headers = (_("Module"), _("Package name"), _(" Required "),
                   _(" Installed "), _("Provided features"))
        self.setHeaderLabels(headers)
        mandatory_item = QTreeWidgetItem(["Mandatory"])
        font = mandatory_item.font(0)
        font.setBold(True)
        mandatory_item.setFont(0, font)
        optional_item = QTreeWidgetItem(["Optional"])
        optional_item.setFont(0, font)
        self.addTopLevelItems([mandatory_item, optional_item])

        for dependency in dependencies:
            item = QTreeWidgetItem([
                dependency.modname, dependency.package_name,
                dependency.required_version, dependency.installed_version,
                dependency.features
            ])
            if dependency.check():
                item.setIcon(0, ima.icon('dependency_ok'))
            elif dependency.optional:
                item.setIcon(0, ima.icon('dependency_warning'))
                item.setForeground(2, QColor('#ff6a00'))
            else:
                item.setIcon(0, ima.icon('dependency_error'))
                item.setForeground(2, QColor(Qt.darkRed))
            if dependency.optional:
                optional_item.addChild(item)
            else:
                mandatory_item.addChild(item)
        self.expandAll()
Пример #30
0
def fill_item(item, value):
    """
    Display a dictionary as a QtTreeWidget

    adapted from http://stackoverflow.com/a/21806048/1221924
    """
    item.setExpanded(False)
    if hasattr(value, 'items'):
        for key, val in sorted(value.items()):
            child = QTreeWidgetItem()
            # val is dict or a list -> recurse
            if hasattr(val, 'items') or _listlike(val):
                child.setText(0, _short_repr(key).strip("'"))
                item.addChild(child)
                fill_item(child, val)
                if key == 'descriptors':
                    child.setExpanded(False)
            # val is not iterable -> show key and val on one line
            else:
                # Show human-readable datetime alongside raw timestamp.
                # 1484948553.567529 > '[2017-01-20 16:42:33] 1484948553.567529'
                if (key == 'time') and isinstance(val, float):
                    FMT = '%Y-%m-%d %H:%M:%S'
                    ts = datetime.fromtimestamp(val).strftime(FMT)
                    text = "time: [{}] {}".format(ts, val)
                else:
                    text = "{}: {}".format(
                        _short_repr(key).strip("'"), _short_repr(val))
                child.setText(0, text)
                item.addChild(child)

    elif type(value) is list:
        for val in value:
            if hasattr(val, 'items'):
                fill_item(item, val)
            elif _listlike(val):
                fill_item(item, val)
            else:
                child = QTreeWidgetItem()
                item.addChild(child)
                child.setExpanded(False)
                child.setText(0, _short_repr(val))
    else:
        child = QTreeWidgetItem()
        child.setText(0, _short_repr(value))
        item.addChild(child)
Пример #31
0
 def __init__(self, path, treewidget):
     QTreeWidgetItem.__init__(self, treewidget, QTreeWidgetItem.Type)
     self.path = path
     self.setIcon(0, ima.icon('python'))
     self.setToolTip(0, path)
     set_item_user_text(self, path)
Пример #32
0
def fill_item(item, value):
    """
    Display a dictionary as a QtTreeWidget

    adapted from http://stackoverflow.com/a/21806048/1221924
    """
    item.setExpanded(False)
    if hasattr(value, 'items'):
        for key, val in sorted(value.items()):
            child = QTreeWidgetItem()
            # val is dict or a list -> recurse
            if hasattr(val, 'items') or _listlike(val):
                child.setText(0, _short_repr(key).strip("'"))
                item.addChild(child)
                fill_item(child, val)
                if key == 'descriptors':
                    child.setExpanded(False)
            # val is not iterable -> show key and val on one line
            else:
                # Show human-readable datetime alongside raw timestamp.
                # 1484948553.567529 > '[2017-01-20 16:42:33] 1484948553.567529'
                if (key == 'time') and isinstance(val, float):
                    FMT = '%Y-%m-%d %H:%M:%S'
                    ts = datetime.fromtimestamp(val).strftime(FMT)
                    text = "time: [{}] {}".format(ts, val)
                else:
                    text = "{}: {}".format(_short_repr(key).strip("'"),
                                           _short_repr(val))
                child.setText(0, text)
                item.addChild(child)

    elif type(value) is list:
        for val in value:
            if hasattr(val, 'items'):
                fill_item(item, val)
            elif _listlike(val):
                fill_item(item, val)
            else:
                child = QTreeWidgetItem()
                item.addChild(child)
                child.setExpanded(False)
                child.setText(0, _short_repr(val))
    else:
        child = QTreeWidgetItem()
        child.setText(0, _short_repr(value))
        item.addChild(child)
Пример #33
0
 def new_item(parent, text, val=None):
     child = QTreeWidgetItem([text])
     fill_item(child, val)
     parent.addChild(child)
     child.setExpanded(True)
    def populate_tree(self):
        """Create each item (and associated data) in the tree"""
        if not self.stats:
            warn_item = QTreeWidgetItem(self)
            warn_item.setData(
                0, Qt.DisplayRole,
                _('No timings to display. '
                  'Did you forget to add @profile decorators ?')
                .format(url=WEBSITE_URL))
            warn_item.setFirstColumnSpanned(True)
            warn_item.setTextAlignment(0, Qt.AlignCenter)
            font = warn_item.font(0)
            font.setStyle(QFont.StyleItalic)
            warn_item.setFont(0, font)
            return

        try:
            monospace_font = self.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            monospace_font = QFont("Courier New")
            monospace_font.setPointSize(10)

        for func_info, func_data in self.stats.items():
            # Function name and position
            filename, start_line_no, func_name = func_info
            func_stats, func_total_time = func_data
            func_item = QTreeWidgetItem(self)
            func_item.setData(
                0, Qt.DisplayRole,
                _('{func_name} ({time_ms:.3f}ms) in file "{filename}", '
                  'line {line_no}').format(
                    filename=filename,
                    line_no=start_line_no,
                    func_name=func_name,
                    time_ms=func_total_time * 1e3))
            func_item.setFirstColumnSpanned(True)
            func_item.setData(COL_POS, Qt.UserRole,
                              (osp.normpath(filename), start_line_no))

            # For sorting by time
            func_item.setData(COL_TIME, Qt.DisplayRole, func_total_time * 1e3)
            func_item.setData(COL_PERCENT, Qt.DisplayRole,
                              func_total_time * 1e3)

            if self.parent().use_colors:
                # Choose deteministic unique color for the function
                md5 = hashlib.md5((filename + func_name).encode("utf8")).hexdigest()
                hue = (int(md5[:2], 16) - 68) % 360  # avoid blue (unreadable)
                func_color = QColor.fromHsv(hue, 200, 255)
            else:
                # Red color only
                func_color = QColor.fromRgb(255, 0, 0)

            # Lines of code
            for line_info in func_stats:
                line_item = QTreeWidgetItem(func_item)
                (line_no, code_line, line_total_time, time_per_hit,
                 hits, percent) = line_info
                self.fill_item(
                    line_item, filename, line_no, code_line,
                    line_total_time, percent, time_per_hit, hits)

                # Color background
                if line_total_time is not None:
                    alpha = percent
                    color = QColor(func_color)
                    color.setAlphaF(alpha)  # Returns None
                    color = QBrush(color)
                    for col in range(self.columnCount()):
                        line_item.setBackground(col, color)
                else:

                    for col in range(self.columnCount()):
                        line_item.setForeground(col, CODE_NOT_RUN_COLOR)

                # Monospace font for code
                line_item.setFont(COL_LINE, monospace_font)
Пример #35
0
    def refresh(self):
        title = _("Results for ") + self.filename
        self.set_title(title)
        self.clear()
        self.data = {}

        # Populating tree
        results = (
            (_("Convention"), ima.icon("convention"), self.results["C:"]),
            (_("Refactor"), ima.icon("refactor"), self.results["R:"]),
            (_("Warning"), ima.icon("warning"), self.results["W:"]),
            (_("Error"), ima.icon("error"), self.results["E:"]),
        )
        for title, icon, messages in results:
            title += " (%d message%s)" % (len(messages),
                                          "s" if len(messages) > 1 else "")
            title_item = QTreeWidgetItem(self, [title], QTreeWidgetItem.Type)
            title_item.setIcon(0, icon)
            if not messages:
                title_item.setDisabled(True)

            modules = {}
            for message_data in messages:
                # If message data is legacy version without message_name
                if len(message_data) == 4:
                    message_data = tuple(list(message_data) + [None])

                module, lineno, message, msg_id, message_name = message_data

                basename = osp.splitext(osp.basename(self.filename))[0]
                if not module.startswith(basename):
                    # Pylint bug
                    i_base = module.find(basename)
                    module = module[i_base:]

                dirname = osp.dirname(self.filename)
                if module.startswith(".") or module == basename:
                    modname = osp.join(dirname, module)
                else:
                    modname = osp.join(dirname, *module.split("."))

                if osp.isdir(modname):
                    modname = osp.join(modname, "__init__")

                for ext in (".py", ".pyw"):
                    if osp.isfile(modname + ext):
                        modname = modname + ext
                        break

                if osp.isdir(self.filename):
                    parent = modules.get(modname)
                    if parent is None:
                        item = QTreeWidgetItem(title_item, [module],
                                               QTreeWidgetItem.Type)
                        item.setIcon(0, ima.icon("python"))
                        modules[modname] = item
                        parent = item
                else:
                    parent = title_item

                if len(msg_id) > 1:
                    if not message_name:
                        message_string = "{msg_id} "
                    else:
                        message_string = "{msg_id} ({message_name}) "

                message_string += "line {lineno}: {message}"
                message_string = message_string.format(
                    msg_id=msg_id,
                    message_name=message_name,
                    lineno=lineno,
                    message=message)
                msg_item = QTreeWidgetItem(parent, [message_string],
                                           QTreeWidgetItem.Type)
                msg_item.setIcon(0, ima.icon("arrow"))
                self.data[id(msg_item)] = (modname, lineno)
Пример #36
0
 def __init__(self, parent, lineno, colno, match):
     self.lineno = lineno
     self.colno = colno
     self.match = match
     QTreeWidgetItem.__init__(self, parent, [self.__repr__()],
                              QTreeWidgetItem.Type)
Пример #37
0
    def refresh(self):
        title = _('Results for ')+self.filename
        self.set_title(title)
        self.clear()
        self.data = {}
        # Populating tree
        results = ((_('Convention'),
                   ima.icon('convention'), self.results['C:']),
                   (_('Refactor'),
                   ima.icon('refactor'), self.results['R:']),
                   (_('Warning'),
                   ima.icon('warning'), self.results['W:']),
                   (_('Error'),
                   ima.icon('error'), self.results['E:']))
        for title, icon, messages in results:
            title += ' (%d message%s)' % (len(messages),
                                          's' if len(messages) > 1 else '')
            title_item = QTreeWidgetItem(self, [title], QTreeWidgetItem.Type)
            title_item.setIcon(0, icon)
            if not messages:
                title_item.setDisabled(True)
            modules = {}
            for message_data in messages:
                # If message data is legacy version without message_name
                if len(message_data) == 4:
                    message_data = tuple(list(message_data) + [None])

                module, lineno, message, msg_id, message_name = message_data

                basename = osp.splitext(osp.basename(self.filename))[0]
                if not module.startswith(basename):
                    # Pylint bug
                    i_base = module.find(basename)
                    module = module[i_base:]
                dirname = osp.dirname(self.filename)
                if module.startswith('.') or module == basename:
                    modname = osp.join(dirname, module)
                else:
                    modname = osp.join(dirname, *module.split('.'))
                if osp.isdir(modname):
                    modname = osp.join(modname, '__init__')
                for ext in ('.py', '.pyw'):
                    if osp.isfile(modname+ext):
                        modname = modname + ext
                        break
                if osp.isdir(self.filename):
                    parent = modules.get(modname)
                    if parent is None:
                        item = QTreeWidgetItem(title_item, [module],
                                               QTreeWidgetItem.Type)
                        item.setIcon(0, ima.icon('python'))
                        modules[modname] = item
                        parent = item
                else:
                    parent = title_item
                if len(msg_id) > 1:
                    if not message_name:
                        message_string = "{msg_id} "
                    else:
                        message_string = "{msg_id} ({message_name}) "

                message_string += "line {lineno}: {message}"

                message_string = message_string.format(
                    msg_id=msg_id, message_name=message_name,
                    lineno=lineno, message=message)
                msg_item = QTreeWidgetItem(
                    parent, [message_string], QTreeWidgetItem.Type)
                msg_item.setIcon(0, ima.icon('arrow'))
                self.data[id(msg_item)] = (modname, lineno)
Пример #38
0
    def update_dependencies(self, dependencies):
        self.clear()
        headers = (_("Module"), _(" Required "),
                   _(" Installed "), _("Provided features"))
        self.setHeaderLabels(headers)
        mandatory_item = QTreeWidgetItem(["Mandatory"])
        font = mandatory_item.font(0)
        font.setBold(True)
        mandatory_item.setFont(0, font)
        optional_item = QTreeWidgetItem(["Optional"])
        optional_item.setFont(0, font)
        self.addTopLevelItems([mandatory_item, optional_item])

        for dependency in dependencies:
            item = QTreeWidgetItem([dependency.modname,
                                    dependency.required_version,
                                    dependency.installed_version,
                                    dependency.features])
            if dependency.check():
                item.setIcon(0, ima.icon('dependency_ok'))
            elif dependency.optional:
                item.setIcon(0, ima.icon('dependency_warning'))
                item.setForeground(2, QColor('#ff6a00'))
            else:
                item.setIcon(0, ima.icon('dependency_error'))
                item.setForeground(2, QColor(Qt.darkRed))
            if dependency.optional:
                optional_item.addChild(item)
            else:
                mandatory_item.addChild(item)
        self.expandAll()
Пример #39
0
    def __init__(self, opts):
        super(VCPChooser, self).__init__()
        uic.loadUi(os.path.join(CHOOSER_DIR, 'vcp_chooser.ui'), self)

        self.setAttribute(Qt.WA_DeleteOnClose, True)

        self.opts = opts
        self._vcp_data = {}

        self.selection = self.vcpTreeView.selectionModel()

        # example VCP section
        category = QTreeWidgetItem(self.vcpTreeView)
        category.setText(0, 'Example VCPs')
        category.setFlags(Qt.ItemIsEnabled)

        # add example VCPs to the treeview
        for entry_point in iter_entry_points(group='qtpyvcp.example_vcp'):
            child = QTreeWidgetItem(category)
            child.setText(0, self.get_vcp_data(entry_point))

        # test VCP section
        category = QTreeWidgetItem(self.vcpTreeView)
        category.setText(0, 'Video Test VCPs')
        category.setFlags(Qt.ItemIsEnabled)

        # add example VCPs to the treeview
        for entry_point in iter_entry_points(group='qtpyvcp.test_vcp'):
            child = QTreeWidgetItem(category)
            child.setText(0, self.get_vcp_data(entry_point))

        # installed VCP section
        category = QTreeWidgetItem(self.vcpTreeView)
        category.setText(0, 'Installed VCPs')
        category.setFlags(Qt.ItemIsEnabled)
        category.setHidden(True)

        # add installed VCPs to the treeview
        for entry_point in iter_entry_points(group='qtpyvcp.vcp'):
            child = QTreeWidgetItem(category)
            child.setText(0, self.get_vcp_data(entry_point))
            category.setHidden(False)

        if os.path.exists(CUSTOM_VCP_DIR):
            category = QTreeWidgetItem(self.vcpTreeView)
            category.setText(0, 'Custom VCPs')
            category.setFlags(Qt.ItemIsEnabled)
            for dir_name in os.listdir(CUSTOM_VCP_DIR):
                if not os.path.isdir(os.path.join(CUSTOM_VCP_DIR, dir_name)):
                    continue
                child = QTreeWidgetItem(category)
                child.setText(0, dir_name)

        self.vcpTreeView.expandAll()
        self.vcpTreeView.activated.connect(self.on_launchVCPButton_clicked)
        self.selection.selectionChanged.connect(self.on_selection_changed)
Пример #40
0
    def setup_ui(self):
        self.nodes: Dict[str, 'QTreeWidgetItem'] = {}
        self.setColumnCount(3)
        header_item = QTreeWidgetItem()
        header_item.setText(0, self.tr('Name'))
        self.setColumnWidth(0, 10 * 10)
        header_item.setText(1, self.tr('Size'))
        self.setColumnWidth(1, 10 * 10)
        header_item.setText(2, self.tr('Value'))
        header_item.setTextAlignment(0, Qt.AlignCenter)
        header_item.setTextAlignment(1, Qt.AlignCenter)
        header_item.setTextAlignment(2, Qt.AlignCenter)
        self.setHeaderItem(header_item)
        self.auto_expand = False

        self.itemClicked.connect(self.on_item_clicked)
        self.itemDoubleClicked.connect(self.on_item_double_clicked)
        self.customContextMenuRequested.connect(self.on_right_clicked)
        self.setContextMenuPolicy(Qt.CustomContextMenu)

        self.context_menu = QMenu()
        show_action = self.context_menu.addAction(self.tr('View'))
        save_action = self.context_menu.addAction(self.tr('Save as '))
        cancel_action = self.context_menu.addAction(self.tr('Undo'))
        redo_action = self.context_menu.addAction(self.tr('Redo'))
        delete_action = self.context_menu.addAction(self.tr('Delete'))
        show_action.triggered.connect(self.on_show_data_by_context_menu)
Пример #41
0
    def add_layer_item(self, layer, unique=True, *args, **kwargs):
        """
        Adds a `Layer` object to the loaded layer list widget.

        Parameters
        ----------
        layer : specviz.core.data.Spectrum1DRefLayer
            The `Layer` object to add to the list widget.
        """
        # Make sure there is only one item per layer object
        if unique:
            if self.get_layer_item(layer) is not None:
                return

        new_item = QTreeWidgetItem(
            self.get_layer_item(layer._parent)
            or self.contents.tree_widget_layer_list)
        new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable
                          | Qt.ItemIsEditable)
        new_item.setText(0, layer.name)
        new_item.setData(0, Qt.UserRole, layer)
        new_item.setCheckState(0, Qt.Checked)

        self.contents.tree_widget_layer_list.setCurrentItem(new_item)
Пример #42
0
 def on_item_double_clicked(self, item: QTreeWidgetItem, col: int) -> None:
     """
     双击条目的事件,触发数据显示。
     """
     if col == 0 and item.text(0) in self.nodes.keys():
         self.show_data(item.text(0))
Пример #43
0
 def __init__(self, parent=None):
     QTreeWidgetItem.__init__(self, parent)
Пример #44
0
    def refresh(self):
        """
        Refreshing search results panel
        """
        title = "'%s' - " % self.search_text
        if self.results is None:
            text = _('Search canceled')
        else:
            nb_files = len(self.results)
            if nb_files == 0:
                text = _('String not found')
            else:
                text_matches = _('matches in')
                text_files = _('file')
                if nb_files > 1:
                    text_files += 's'
                text = "%d %s %d %s" % (self.nb, text_matches, nb_files,
                                        text_files)
        if self.error_flag:
            text += ' (' + self.error_flag + ')'
        elif self.results is not None and not self.completed:
            text += ' (' + _('interrupted') + ')'
        self.set_title(title + text)
        self.clear()
        self.data = {}

        if not self.results:  # First search interrupted *or* No result
            return

        # Directory set
        dir_set = set()
        for filename in sorted(self.results.keys()):
            dirname = osp.abspath(osp.dirname(filename))
            dir_set.add(dirname)

        # Root path
        root_path_list = None
        _common = get_common_path(list(dir_set))
        if _common is not None:
            root_path_list = [_common]
        else:
            _common = get_common_path(self.pathlist)
            if _common is not None:
                root_path_list = [_common]
            else:
                root_path_list = self.pathlist
        if not root_path_list:
            return
        for _root_path in root_path_list:
            dir_set.add(_root_path)
        # Populating tree: directories
        def create_dir_item(dirname, parent):
            if dirname not in root_path_list:
                displayed_name = osp.basename(dirname)
            else:
                displayed_name = dirname
            item = QTreeWidgetItem(parent, [displayed_name],
                                   QTreeWidgetItem.Type)
            item.setIcon(0, ima.icon('DirClosedIcon'))
            return item

        dirs = {}
        for dirname in sorted(list(dir_set)):
            if dirname in root_path_list:
                parent = self
            else:
                parent_dirname = abspardir(dirname)
                parent = dirs.get(parent_dirname)
                if parent is None:
                    # This is related to directories which contain found
                    # results only in some of their children directories
                    if osp.commonprefix([dirname] + root_path_list):
                        # create new root path
                        pass
                    items_to_create = []
                    while dirs.get(parent_dirname) is None:
                        items_to_create.append(parent_dirname)
                        parent_dirname = abspardir(parent_dirname)
                    items_to_create.reverse()
                    for item_dir in items_to_create:
                        item_parent = dirs[abspardir(item_dir)]
                        dirs[item_dir] = create_dir_item(item_dir, item_parent)
                    parent_dirname = abspardir(dirname)
                    parent = dirs[parent_dirname]
            dirs[dirname] = create_dir_item(dirname, parent)
        self.root_items = [dirs[_root_path] for _root_path in root_path_list]
        # Populating tree: files
        for filename in sorted(self.results.keys()):
            parent_item = dirs[osp.dirname(filename)]
            file_item = QTreeWidgetItem(parent_item, [osp.basename(filename)],
                                        QTreeWidgetItem.Type)
            file_item.setIcon(0, get_filetype_icon(filename))
            colno_dict = {}
            fname_res = []
            for lineno, colno, line in self.results[filename]:
                if lineno not in colno_dict:
                    fname_res.append((lineno, colno, line))
                colno_dict[lineno] = colno_dict.get(lineno, []) + [str(colno)]
            for lineno, colno, line in fname_res:
                colno_str = ",".join(colno_dict[lineno])
                item = QTreeWidgetItem(
                    file_item,
                    ["%d (%s): %s" % (lineno, colno_str, line.rstrip())],
                    QTreeWidgetItem.Type)
                item.setIcon(0, ima.icon('arrow'))
                self.data[id(item)] = (filename, lineno)
        # Removing empty directories
        top_level_items = [
            self.topLevelItem(index)
            for index in range(self.topLevelItemCount())
        ]
        for item in top_level_items:
            if not item.childCount():
                self.takeTopLevelItem(self.indexOfTopLevelItem(item))
Пример #45
0
 def __init__(self, parent=None):
     QTreeWidgetItem.__init__(self, parent)
Пример #46
0
 def __init__(self, path, treewidget):
     QTreeWidgetItem.__init__(self, treewidget, QTreeWidgetItem.Type)
     self.path = path
     self.setIcon(0, ima.icon('python'))
     self.setToolTip(0, path)
     set_item_user_text(self, path)
Пример #47
0
 def refresh(self):
     title = _('Results for ')+self.filename
     self.set_title(title)
     self.clear()
     self.data = {}
     # Populating tree
     results = ((_('Convention'),
                ima.icon('convention'), self.results['C:']),
                (_('Refactor'),
                ima.icon('refactor'), self.results['R:']),
                (_('Warning'),
                ima.icon('warning'), self.results['W:']),
                (_('Error'),
                ima.icon('error'), self.results['E:']))
     for title, icon, messages in results:
         title += ' (%d message%s)' % (len(messages),
                                       's' if len(messages)>1 else '')
         title_item = QTreeWidgetItem(self, [title], QTreeWidgetItem.Type)
         title_item.setIcon(0, icon)
         if not messages:
             title_item.setDisabled(True)
         modules = {}
         for module, lineno, message, msg_id in messages:
             basename = osp.splitext(osp.basename(self.filename))[0]
             if not module.startswith(basename):
                 # Pylint bug
                 i_base = module.find(basename)
                 module = module[i_base:]
             dirname = osp.dirname(self.filename)
             if module.startswith('.') or module == basename:
                 modname = osp.join(dirname, module)
             else:
                 modname = osp.join(dirname, *module.split('.'))
             if osp.isdir(modname):
                 modname = osp.join(modname, '__init__')
             for ext in ('.py', '.pyw'):
                 if osp.isfile(modname+ext):
                     modname = modname + ext
                     break
             if osp.isdir(self.filename):
                 parent = modules.get(modname)
                 if parent is None:
                     item = QTreeWidgetItem(title_item, [module],
                                            QTreeWidgetItem.Type)
                     item.setIcon(0, ima.icon('python'))
                     modules[modname] = item
                     parent = item
             else:
                 parent = title_item
             if len(msg_id) > 1:
                 text = "[%s] %d : %s" % (msg_id, lineno, message)
             else:
                 text = "%d : %s" % (lineno, message)
             msg_item = QTreeWidgetItem(parent, [text], QTreeWidgetItem.Type)
             msg_item.setIcon(0, ima.icon('arrow'))
             self.data[id(msg_item)] = (modname, lineno)
Пример #48
0
    def populate_tree(self):
        """Create each item (and associated data) in the tree"""
        if not self.stats:
            warn_item = QTreeWidgetItem(self)
            warn_item.setData(
                0, Qt.DisplayRole,
                _('No timings to display. '
                  'Did you forget to add @profile decorators ?')
                .format(url=WEBSITE_URL))
            warn_item.setFirstColumnSpanned(True)
            warn_item.setTextAlignment(0, Qt.AlignCenter)
            font = warn_item.font(0)
            font.setStyle(QFont.StyleItalic)
            warn_item.setFont(0, font)
            return

        try:
            monospace_font = self.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            monospace_font = QFont("Courier New")
            monospace_font.setPointSize(10)

        for func_info, func_data in self.stats.items():
            # Function name and position
            filename, start_line_no, func_name = func_info
            func_stats, func_total_time = func_data
            func_item = QTreeWidgetItem(self)
            func_item.setData(
                0, Qt.DisplayRole,
                _('{func_name} ({time_ms:.3f}ms) in file "{filename}", '
                  'line {line_no}').format(
                    filename=filename,
                    line_no=start_line_no,
                    func_name=func_name,
                    time_ms=func_total_time * 1e3))
            func_item.setFirstColumnSpanned(True)
            func_item.setData(COL_POS, Qt.UserRole,
                              (osp.normpath(filename), start_line_no))

            # For sorting by time
            func_item.setData(COL_TIME, Qt.DisplayRole, func_total_time * 1e3)
            func_item.setData(COL_PERCENT, Qt.DisplayRole,
                              func_total_time * 1e3)

            if self.parent().use_colors:
                # Choose deteministic unique color for the function
                md5 = hashlib.md5((filename + func_name).encode("utf8")).hexdigest()
                hue = (int(md5[:2], 16) - 68) % 360  # avoid blue (unreadable)
                func_color = QColor.fromHsv(hue, 200, 255)
            else:
                # Red color only
                func_color = QColor.fromRgb(255, 0, 0)

            # Lines of code
            for line_info in func_stats:
                line_item = QTreeWidgetItem(func_item)
                (line_no, code_line, line_total_time, time_per_hit,
                 hits, percent) = line_info
                self.fill_item(
                    line_item, filename, line_no, code_line,
                    line_total_time, percent, time_per_hit, hits)

                # Color background
                if line_total_time is not None:
                    alpha = percent
                    color = QColor(func_color)
                    color.setAlphaF(alpha)  # Returns None
                    color = QBrush(color)
                    for col in range(self.columnCount()):
                        line_item.setBackground(col, color)
                else:

                    for col in range(self.columnCount()):
                        line_item.setForeground(col, CODE_NOT_RUN_COLOR)

                # Monospace font for code
                line_item.setFont(COL_LINE, monospace_font)
Пример #49
0
    def set_data_view(self, data_dic: Dict[str, object],
                      root: 'QTreeWidgetItem'):
        """
        递归方式显示json。
        显示的时候要注意层级。
        :param data_dic:
        :param root:
        :return:
        """
        for k in data_dic.keys():
            print(k)
            if type(data_dic[k]) == dict:
                child = QTreeWidgetItem(root)
                child.setText(0, repr(k))
                self.set_data_view(data_dic[k], child)
            elif not isinstance(data_dic[k], str):
                print(k)
                d = {
                    attr_name: str(getattr(data_dic[k], attr_name))
                    for attr_name in dir(data_dic[k])
                }

                child = QTreeWidgetItem(root)
                child.setText(0, repr(k))
                self.set_data_view(d, child)
            else:
                child = QTreeWidgetItem(root)
                child.setText(0, repr(k))
                child.setText(1, str(self.get_size(data_dic[k])))
                child.setText(2, data_dic[k])
Пример #50
0
    def refresh(self):
        """
        Refreshing search results panel
        """
        title = "'%s' - " % self.search_text
        if self.results is None:
            text = _('Search canceled')
        else:
            nb_files = len(self.results)
            if nb_files == 0:
                text = _('String not found')
            else:
                text_matches = _('matches in')
                text_files = _('file')
                if nb_files > 1:
                    text_files += 's'
                text = "%d %s %d %s" % (self.nb, text_matches,
                                        nb_files, text_files)
        if self.error_flag:
            text += ' (' + self.error_flag + ')'
        elif self.results is not None and not self.completed:
            text += ' (' + _('interrupted') + ')'
        self.set_title(title+text)
        self.clear()
        self.data = {}
        
        if not self.results: # First search interrupted *or* No result
            return

        # Directory set
        dir_set = set()
        for filename in sorted(self.results.keys()):
            dirname = osp.abspath(osp.dirname(filename))
            dir_set.add(dirname)
                
        # Root path
        root_path_list = None
        _common = get_common_path(list(dir_set))
        if _common is not None:
            root_path_list = [_common]
        else:
            _common = get_common_path(self.pathlist)
            if _common is not None:
                root_path_list = [_common]
            else:
                root_path_list = self.pathlist
        if not root_path_list:
            return
        for _root_path in root_path_list:
            dir_set.add(_root_path)
        # Populating tree: directories
        def create_dir_item(dirname, parent):
            if dirname not in root_path_list:
                displayed_name = osp.basename(dirname)
            else:
                displayed_name = dirname
            item = QTreeWidgetItem(parent, [displayed_name],
                                   QTreeWidgetItem.Type)
            item.setIcon(0, ima.icon('DirClosedIcon'))
            return item
        dirs = {}
        for dirname in sorted(list(dir_set)):
            if dirname in root_path_list:
                parent = self
            else:
                parent_dirname = abspardir(dirname)
                parent = dirs.get(parent_dirname)
                if parent is None:
                    # This is related to directories which contain found
                    # results only in some of their children directories
                    if osp.commonprefix([dirname]+root_path_list):
                        # create new root path
                        pass
                    items_to_create = []
                    while dirs.get(parent_dirname) is None:
                        items_to_create.append(parent_dirname)
                        parent_dirname = abspardir(parent_dirname)
                    items_to_create.reverse()
                    for item_dir in items_to_create:
                        item_parent = dirs[abspardir(item_dir)]
                        dirs[item_dir] = create_dir_item(item_dir, item_parent)
                    parent_dirname = abspardir(dirname)
                    parent = dirs[parent_dirname]
            dirs[dirname] = create_dir_item(dirname, parent)
        self.root_items = [dirs[_root_path] for _root_path in root_path_list]
        # Populating tree: files
        for filename in sorted(self.results.keys()):
            parent_item = dirs[osp.dirname(filename)]
            file_item = QTreeWidgetItem(parent_item, [osp.basename(filename)],
                                        QTreeWidgetItem.Type)
            file_item.setIcon(0, get_filetype_icon(filename))
            colno_dict = {}
            fname_res = []
            for lineno, colno, line in self.results[filename]:
                if lineno not in colno_dict:
                    fname_res.append((lineno, colno, line))
                colno_dict[lineno] = colno_dict.get(lineno, [])+[str(colno)]
            for lineno, colno, line in fname_res:
                colno_str = ",".join(colno_dict[lineno])
                item = QTreeWidgetItem(file_item,
                           ["%d (%s): %s" % (lineno, colno_str, line.rstrip())],
                           QTreeWidgetItem.Type)
                item.setIcon(0, ima.icon('arrow'))
                self.data[id(item)] = (filename, lineno)
        # Removing empty directories
        top_level_items = [self.topLevelItem(index)
                           for index in range(self.topLevelItemCount())]
        for item in top_level_items:
            if not item.childCount():
                self.takeTopLevelItem(self.indexOfTopLevelItem(item))