예제 #1
0
 def __grounded(self) -> None:
     """Grounded combinations."""
     current_item = self.collection_list.currentItem()
     self.collections_grounded.clear()
     self.grounded_list.clear()
     g = self.collections[self.collection_list.row(current_item)]
     item = QListWidgetItem("Released")
     icon = graph2icon(g,
                       self.grounded_list.iconSize().width(),
                       self.graph_link_as_node.isChecked(),
                       self.graph_show_label.isChecked(),
                       self.prefer.monochrome_option,
                       pos=self.ground_engine)
     item.setIcon(icon)
     self.collections_grounded.append(g)
     self.grounded_list.addItem(item)
     for node, graph_ in labeled_enumerate(g):
         item = QListWidgetItem(f"link_{node}")
         icon = graph2icon(g,
                           self.grounded_list.iconSize().width(),
                           self.graph_link_as_node.isChecked(),
                           self.graph_show_label.isChecked(),
                           self.prefer.monochrome_option,
                           except_node=node,
                           pos=self.ground_engine)
         item.setIcon(icon)
         self.collections_grounded.append(graph_)
         self.grounded_list.addItem(item)
예제 #2
0
    def __init__(self, settings: BaseSettings, parent=None):
        super().__init__(parent)
        self.settings = settings
        self.file_list = QListWidget()
        self.file_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.cancel_btn = QPushButton("Cancel", clicked=self.reject)
        self.load_btn = QPushButton("Load", clicked=self.accept)

        for name_list, method in settings.get_last_files_multiple():
            entry = f"{name_list[0]} {method}"
            item = QListWidgetItem(entry, self.file_list)
            item.setData(Qt.UserRole, (name_list, method))

        last_set = {(tuple(x), y)
                    for x, y in settings.get_last_files_multiple()}
        for name_list, method in settings.get_last_files():
            if (tuple(name_list), method) in last_set:
                continue
            entry = f"{name_list[0]} {method}"
            item = QListWidgetItem(entry, self.file_list)
            item.setData(Qt.UserRole, (name_list, method))

        layout = QGridLayout()
        layout.addWidget(QLabel("Select files"))
        layout.addWidget(self.file_list, 1, 0, 1, 2)
        layout.addWidget(self.cancel_btn, 2, 0)
        layout.addWidget(self.load_btn, 2, 1)

        self.setLayout(layout)
        self.resize(
            *self.settings.get_from_profile("multiple_files_dialog_size", (
                self.size().width(), self.size().height())))
예제 #3
0
 def __set_name(self, index: int) -> None:
     """Load the parameters of the point."""
     if not len(self.vpoints) > index:
         return
     vpoint = self.vpoints[index]
     self.x_box.setValue(vpoint.x)
     self.y_box.setValue(vpoint.y)
     color_text = vpoint.color_str
     color_index = self.color_box.findText(color_text)
     if color_index > -1:
         self.color_box.setCurrentIndex(color_index)
     else:
         self.color_box.addItem(color_icon(color_text), color_text)
         self.color_box.setCurrentIndex(self.color_box.count() - 1)
     self.type_box.setCurrentIndex(vpoint.type)
     self.angle_box.setValue(vpoint.angle)
     self.noSelected.clear()
     self.selected.clear()
     for linkName in vpoint.links:
         self.selected.addItem(QListWidgetItem(self.link_icon, linkName))
     for vlink in self.vlinks:
         if vlink.name in vpoint.links:
             continue
         self.noSelected.addItem(QListWidgetItem(self.link_icon,
                                                 vlink.name))
예제 #4
0
 def __set_name(self, index: int) -> None:
     """Load the parameters of the link."""
     if not self.name_box.isEnabled():
         return
     if len(self.vlinks) > index:
         vlink = self.vlinks[index]
         self.name_edit.setText(vlink.name)
         color_text = vlink.color_str
         color_index = self.color_box.findText(color_text)
         if color_index > -1:
             self.color_box.setCurrentIndex(color_index)
         else:
             self.color_box.addItem(color_icon(color_text), color_text)
             self.color_box.setCurrentIndex(self.color_box.count() - 1)
         self.noSelected.clear()
         self.selected.clear()
         for p in vlink.points:
             self.selected.addItem(QListWidgetItem(self.icon, f'Point{p}'))
         for p in range(len(self.vpoints)):
             if p in vlink.points:
                 continue
             self.noSelected.addItem(QListWidgetItem(self.icon, f'Point{p}'))
     not_ground = index > 0
     for widget in (self.name_edit, self.color_box, self.color_pick_button):
         widget.setEnabled(not_ground)
예제 #5
0
    def _search(self, needle):

        import Levenshtein

        if not needle:
            haystack = self._haystack[:]
            if self._default:
                haystack.insert(0,
                                (self._default[0].lower(), ) + self._default)
            self._result_box.clear()
            for lower_label, label, data, on_select in haystack:
                item = QListWidgetItem(label, self._result_box)
                item.data = data
                item.on_select = on_select
                self._result_box.addItem(item)
            return
        needle = needle.lower()
        needles = needle.split()
        self._result_box.show()
        self._result_box.clear()
        results = []
        for lower_label, label, data, on_select in self._haystack:
            for subneedle in needles:
                if subneedle not in lower_label:
                    break
            else:
                results.append(
                    (Levenshtein.distance(needle, lower_label) / len(label),
                     label, data, on_select))
        for score, label, data, on_select in sorted(results,
                                                    key=lambda t: t[0]):
            item = QListWidgetItem(label, self._result_box)
            item.data = data
            item.on_select = on_select
            self._result_box.addItem(item)
예제 #6
0
    def update_list(self, filter_text):
        """
        Update the displayed list by filtering self.completion_list.

        If no items are left on the list the autocompletion should stop
        """
        self.clear()
        icons_map = {CompletionItemKind.TEXT: 'text',
                     CompletionItemKind.METHOD: 'method',
                     CompletionItemKind.FUNCTION: 'function',
                     CompletionItemKind.CONSTRUCTOR: 'constructor',
                     CompletionItemKind.FIELD: 'field',
                     CompletionItemKind.VARIABLE: 'variable',
                     CompletionItemKind.CLASS: 'class',
                     CompletionItemKind.INTERFACE: 'interface',
                     CompletionItemKind.MODULE: 'module',
                     CompletionItemKind.PROPERTY: 'property',
                     CompletionItemKind.UNIT: 'unit',
                     CompletionItemKind.VALUE: 'value',
                     CompletionItemKind.ENUM: 'enum',
                     CompletionItemKind.KEYWORD: 'keyword',
                     CompletionItemKind.SNIPPET: 'snippet',
                     CompletionItemKind.COLOR: 'color',
                     CompletionItemKind.FILE: 'filenew',
                     CompletionItemKind.REFERENCE: 'reference',
                     }

        height = self.item_height
        width = self.item_width

        for completion in self.completion_list:
            if not self.is_internal_console:
                completion_label = completion['filterText']
                icon = icons_map.get(completion['kind'], 'no_match')
                completion_data = completion['insertText']
                completion_text = self.get_html_item_representation(
                    completion_data, icon, height=height, width=width)
                item = QListWidgetItem(ima.icon(icon),
                                       completion_text)
                item.setData(Qt.UserRole, completion_data)
            else:
                completion_label = completion[0]
                completion_text = self.get_html_item_representation(
                    completion_label, '', height=height, width=width)
                item = QListWidgetItem()
                item.setData(Qt.UserRole, completion_label)
                item.setText(completion_text)

            if self.check_can_complete(
                    completion_label, filter_text):
                self.addItem(item)

        if self.count() > 0:
            self.setCurrentRow(0)
            self.scrollTo(self.currentIndex(),
                          QAbstractItemView.PositionAtTop)
        else:
            self.hide()
예제 #7
0
    def __init__(
        self,
        parent: QWidget,
        title: str,
        main_expr: str,
        storage_data: Mapping[str, str],
        input_data: Sequence[Tuple[int, int]],
        path_data: Mapping[str, _Paths],
        collection_data: Sequence[_Pairs],
        config_data: Mapping[str, Mapping[str, Any]],
        algorithm_data: Sequence[Mapping[str, Any]],
        background_path: str
    ):
        """Data come from commit."""
        super(OverviewDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setWindowTitle(f"Project: {title}")

        # Expression of storage data
        self.main_expr.setText(main_expr)
        for name, expr in storage_data.items():
            item = QListWidgetItem(f"[{name}]: {expr}")
            item.setToolTip(expr)
            self.storage_list.addItem(item)
        size = len(storage_data)
        if main_expr != "M[]":
            size += 1
        self.__set_item_text(0, size)
        # Expression of inputs variable data and Path data
        for a, b in input_data:
            self.variables_list.addItem(f"Point{a}->Point{b}")
        for name, paths in path_data.items():
            item = QListWidgetItem(name)
            item.setToolTip(", ".join(
                f'[{i}]' for i, path in enumerate(paths) if path
            ))
            self.records_list.addItem(item)
        self.__set_item_text(1, len(input_data), len(path_data))
        # Structure collections and Triangle collections
        for edges in collection_data:
            self.structures_list.addItem(str(edges))
        for name, data in config_data.items():
            item = QListWidgetItem(name)
            item.setToolTip(data['expression'])
            self.triangular_iteration_list.addItem(item)
        self.__set_item_text(2, len(collection_data), len(config_data))
        # Dimensional synthesis
        for data in algorithm_data:
            self.results_list.addItem(data['algorithm'])
        self.__set_item_text(3, len(algorithm_data))
        # Background image
        self.image_path.setText(background_path)
        self.__set_item_text(4, 1 if background_path else 0)
        self.background_preview.setPixmap(QPixmap(background_path))
예제 #8
0
    def update_list(self, filter_text):
        """
        Update the displayed list by filtering self.completion_list.

        If no items are left on the list the autocompletion should stop
        """
        self.clear()

        self.display_index = []
        height = self.item_height
        width = self.item_width

        for i, completion in enumerate(self.completion_list):
            if not self.is_internal_console:
                code_snippets_enabled = getattr(self.textedit, 'code_snippets',
                                                False)
                completion_label = completion['filterText']
                completion_text = completion['insertText']
                if not code_snippets_enabled:
                    completion_label = completion['insertText']
                icon = self.ICONS_MAP.get(completion['kind'], 'no_match')
                item = QListWidgetItem()
                item.setIcon(ima.icon(icon))
                self.set_item_text(item,
                                   completion,
                                   height=height,
                                   width=width)
                item.setData(Qt.UserRole, completion_text)
            else:
                completion_label = completion[0]
                completion_text = self.get_html_item_representation(
                    completion_label,
                    '',
                    icon_provider=None,
                    size=0,
                    height=height,
                    width=width)
                item = QListWidgetItem()
                item.setData(Qt.UserRole, completion_label)
                item.setText(completion_text)

            if self.check_can_complete(completion_label, filter_text):
                self.addItem(item)
                self.display_index.append(i)

        if self.count() > 0:
            self.setCurrentRow(0)
            self.scrollTo(self.currentIndex(), QAbstractItemView.PositionAtTop)
        else:
            self.hide()
예제 #9
0
    def update_info(self):
        res = self.calculation_manager.get_results()
        for el in res.errors:
            if el[0]:
                QListWidgetItem(el[0], self.logs)
            ExceptionListItem(el[1], self.logs)
            if (state_store.report_errors and parsed_version.is_devrelease
                    and not isinstance(el[1][0], SegmentationLimitException)
                    and isinstance(el[1][1], tuple)):
                with sentry_sdk.push_scope() as scope:
                    scope.set_tag("auto_report", "true")
                    sentry_sdk.capture_event(el[1][1][0])
        self.whole_progress.setValue(res.global_counter)
        working_search = True
        for uuid, progress in res.jobs_status.items():
            calculation = self.calculation_manager.calculation_dict[uuid]
            total = len(calculation.file_list)
            if uuid in self.progress_item_dict:
                item = self.progress_item_dict[uuid]
                item.update_count(progress)
            else:
                item = CalculationProcessItem(calculation, self.task_count,
                                              progress)
                self.task_count += 1
                self.task_que.appendRow(item)
                self.progress_item_dict[uuid] = item

            if working_search and progress != total:
                self.part_progress.setMaximum(total)
                self.part_progress.setValue(progress)
                working_search = False
        if not self.calculation_manager.has_work:
            self.part_progress.setValue(self.part_progress.maximum())
            self.preview_timer.stop()
            logging.info("Progress stop")
예제 #10
0
파일: list.py 프로젝트: fisher2017/Anaconda
    def setup(self):
        """
        Initial setup for populating items if any.
        """
        # TODO: Check against regex and raise error accordingly!
        new_items = []
        for text in self.items_text:
            if self.normalize:
                text = text.lower()
            new_items.append(text)

        self.items_text = new_items

        if not self.duplicates:
            if len(set(self.items_text)) != len(self.items_text):
                raise Exception('The list cannot contains duplicates.')

        for item in self.items_text:
            item = QListWidgetItem(item)
            item.extra_data = None
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            self.add(item)
            item.setSizeHint(QSize(item.sizeHint().width(), self._height()))

        self.refresh()
예제 #11
0
    def load_project_list(self):
        """
        Populate the project selection list.
        """
        self.list_projects.clear()

        for path in self.projects_dict:
            project = self.projects_dict[path]
            name = project.name

            item = QListWidgetItem(name)

            if getattr(project, 'icon', None):
                icon = self.api.load_icon(path, project)
            else:
                icon = qta.icon('fa.cog')

            item.setIcon(icon)
            item.project = project
            item.path = path
            if project.commands:
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
                              | Qt.ItemIsEnabled)
                if project.is_app:
                    item.setCheckState(Qt.Checked)
                else:
                    item.setCheckState(Qt.Unchecked)

            self.list_projects.addItem(item)
            self.toogle_dev_tools(visible=self.dev_tool_visible)

        for i in range(self.list_projects.count()):
            item = self.list_projects.item(i)
            item.setSizeHint(QSize(item.sizeHint().width(), self._height()))
예제 #12
0
    def addItem(self,
                project_info: ProjectInfo,
                plugin_name=None,
                enabled=True):
        # don't add duplicates
        if (self.findItems(project_info.name, Qt.MatchFixedString)
                and not plugin_name):
            return

        # including summary here for sake of filtering below.
        searchable_text = project_info.name + " " + project_info.summary
        item = QListWidgetItem(searchable_text, parent=self)
        item.version = project_info.version
        super().addItem(item)

        widg = PluginListItem(
            *project_info,
            parent=self,
            plugin_name=plugin_name,
            enabled=enabled,
        )
        method = getattr(self.installer,
                         'uninstall' if plugin_name else 'install')
        widg.action_button.clicked.connect(lambda: method([project_info.name]))

        item.setSizeHint(widg.sizeHint())
        self.setItemWidget(item, widg)
예제 #13
0
 def update_info(self):
     res = self.calculation_manager.get_results()
     for el in res.errors:
         if el[0]:
             QListWidgetItem(el[0], self.logs)
         ExceptionListItem(el[1], self.logs)
         if (state_store.report_errors and parsed_version.is_devrelease
                 and not isinstance(el[1][0], SegmentationLimitException)
                 and isinstance(el[1][1], tuple)):
             with sentry_sdk.push_scope() as scope:
                 scope.set_tag("auto_report", "true")
                 sentry_sdk.capture_event(el[1][1][0])
     self.whole_progress.setValue(res.global_counter)
     working_search = True
     for i, (progress, total) in enumerate(res.jobs_status):
         if working_search and progress != total:
             self.part_progress.setMaximum(total)
             self.part_progress.setValue(progress)
             working_search = False
         if i < self.task_que.count():
             item = self.task_que.item(i)
             item.setText("Task {} ({}/{})".format(i, progress, total))
         else:
             self.task_que.addItem("Task {} ({}/{})".format(
                 i, progress, total))
     if not self.calculation_manager.has_work:
         print(
             "[ProgressView.update_info]",
             self.calculation_manager.has_work,
             self.calculation_manager.batch_manager.has_work,
             self.calculation_manager.writer.writing_finished(),
         )
         self.part_progress.setValue(self.part_progress.maximum())
         self.preview_timer.stop()
         logging.info("Progress stop")
예제 #14
0
 def scan_config_devices_update_list_view(self):
     """
     Scans for saved devices
     :return:
     """
     self.devices_view.clear()
     paired_devices = self.config['device']
     for i in paired_devices:
         if paired_devices[i].get('wifi'):
             icon = ':/icons/icons/portrait_mobile_disconnect.svg'
             devices_view_list_item = QListWidgetItem(
                 QIcon(icon), "{device}\n{mode}\n{status}".format(
                     device=paired_devices[i].get('model'),
                     mode=i,
                     status='Disconnected'))
             __sha_shift = self.config.get('sha_shift', 5)
             __sha = hashlib.sha256(
                 str(i).encode()).hexdigest()[__sha_shift:__sha_shift + 6]
             devices_view_list_item.setToolTip(
                 "<span style='color: #{color}'>Device</snap>: <b>{d}</b>\n"
                 "Status: {s}".format(
                     d=i,
                     s="Disconnected. Right click 'ping' to attempt "
                     "reconnect",
                     color=__sha))
             devices_view_list_item.setFont(QFont('Noto Sans', 8))
             self.devices_view.addItem(devices_view_list_item)
     return paired_devices
예제 #15
0
    def __init__(self, text, packages=(), parent=None):
        """Accept actions for pacakge manager."""
        super(ActionsDialog, self).__init__(parent=parent)

        self.packages = packages

        self.label = QLabel(text)
        self.list = ListWidgetActionPackages(self)
        self.button_cancel = ButtonDanger('Cancel')
        self.button_accept = ButtonPrimary('Ok')

        self.setWindowTitle('Proceed with the following actions?')

        for item in packages:
            item = QListWidgetItem(item)
            self.list.addItem(item)

        # Layout
        layout_buttons = QHBoxLayout()
        layout_buttons.addStretch()
        layout_buttons.addWidget(self.button_cancel)
        layout_buttons.addWidget(SpacerHorizontal())
        layout_buttons.addWidget(self.button_accept)

        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(SpacerVertical())
        layout.addWidget(self.list)
        layout.addWidget(SpacerVertical())
        layout.addWidget(SpacerVertical())
        layout.addLayout(layout_buttons)
        self.setLayout(layout)

        self.button_accept.clicked.connect(self.accept)
        self.button_cancel.clicked.connect(self.reject)
예제 #16
0
파일: main.py 프로젝트: lnls-sirius/hla
    def _do_update(self):
        if self.sender().text() == 'Abort':
            self._update_task.terminate()
            now = Time.now().strftime('%Y/%m/%d-%H:%M:%S')
            item = QListWidgetItem(now + '  Aborted.')
            self._progress_list.addItem(item)
            self._progress_list.scrollToBottom()
            self._setup_search_button()
        else:
            if self.dt_start.dateTime() >= self.dt_stop.dateTime() or \
                    self.dt_start.dateTime() > Time.now() or \
                    self.dt_stop.dateTime() > Time.now():
                QMessageBox.warning(self, 'Ops...',
                                    'Insert a valid time interval.')
                return

            self._macreport.timestamp_start = \
                self.dt_start.dateTime().toSecsSinceEpoch()
            self._macreport.timestamp_stop = \
                self.dt_stop.dateTime().toSecsSinceEpoch()

            self._progress_list.clear()
            self._pb_showraw.setEnabled(False)
            self._pb_showpvsd.setEnabled(False)
            self._setup_search_button()

            self._update_task = UpdateTask(self._macreport)
            self._update_task.updated.connect(self._update_progress)
            self._update_task.start()
예제 #17
0
 def make_items(self, uri_file_list):
     self.clear()
     for filename, is_label in uri_file_list:
         item = QListWidgetItem(filename)
         item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
         item.setCheckState(Qt.Checked if is_label else Qt.Unchecked)
         self.addItem(item)
예제 #18
0
    def addItem(self,
                project_info: ProjectInfo,
                plugin_name=None,
                enabled=True):
        # don't add duplicates
        if self.findItems(project_info.name, Qt.MatchFixedString):
            if not plugin_name:
                return

        item = QListWidgetItem(project_info.name, parent=self)
        item.version = project_info.version
        super().addItem(item)

        widg = PluginListItem(
            *project_info,
            parent=self,
            plugin_name=plugin_name,
            enabled=enabled,
        )
        method = getattr(self.installer,
                         'uninstall' if plugin_name else 'install')
        widg.action_button.clicked.connect(lambda: method([project_info.name]))

        item.setSizeHint(widg.sizeHint())
        self.setItemWidget(item, widg)
예제 #19
0
    def submit(self):
        """Put a new command on the queue for later execution.
        """
        # put the new command on the queue
        cmd = str(self.mdi_entry_widget.text()).strip()
        row_item = QListWidgetItem()
        row_item.setText(cmd)
        row_item.setData(MDIHistory.MDQQ_ROLE, MDIHistory.MDIQ_TODO)
        row_item.setIcon(self.icon_waiting)
        if self.mdi_listorder_natural:
            self.addItem(row_item)
        else:
            self.insertItem(0, row_item)

        # Set the recently added item as the "current" item
        # if the queue is not paused this will quickly get overridden
        # to the executing item highlight mode
        self.clearSelection()
        self.setCurrentItem(row_item)

        # put the command onto the status channel mdi history
        # This always adds this item at position Zero on the channel
        STATUS.mdi_history.setValue(cmd)

        # now clear down the mdi entry text ready for new input
        self.mdi_entry_widget.clear()
예제 #20
0
    def __init__(self, vpoints: List[VPoint], vlinks: List[VLink],
                 pos: Union[int, bool], parent: QWidget):
        """Input data reference from main window.

        + Needs VPoints and VLinks information.
        + If row is false: Create action.
        """
        super(EditPointDialog, self).__init__(parent)
        self.setupUi(self)
        flags = self.windowFlags()
        self.setWindowFlags(flags & ~Qt.WindowContextHelpButtonHint)
        icon = self.windowIcon()
        self.icon = QIcon(QPixmap(":/icons/link.png"))
        self.vpoints = vpoints
        self.vlinks = vlinks
        vpoints_count = len(vpoints)
        for i, e in enumerate(color_names):
            self.color_box.insertItem(i, color_icon(e), e)
        for vlink in vlinks:
            self.no_selected.addItem(QListWidgetItem(self.icon, vlink.name))
        if pos is False:
            self.name_box.addItem(icon, f'Point{vpoints_count}')
            self.name_box.setEnabled(False)
            self.color_box.setCurrentIndex(self.color_box.findText('green'))
        else:
            for i in range(vpoints_count):
                self.name_box.insertItem(i, icon, f'Point{i}')
            self.name_box.setCurrentIndex(pos)
        self.type_box.currentIndexChanged.connect(self.__check_angle)
        self.__check_angle()
예제 #21
0
    def update_progress(self, progress):
        if not progress:
            return

        self.log.clear()

        for entry in progress:
            title, description, date, icon = entry

            entry = EntryWidget()
            entry.setTitle(title)
            entry.setDescription(description)
            entry.setDate(date)
            entry.setIcon(QIcon.fromTheme(icon), self.iconsize)

            if self.style_thresh:
                if (int(date) < self.style_thresh):
                    entry.setStyle("color: lightgreen")
                else:
                    entry.setStyle("color: lightsalmon")

            item = QListWidgetItem(self.log)
            item.setSizeHint(entry.sizeHint())

            self.log.insertItem(0, item)
            self.log.setItemWidget(item, entry)
예제 #22
0
    def _on_data_change(self, *event):

        components = getattr(type(self.state),
                             'component').get_choices(self.state)

        self.ui.list_component.clear()

        for component in components:

            if isinstance(component, ChoiceSeparator):
                item = QListWidgetItem(str(component))
                item.setFlags(item.flags() & ~Qt.ItemIsSelectable)
                item.setForeground(Qt.gray)
            else:
                item = QListWidgetItem(component.label)
                item.setCheckState(Qt.Checked)
            self.ui.list_component.addItem(item)
예제 #23
0
    def rebuild_selected_packages_list_widget(self):
        # remove all items
        self.selected_packages_list_widget.clear()

        for f in self.file_paths:
            file_item = QListWidgetItem()
            file_item.setText(f)
            self.selected_packages_list_widget.addItem(file_item)
 def update(self, files):
     self.clear()
     for i, fname in enumerate(files):
         fname = fname.encode('utf-8')
         text = os.path.basename(fname)
         icon = QIcon(FILE_ICON)
         item = QListWidgetItem(icon, text)
         item.setData(Qt.UserRole, fname)
         self.addItem(item)
예제 #25
0
 def __init__(self,
              name: str,
              widget: QListWidget,
              parent: Optional[QWidget] = None):
     super(AddInput, self).__init__(parent)
     self.setText(f"Add variable of {name}")
     self.item = QListWidgetItem(name)
     self.item.setToolTip(name)
     self.widget = widget
예제 #26
0
    def __init__(self, parent: QWidget, title: str, storage_data: Dict[str,
                                                                       str],
                 input_data: Sequence[Tuple[int, int]],
                 path_data: Dict[str, Sequence[Tuple[float, float]]],
                 collection_data: List[Tuple[Tuple[int, int], ...]],
                 config_data: Dict[str, Dict[str, Any]],
                 algorithm_data: List[Dict[str, Any]]):
        """Data come from commit."""
        super(OverviewDialog, self).__init__(parent)
        self.setupUi(self)
        flags = self.windowFlags()
        self.setWindowFlags(flags & ~Qt.WindowContextHelpButtonHint)
        self.setWindowTitle(f"Project: {title}")

        # Expression of storage data.
        for name, expr in storage_data.items():
            item = QListWidgetItem(f"[Storage] - {name}")
            item.setToolTip(expr)
            self.storage_list.addItem(item)
        self.__set_item_text(0, len(storage_data))

        # Expression of inputs variable data and Path data.
        for a, b in input_data:
            self.variables_list.addItem(f"Point{a}->Point{b}")
        for name, paths in path_data.items():
            item = QListWidgetItem(name)
            item.setToolTip(", ".join(f'[{i}]' for i, path in enumerate(paths)
                                      if path))
            self.records_list.addItem(item)
        self.__set_item_text(1, len(input_data), len(path_data))

        # Structure collections and Triangle collections.
        for edges in collection_data:
            self.structures_list.addItem(str(edges))
        for name, data in config_data.items():
            item = QListWidgetItem(name)
            item.setToolTip(data['Expression'])
            self.triangular_iteration_list.addItem(item)
        self.__set_item_text(2, len(collection_data), len(config_data))

        # Dimensional synthesis.
        for data in algorithm_data:
            self.results_list.addItem(data['Algorithm'])
        self.__set_item_text(3, len(algorithm_data))
예제 #27
0
    def addItem(
        self,
        project_info: ProjectInfo,
        installed=False,
        plugin_name=None,
        enabled=True,
        npe_version=1,
    ):
        # don't add duplicates
        if (
            self.findItems(project_info.name, Qt.MatchFixedString)
            and not plugin_name
        ):
            return

        # including summary here for sake of filtering below.
        searchable_text = project_info.name + " " + project_info.summary
        item = QListWidgetItem(searchable_text, parent=self)
        item.version = project_info.version
        super().addItem(item)
        widg = PluginListItem(
            *project_info,
            parent=self,
            plugin_name=plugin_name,
            enabled=enabled,
            installed=installed,
            npe_version=npe_version,
        )
        item.widget = widg
        item.npe_version = npe_version
        action_name = 'uninstall' if installed else 'install'
        item.setSizeHint(widg.sizeHint())
        self.setItemWidget(item, widg)

        if project_info.url:
            import webbrowser

            widg.help_button.clicked.connect(
                lambda: webbrowser.open(project_info.url)
            )
        else:
            widg.help_button.setVisible(False)

        widg.action_button.clicked.connect(
            lambda: self.handle_action(item, project_info.name, action_name)
        )
        widg.update_btn.clicked.connect(
            lambda: self.handle_action(
                item, project_info.name, "install", update=True
            )
        )
        widg.cancel_btn.clicked.connect(
            lambda: self.handle_action(item, project_info.name, "cancel")
        )
        item.setSizeHint(widg.sizeHint())
        self.setItemWidget(item, widg)
예제 #28
0
    def setup_symbol_list(self, filter_text, current_path):
        """Setup list widget content for symbol list display."""
        # Get optional symbol name
        filter_text, symbol_text = filter_text.split('@')

        # Fetch the Outline explorer data, get the icons and values
        oedata = self.get_symbol_list()
        icons = get_python_symbol_icons(oedata)

        # The list of shorten paths here is needed in order to have the same
        # point of measurement for the list widget width as in the file list
        # See issue 4648
        short_paths = shorten_paths(self.paths, self.save_status)
        symbol_list = process_python_symbol_data(oedata)
        line_fold_token = [(item[0], item[2], item[3]) for item in symbol_list]
        choices = [item[1] for item in symbol_list]
        scores = get_search_scores(symbol_text, choices, template="<b>{0}</b>")

        # Build the text that will appear on the list widget
        results = []
        lines = []
        self.filtered_symbol_lines = []
        for index, score in enumerate(scores):
            text, rich_text, score_value = score
            line, fold_level, token = line_fold_token[index]
            lines.append(text)
            if score_value != -1:
                results.append((score_value, line, text, rich_text, fold_level,
                                icons[index], token))

        template = '{0}{1}'

        for (score, line, text, rich_text, fold_level, icon,
             token) in sorted(results):
            fold_space = '&nbsp;' * (fold_level)
            line_number = line + 1
            self.filtered_symbol_lines.append(line_number)
            textline = template.format(fold_space, rich_text)
            item = QListWidgetItem(icon, textline)
            item.setSizeHint(QSize(0, 16))
            self.list.addItem(item)

        # To adjust the delegate layout for KDE themes
        self.list.files_list = False

        # Move selected item in list accordingly
        # NOTE: Doing this is causing two problems:
        # 1. It makes the cursor to auto-jump to the last selected
        #    symbol after opening or closing a different file
        # 2. It moves the cursor to the first symbol by default,
        #    which is very distracting.
        # That's why this line is commented!
        # self.set_current_row(0)

        # Update list size
        self.fix_size(short_paths, extra=100)
예제 #29
0
 def update_list(self):
     """Update path list"""
     self.listwidget.clear()
     for name in self.pathlist + self.ro_pathlist:
         item = QListWidgetItem(name)
         item.setIcon(ima.icon('DirClosedIcon'))
         if name in self.ro_pathlist:
             item.setFlags(Qt.NoItemFlags)
         self.listwidget.addItem(item)
     self.refresh()
예제 #30
0
    def _on_data_change(self, *event):

        components = getattr(type(self.state), 'component').get_choices(self.state)

        self.ui.list_component.clear()

        for component in components:

            item = QListWidgetItem(component.label)
            item.setCheckState(Qt.Checked)
            self.ui.list_component.addItem(item)