Пример #1
0
    def __init__(self, stage, astergui, parent=None, **kwargs):
        """
        Create editor.

        Arguments:
            stage (Stage): Stage to edit.
            astergui (AsterGui): AsterGui instance.
            parent (Optional[QWidget]): Parent widget. Defaults to
                *None*.
            **kwargs: Keyword arguments.
        """
        super(StageTextEditor,
              self).__init__(parent=parent,
                             name=translate("StageTextEditor", "Edit stage"),
                             astergui=astergui,
                             **kwargs)

        self.stage = stage
        self.prev_state = stage.get_text()

        title = translate("StageTextEditor", "Edit stage '{}'")
        self.setWindowTitle(title.format(stage.name))
        self.setPixmap(load_pixmap("as_pic_edit_stage.png"))

        self.editor = TextEditor(self)
        v_layout = Q.QVBoxLayout(self)
        v_layout.addWidget(self.editor)
        commands = [j for i in [CATA.get_category(i) \
                                    for i in CATA.get_categories()] for j in i]
        self.editor.setKeywords(commands, 0, Q.QColor("#ff0000"))
        self.editor.setText(self.prev_state)
        self.editor.textChanged.connect(self.updateButtonStatus)
        self.setFocusProxy(self.editor)
        astergui.preferencesChanged.connect(self.editor.updateSettings)
        self.editor.updateSettings(self.astergui().preferencesMgr())
Пример #2
0
    def __init__(self, astergui, parent=None):
        """
        Create `Show all` edition panel.

        Arguments:
            astergui (AsterGui): Parent AsterGui instance.
            parent (Optional[QWidget]): Parent widget. Defaults to
                *None*.
        """
        super(ShowAllPanel, self).__init__(parent=parent,
                                           name=translate("ShowAllPanel",
                                                          "Show all commands"),
                                           astergui=astergui)
        self.setWindowTitle(translate("ShowAllPanel", "Add command"))
        self.setPixmap(load_pixmap("as_pic_new_command.png"))
        v_layout = Q.QVBoxLayout(self)
        v_layout.setContentsMargins(0, 0, 0, 0)
        self.panel = Panel(self)
        description = Q.QGroupBox(self)
        description.setTitle(translate("ShowAllPanel", "Command description"))
        desc_layout = Q.QVBoxLayout(description)
        self.info = Q.QLabel(description)
        self.info.setWordWrap(True)
        self.info.setOpenExternalLinks(True)
        desc_layout.addWidget(self.info)
        for category in CATA.get_categories("showall"):
            # get commands from category
            items = CATA.get_category(category)
            if not items:
                continue
            # get translation for category's title
            view = CategoryView(translate_category(category),
                                parent=self.panel)
            view.category = category
            for item in items:
                # get translation for command
                title = translate_command(item)
                if title != item:
                    title = title + " ({})".format(item)
                view.addItem(title, item)
            self.panel.addWidget(view)
            connect(view.selected, self._selectionChanged)
            connect(view.doubleClicked, self._doubleClicked)
        v_layout.addWidget(self.panel)
        v_layout.addWidget(description)
        connect(self.astergui().selectionChanged, self.updateButtonStatus)
        self.panel.installEventFilter(self)
        self.setFocusProxy(self.panel)
Пример #3
0
    def _selectionChanged(self, command):
        """
        Called when a command is selected in any category.

        Arguments:
            command (str): Command name.
        """
        sender_view = self.sender()
        for view in self.panel.widgets():
            if view != sender_view:
                view.clearSelection()
        if command:
            translation = translate_command(command)
            description = CATA.get_command_docstring(command)
            url = self.astergui().doc_url(command)
            if translation != command:
                text = italic(translation) + " ({})".format(bold(command))
            else:
                text = bold(command)
            # add doc url
            if url:
                doc = href(image(CFG.rcfile("as_pic_help.png"),
                                 width=20, height=20), url)
                text += " " + doc
            text = preformat(text)
            if description:
                text = text + "<br/>" + description
            self.info.setText(text)
        else:
            self.info.setText("")
        self.updateButtonStatus()
Пример #4
0
    def _updateState(self):
        """Update state and current title label."""
        disabled = self.command() is None
        self.setDisabled(disabled)

        if not disabled:
            disabled = self.command().gettype(ConversionLevel.NoFail) is None
        self._name.setDisabled(disabled)

        txt = []
        pview = self.currentParameterView()
        if pview is not None:
            txt = pview.path().names()

        ppath = None
        txt_list = []
        tooltip = ""
        whats_this = ""
        while len(txt) > 0:
            name = txt.pop(0)
            if ppath is None:
                ppath = ParameterPath(self.command(), name=name)
            else:
                ppath = ppath.absolutePath(name)
            if ppath.isInSequence():
                txt_list.append("[" + name + "]")
            elif get_cata_typeid(ppath.keyword()) in (IDS.simp, IDS.fact):
                # translate keyword
                kwtext = Options.translate_command(ppath.command().title, name)
                txt_list.append(kwtext)
            elif get_cata_typeid(ppath.keyword()) == IDS.command:
                # translate command
                translation = Options.translate_command(name)
                txt_list.append(translation)
                if translation != name:
                    wttext = italic(translation) + " ({})".format(bold(name))
                else:
                    wttext = bold(name)
                tooltip = preformat(wttext)
                url = self.astergui().doc_url(name)
                if url:
                    wttext += "&nbsp;"
                    wttext += href(
                        image(CFG.rcfile("as_pic_help.png"),
                              width=20,
                              height=20), url)
                wttext = preformat(wttext)
                docs = CATA.get_command_docstring(name)
                if docs:
                    wttext += "<hr>"
                    wttext += docs
                whats_this = wttext

        self.title.setTitle(txt_list)
        self.title.setToolTip(tooltip)
        self.title.setWhatsThis(whats_this)
Пример #5
0
    def _typeInformation(self):
        """
        Gets the information text about keyword type.
        """
        inflist = []
        kword = self.path().keyword()
        if kword is not None:
            kwtypelist = []
            kwdef = kword.definition
            enum = kwdef.get('into') is not None
            if enum and sorted(kwdef.get('into')) == ["NON", "OUI"]:
                txt = "'%s'/'%s'" % (bold(translate("ParameterPanel", "Yes")),
                                     bold(translate("ParameterPanel", "No")))
                inflist.append(txt)
            elif kwdef.get('typ') is not None:
                kwtypelist = to_list(kwdef.get('typ'))

            for kwtype in kwtypelist:
                if kwtype is None:
                    continue

                if kwtype == 'I':
                    txt = bold(translate("ParameterPanel", "integer"))
                    lim = self._numberLimitsInfo(kwdef.get('val_min'),
                                                 kwdef.get('val_max'))
                    if len(lim):
                        txt += " " + lim
                elif kwtype == 'R':
                    txt = bold(translate("ParameterPanel", "float"))
                    lim = self._numberLimitsInfo(kwdef.get('val_min'),
                                                 kwdef.get('val_max'))
                    if len(lim):
                        txt += " " + lim
                elif kwtype == 'TXM':
                    txt = bold(translate("ParameterPanel", "string"))
                elif is_subclass(kwtype, CATA.package('DataStructure').CO):
                    txt = bold(translate("ParameterPanel", "macro name"))
                elif isinstance(kwtype, (types.TypeType, types.ClassType)):
                    txt = translate("ParameterPanel", "object with type")
                    txt += bold(" '%s'" % kwtype.__name__)
                else:
                    txt = bold(str(kwtype))

                if len(txt):
                    if enum:
                        txt += " (%s)" % italic(translate("ParameterPanel",
                                                          "enumerated"))
                    inflist.append(txt)
        info = ""
        if len(inflist):
            islist = self.path().isKeywordSequence() and \
                not self.path().isInSequence()
            prefix = translate("ParameterPanel", "List with types") \
                if islist else translate("ParameterPanel", "Value types")
            info = prefix + ": " + ", ".join(inflist)
        return info
Пример #6
0
 def _is_meshgroup(cls, path):
     ismeshkw = is_contains_word(path.name(), ["GROUP_MA", "GROUP_NO"])
     if ismeshkw:
         kw_def = path.keyword().definition
         typ = kw_def.get('typ')
         if isinstance(typ, (tuple, list)):
             if len(typ) > 0:
                 typ = typ[0]
             else:
                 typ = None
         ismeshkw = is_subclass(typ, CATA.package('DataStructure').GEOM)
     return ismeshkw
Пример #7
0
 def updateTranslations(self):
     """
     Update translations in GUI elements.
     """
     views = self.panel.widgets()
     for view in views:
         items = CATA.get_category(view.category)
         view.clear()
         for item in items:
             title = translate_command(item)
             if title != item:
                 title = title + " ({})".format(item)
             view.addItem(title, item)
     self.panel.applyFilter()
Пример #8
0
def translate_command(command,
                      keyword=None,
                      item=None,
                      force_translations=None):
    """
    Get professionally-oriented translation for:

    - Command;
    - Command's keyword;
    - Keyword's enumerator (*into* value).

    Usage of business-oriented translations is controlled via:

    - Option of *Preferences* dialog;
    - Command line switch;
    - *force_translations* argument (see below).

    Arguments:
        command (str): Command's catalog name.
        keyword (Optional[str]): Keyword's catalog name. Defaults to
            *None*.
        item (Optional[str]): Item's catalog name. Defaults to *None*.
        force_translations (Optional[bool]): Forced option for usage of
            business-oriented translations. When this parameter is
            specified, an option set in *Preferences* dialog is ignored.
            This argument is used in *Parameters* panel only.
            Defaults to *None* that means no forced option.

    Returns:
        str: Translation or native catalog name depending on currently
        specified behavior.
    """
    from_cmdline = behavior().forced_native_names and \
        behavior().force_native_names

    if force_translations is not None:
        from_preferences = not behavior().forced_native_names and \
            not force_translations
    else:
        from_preferences = not behavior().forced_native_names and \
            behavior().use_native_names

    use_native_names = from_cmdline or from_preferences

    if use_native_names:
        return item if item is not None else \
            keyword if keyword is not None else command
    else:
        return translate("Commands",
                         CATA.get_translation(command, keyword, item))
Пример #9
0
    def _is_filename(cls, path):
        """
        Check if `path` is a unit keyword.

        Arguments:
            path (ParameterPath): Parameter's path.

        Returns:
            bool: *True* if `path` is a unit parameter; *False* otherwise.
        """
        is_file = is_contains_word(path.name(), 'UNITE')
        param_def = path.keyword()
        if is_file and param_def is not None and \
                hasattr(param_def, "definition"):
            defin = param_def.definition
            objtype = defin.get('typ')
            if not is_subclass(objtype,
                               CATA.package('DataStructure').UnitBaseType):
                is_file = False
        return is_file
Пример #10
0
 def update(self):
     """Update model."""
     stages = []
     if self.case is None:
         if get_node_type(self.root) == NodeType.Stage:
             stages.append(self.root)
     else:
         self._stage_children = {}
         self._categories = []
         stages = self.case.stages
     for stage in stages:
         if stage.is_graphical_mode():
             # not be necessary if command.check was called before update
             stage.reorder()
             commands = stage.sorted_commands
             categories = []
             withnext = []
             for command in commands:
                 if command.title == "_CONVERT_COMMENT":
                     if behavior().show_comments:
                         withnext.append(command)
                     continue
                 category = CATA.get_command_category(command.title)
                 category = translate_category(category)
                 if not categories or categories[-1].name != category:
                     uid = len(self._categories) + 1
                     new_category = Category(-uid, category, stage.uid,
                                             self._history_proxy)
                     self._categories.append(new_category)
                     categories.append(new_category)
                 for i in withnext:
                     categories[-1].add_child(i)
                 categories[-1].add_child(command)
                 withnext = []
             # purge the buffer
             if categories:  # only comments => ignored!
                 for i in withnext:
                     categories[-1].add_child(i)
             self._stage_children[stage] = categories
         else:
             self._stage_children[stage] = []
Пример #11
0
    def validate(self):
        """
        Perform value validation.

        Returns:
           bool: Validation status: True if value is valid; False
           otherwise.
        """
        state = True
        checker = CATA.package('Syntax').SyntaxCheckerVisitor()
        cond_context = self.conditionStorage(with_default=True)
        # conditionStorage returns values for simple keyword
        if isinstance(cond_context, dict):
            checker.set_parent_context(cond_context)

        exc_message = []
        try:
            self.keyword().accept(checker, self.itemValue())
        except Exception as exc:  # pragma pylint: disable=broad-except
            from traceback import format_exc
            exc_message.append("Raw output message:\n{}\n".format(exc.args[0]))
            if debug_mode():
                exc_message.append("\n" + format_exc(exc))
            state = False

        if state:
            return True

        rule = None
        stack = checker.stack
        if len(stack) > 0 and not isinstance(stack[-1], basestring):
            rule = stack.pop()

        item = self
        while len(stack) > 0:
            items = item.findItemsByName(stack.pop(0))
            for i in items:
                if not i.testFlags(self.ItemFlags.Filtered) and \
                        not i.testFlags(self.ItemFlags.Excluded):
                    item = i
                    break


#        pos = self.contentsRect().center()
        msgInfo = []
        hiframe = None
        if item is not None and item != self:
            rect = item.itemRect()
            space = self.grid().spacing() / 2
            rect.adjust(-space, -space, space, space)
            self.ensureVisible.emit(rect)
            #            pos = rect.center()

            hiframe = ParameterItemHilighter(rect, self)
            hiframe.show()
            kwtext = Options.translate_command(item.command().title,
                                               item.itemName())
            msgInfo.append(
                translate("ParameterPanel",
                          "Invalid input in {0}.").format(kwtext))
        else:
            msgInfo.append(translate("ParameterPanel", "Invalid input."))

        if rule is not None:
            rulemsg = translate(
                "ParameterPanel", "Not respected the rule: {0}"
                " with keywords: {1}.")
            msgInfo.append(
                rulemsg.format(type(rule).__name__, ", ".join(rule.ruleArgs)))

        msgInfo.append(
            translate("ParameterPanel",
                      "Do you want to save the changes any way?"))

        #        balloon = ParameterBaloon(self)
        #        balloon.setTitle(translate("ParameterPanel", "Error"))
        #        balloon.setMessage("<br>".join(msg))
        #        balloon.setPositon(self.mapToGlobal(pos))
        #        balloon.show()

        details = " ".join(exc_message)
        answer = MessageBox.question(self,
                                     translate("ParameterPanel", "Error"),
                                     "\n".join(msgInfo),
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.Yes,
                                     detailedText=details)

        if hiframe is not None:
            hiframe.hide()

        return answer == QMessageBox.Yes