예제 #1
0
  def test_i18n_loads_module_by_name(self):
    self.assertTrue(i18n._DICTIONARY is None)

    i18n.load('english')
    self.assertTrue(i18n._DICTIONARY is not None)
    self.assertEqual('Cancel', i18n.translate('cancel'))

    i18n.load('french')
    self.assertEqual('Annuler', i18n.translate('cancel'))
예제 #2
0
 def getItem(self, name):
     all = schema.ns("osaf.pim", self.view).allCollection
     name = translate(name) # search for the localized name
     for item in all:
         if item.displayName == name:
             return item
     
     self.fail("Couldn't find item %s in all collection" % (name,))
예제 #3
0
        def __init__(self, dbobj, dbproperty, errors={}, name=None, title=None, help="", default=None, **kw):
            """
            @param dbobj: The dbobj whoes property is to be displayed by this
              widget
            @param errors: Dict that contains the error messages from the last
              commit.
            @param name: The name attribute of the HTML <input> (or so) element
              that will be created by this. Defaults to dbclass.attribute,
              which will do for most circumstances... A regular String.
            @param title: Will overwrite the datatype.title attribute for the
              widget's caption. Unicode string required.
            @param help: Help text that will be displayed along with the
              widget. May be a XIST element, of course, but you may not want
              to use block level elements in it.
            @param default: Unicode String or other Python object suitable  to
              determine the default setting for this widget if dbobj is None
              (see widget() below)

            The key word arguments may be used to pass arbitrary
            attributes to the widget element.
            """
            widget.actual_widget.__init__(self, dbobj, dbproperty)
            self.errors = errors

            if name is None:
                self.name = "%s_%s" % (dbproperty.dbclass.__name__, dbproperty.attribute_name)
            else:
                if type(name) != StringType:
                    msg = "HTML name property must be string not %s" % repr(name)
                    raise TypeError(msg)

                self.name = name

            if title is None:
                self.title = translate(self.dbproperty.title, self)
            else:
                self.title = title

            if help is None:
                self._help = Frag()
            else:
                self._help = translate(help, self)

            self.default = default

            self.extra_args = kw
예제 #4
0
        def error_message(self, error):
            """
            Return a <div class="error"> with the formated error
            message in it.
            """
            if error is not None:
                if type(error) in (ListType, TupleType):
                    if len(error) > 1:
                        ul = html.ul()
                        for e in error:
                            ul.append(html.li(translate(e, self)))

                        error = ul
                    else:
                        error = translate(error[0], self)
                else:
                    error = translate(error, self)

                error = html.div(error, class_="error")

                return error
            else:
                return Frag()
예제 #5
0
    def setData(self, request=None, data=None, ignoreMissing=False):
        """
		Rebuilds the UI according to the skeleton received from server

		:param request: A finished NetworkService request
		:type request: NetworkService
		:type data: dict
		:param data: The data received
		"""
        assert (request or data)
        if request:
            data = NetworkService.decode(request)

        try:
            skelStructure = {k: v for k, v in data["structure"]}

        except AttributeError:
            NetworkService.notifyChange(self.module)
            conf["mainWindow"].removeWidget(self)
            return

        print
        print("data", data)
        print("action", data["action"])
        if "action" in data and (data["action"]
                                 in ["addSuccess", "editSuccess"]):
            NetworkService.notifyChange(self.module)
            logDiv = html5.Div()
            logDiv["class"].append("msg")
            spanMsg = html5.Span()
            spanMsg.appendChild(html5.TextNode(translate("Entry saved!")))
            spanMsg["class"].append("msgspan")
            logDiv.appendChild(spanMsg)
            if self.module in conf["modules"].keys():
                spanMsg = html5.Span()
                spanMsg.appendChild(
                    html5.TextNode(conf["modules"][self.module]["name"]))
                spanMsg["class"].append("modulspan")
                logDiv.appendChild(spanMsg)
            if "values" in data.keys() and "name" in data["values"].keys():
                spanMsg = html5.Span()
                spanMsg.appendChild(html5.TextNode(str(
                    data["values"]["name"])))
                spanMsg["class"].append("namespan")
                logDiv.appendChild(spanMsg)
            conf["mainWindow"].log("success", logDiv)
            if self.closeOnSuccess:
                conf["mainWindow"].removeWidget(self)
                return
            self.clear()
            # self.bones = {}
            self.reloadData()
            return

        self.clear()
        self.actionbar.resetLoadingState()
        self.dataCache = data

        fieldSets = {}
        cat = "byweek"

        fieldSets[cat] = EditWidgetFieldset(cat)
        fieldSets[cat].addClass("active")

        self.dtstart = data["values"]["startdate"]
        startdateLabel = html5.Label("Termin")
        startdateLabel["class"].append("termin")
        startdateLabel["class"].append("date")
        startdate_id = "vi_%s_%s_edit_bn_%s" % (self.editIdx, self.module,
                                                "repeatdate")
        startdateLabel["for"] = startdate_id
        startdate = date.DateViewBoneDelegate("termin", "startdate",
                                              skelStructure).render(
                                                  data["values"], "startdate")
        startdate["id"] = startdate_id
        containerDiv = html5.Div()
        containerDiv.appendChild(startdateLabel)
        containerDiv.appendChild(startdate)
        containerDiv["class"].append("bone")
        containerDiv["class"].append("bone_startdate")
        containerDiv["class"].append("date")
        fieldSets[cat]._section.appendChild(containerDiv)

        countLabel = html5.Label("Wiederholungen")
        countLabel["class"].append("count")
        countLabel["class"].append("numeric")
        count_id = "vi_%s_%s_edit_bn_%s" % (self.editIdx, self.module, "count")
        countLabel["for"] = count_id

        self.count = html5.Input()
        self.count["id"] = count_id
        containerDiv2 = html5.Div()
        containerDiv2["class"].append("bone")
        containerDiv2["class"].append("bone_count")
        containerDiv2["class"].append("date")
        containerDiv2.appendChild(countLabel)
        containerDiv2.appendChild(self.count)

        # containerDiv3 = html5.Div()
        # self.byweekday = list()
        # for key, value in [["MO", "Mo"], ["TU", "Di"], ["TH", "Mi"], ["WE", "Do"], ["FR", "Fr"], ["SA", "Sa"], ["SU", "So"]]:
        # 	alabel=html5.Label()
        # 	acheckbox=html5.Input()
        # 	acheckbox["type"]="checkbox"
        # 	acheckbox["name"]=key
        # 	alabel.appendChild(acheckbox)
        # 	aspan=html5.Span()
        # 	aspan.element.innerHTML=value
        # 	alabel.appendChild(aspan)
        # 	containerDiv3.appendChild(alabel)
        # 	containerDiv2["class"].append("bone")
        # 	containerDiv2["class"].append("bone_count")
        # 	containerDiv2["class"].append("byweekday")
        # 	self.byweekday.append(acheckbox)

        fieldSets[cat]._section.appendChild(containerDiv2)
        # fieldSets[ cat ]._section.appendChild(containerDiv3)
        for (k, v) in fieldSets.items():
            if not "active" in v["class"]:
                v["class"].append("active")
        tmpList = [(k, v) for (k, v) in fieldSets.items()]
        tmpList.sort(key=lambda x: x[0])
        for k, v in tmpList:
            self.form.appendChild(v)
            v._section = None
예제 #6
0
 def render(self, data, field):
     if field in data.keys():
         return html5.Label(translate(str(data[field])))
     return html5.Label(conf["empty_value"])
예제 #7
0
파일: xmlfile.py 프로젝트: kennym/itools
 def translate(self, catalog, srx_handler=None):
     stream = translate(self.events, catalog, srx_handler)
     return stream_to_str(stream)
예제 #8
0
def findCollection(view, name):
    sidebar = schema.ns("osaf.app", view).sidebarCollection
    name = translate(name) # search for the localized name
    for coll in sidebar:
        if coll.displayName == name:
            return coll
예제 #9
0
파일: list.py 프로젝트: phorward/viur-vi
	def openEditor(self, key):
		pane = Pane(translate("Edit"), closeable=True, iconClasses=["modul_%s" % self.parent().parent().module, "apptype_list", "action_edit" ])
		conf["mainWindow"].stackPane( pane, focus=True )
		edwg = EditWidget(self.parent().parent().module, EditWidget.appList, key=key,
		                    context=self.parent().parent().context)
		pane.addWidget( edwg )
예제 #10
0
파일: list.py 프로젝트: phorward/viur-vi
	def __init__(self, *args, **kwargs):
		super( AddAction, self ).__init__(translate("Add"), *args, **kwargs )
		self["class"] = "icon add list"
예제 #11
0
파일: file.py 프로젝트: sveneberth/viur-vi
 def __init__(self, *args, **kwargs):
     super(AddLeafAction, self).__init__(translate("Add"), *args, **kwargs)
     self["class"] = "icon upload"
예제 #12
0
	def onClick(self, sender=None):
		pane = Pane( translate("Add"), closeable=True, iconClasses=["modul_%s" % self.parent().parent().module, "apptype_tree", "action_add_node" ])
		conf["mainWindow"].stackPane( pane )
		edwg = EditWidget( self.parent().parent().module, EditWidget.appTree, node=self.parent().parent().node, skelType="node" )
		pane.addWidget( edwg )
		pane.focus()
예제 #13
0
 def __init__(self, *args, **kwargs):
     super(ExecuteSingleton, self).__init__(translate("Execute"), *args,
                                            **kwargs)
     self["class"] = "icon save close"
예제 #14
0
 def __init__(self, *args, **kwargs):
     super(SaveClose, self).__init__(translate("Save-Close"), *args,
                                     **kwargs)
     self["class"] = "icon save close"
예제 #15
0
파일: edit.py 프로젝트: Xeon2003/vi
    def setData(self,
                request=None,
                data=None,
                ignoreMissing=False,
                askHierarchyCloning=True):
        """
		Rebuilds the UI according to the skeleton received from server

		@param request: A finished NetworkService request
		@type request: NetworkService
		@type data: dict
		@param data: The data received
		"""
        assert (request or data)

        if request:
            data = NetworkService.decode(request)

        if "action" in data and (data["action"] == "addSuccess"
                                 or data["action"] == "editSuccess"):
            self.modified = False

            logDiv = html5.Div()
            logDiv["class"].append("msg")
            spanMsg = html5.Span()

            spanMsg.appendChild(html5.TextNode(translate(self.logaction)))
            spanMsg["class"].append("msgspan")
            logDiv.appendChild(spanMsg)

            if self.module in conf["modules"].keys():
                spanMsg = html5.Span()
                if self.module.startswith("_"):
                    spanMsg.appendChild(html5.TextNode(self.key))
                else:
                    spanMsg.appendChild(
                        html5.TextNode(conf["modules"][self.module]["name"]))
                spanMsg["class"].append("modulespan")
                logDiv.appendChild(spanMsg)

            if "values" in data.keys() and "name" in data["values"].keys():
                spanMsg = html5.Span()

                name = data["values"].get("name") or data["values"].get(
                    "key", "")
                if isinstance(name, dict):
                    if conf["currentlanguage"] in name.keys():
                        name = name[conf["currentlanguage"]]
                    else:
                        name = name.values()

                if isinstance(name, list):
                    name = ", ".join(name)

                spanMsg.appendChild(
                    html5.TextNode(str(html5.utils.unescape(name))))
                spanMsg["class"].append("namespan")
                logDiv.appendChild(spanMsg)

            try:
                self.key = data["values"]["key"]
            except:
                self.key = None

            conf["mainWindow"].log("success", logDiv)

            if askHierarchyCloning and self.clone:
                # for lists, which are rootNode entries of hierarchies, ask to clone entire hierarchy
                if self.applicationType == EditWidget.appList and "rootNodeOf" in conf[
                        "modules"][self.module]:
                    YesNoDialog(translate(
                        u"Do you want to clone the entire hierarchy?"),
                                yesCallback=self.doCloneHierarchy,
                                noCallback=self.closeOrContinue)
                    return
                # for cloning within a hierarchy, ask for cloning all subentries.
                elif self.applicationType == EditWidget.appHierarchy:
                    YesNoDialog(translate(
                        u"Do you want to clone all subentries of this item?"),
                                yesCallback=self.doCloneHierarchy,
                                noCallback=self.closeOrContinue)
                    return

            self.closeOrContinue()
            return

        #Clear the UI
        self.clear()
        self.bones = {}
        self.views = {}
        self.containers = {}
        self.actionbar.resetLoadingState()
        self.dataCache = data
        self.modified = False

        tmpDict = {k: v for k, v in data["structure"]}
        fieldSets = {}
        currRow = 0
        hasMissing = False
        defaultCat = conf["modules"][self.module].get("visibleName",
                                                      self.module)

        contextVariable = conf["modules"][self.module].get("editContext")
        if self.mode == "edit" and contextVariable:
            if not self.context:
                self.context = {}

            if "=" in contextVariable:
                contextVariable, contextKey = contextVariable.split("=", 1)
            else:
                contextKey = "key"

            self.context.update(
                {contextVariable: data["values"].get(contextKey)})

        for key, bone in data["structure"]:

            cat = defaultCat  #meow!

            if ("params" in bone.keys() and isinstance(bone["params"], dict)
                    and "category" in bone["params"].keys()):
                cat = bone["params"]["category"]

            if not cat in fieldSets.keys():
                fs = html5.Fieldset()
                fs.addClass("active" if not fieldSets else "inactive")

                #fs["class"] = cat

                fs["name"] = cat
                legend = html5.Legend()
                fshref = fieldset_A()
                fshref.appendChild(html5.TextNode(cat))
                legend.appendChild(fshref)
                fs.appendChild(legend)
                section = html5.Section()
                fs.appendChild(section)
                fs._section = section
                fieldSets[cat] = fs

            wdgGen = editBoneSelector.select(self.module, key, tmpDict)
            widget = wdgGen.fromSkelStructure(self.module, key, tmpDict)
            widget["id"] = "vi_%s_%s_%s_%s_bn_%s" % (self.editIdx, self.module,
                                                     self.mode, cat, key)

            if "setContext" in dir(widget) and callable(widget.setContext):
                widget.setContext(self.context)

            if "changeEvent" in dir(widget):
                widget.changeEvent.register(self)

            #widget["class"].append(key)
            #widget["class"].append(bone["type"].replace(".","_"))
            #self.prepareCol(currRow,1)

            descrLbl = html5.Label(
                key if conf["showBoneNames"] else bone.get("descr", key))
            descrLbl["class"].append(key)
            descrLbl["class"].append(bone["type"].replace(".", "_"))
            descrLbl["for"] = "vi_%s_%s_%s_%s_bn_%s" % (
                self.editIdx, self.module, self.mode, cat, key)

            #print(key, bone["required"], bone["error"])
            if bone["required"] or (bone.get("unique") and bone["error"]):
                descrLbl["class"].append("is_required")

                if bone["error"] is not None:
                    descrLbl["class"].append("is_invalid")
                    descrLbl["title"] = bone["error"]
                    fieldSets[cat]["class"].append("is_incomplete")
                    hasMissing = True
                elif bone["error"] is None and not self.wasInitialRequest:
                    descrLbl["class"].append("is_valid")

            if isinstance(bone["error"], dict):
                widget.setExtendedErrorInformation(bone["error"])

            containerDiv = html5.Div()
            containerDiv.appendChild(descrLbl)
            containerDiv.appendChild(widget)

            if ("params" in bone.keys() and isinstance(bone["params"], dict)
                    and "tooltip" in bone["params"].keys()):
                containerDiv.appendChild(
                    ToolTip(longText=bone["params"]["tooltip"]))

            fieldSets[cat]._section.appendChild(containerDiv)
            containerDiv.addClass("bone", "bone_%s" % key,
                                  bone["type"].replace(".", "_"))

            if "." in bone["type"]:
                for t in bone["type"].split("."):
                    containerDiv["class"].append(t)

            currRow += 1
            self.bones[key] = widget
            self.containers[key] = containerDiv

            #Hide invisible bones or logic-flavored bones with their default desire
            if not bone["visible"] or (bone["params"] and
                                       bone["params"].get("logic.visibleIf")):
                self.containers[key].hide()

            # NO elif!
            if bone["params"] and bone["params"].get("logic.readonlyIf"):
                self.containers[key].disable()

        tmpList = [(k, v) for (k, v) in fieldSets.items()]
        tmpList.sort(key=lambda x: x[0])

        for k, v in tmpList:
            self.form.appendChild(v)
            v._section = None

        # Views
        views = conf["modules"][self.module].get("editViews")
        if self.mode == "edit" and isinstance(views, list):
            for view in views:
                vmodule = view.get("module")
                vvariable = view.get("context")
                vclass = view.get("class")
                vtitle = view.get("title")
                vcolumns = view.get("columns")
                vfilter = view.get("filter")

                if not vmodule:
                    print("Misconfiured view: %s" % view)
                    continue

                if vmodule not in conf["modules"]:
                    print("Module '%s' is not described." % vmodule)
                    continue

                vdescr = conf["modules"][vmodule]

                fs = html5.Fieldset()
                fs.addClass("editview", "inactive")

                if vclass:
                    fs.addClass(*vclass)

                fs["name"] = vmodule
                legend = html5.Legend()
                fshref = fieldset_A()
                fshref.appendChild(
                    html5.TextNode(vtitle or vdescr.get("name", vmodule)))
                legend.appendChild(fshref)
                fs.appendChild(legend)
                section = html5.Section()
                fs.appendChild(section)
                fs._section = section
                fieldSets[vmodule] = fs

                if vvariable:
                    context = self.context.copy() if self.context else {}
                    context[vvariable] = data["values"]["key"]
                else:
                    context = self.context

                self.views[vmodule] = ListWidget(vmodule,
                                                 filter=vfilter
                                                 or vdescr.get("filter", {}),
                                                 columns=vcolumns
                                                 or vdescr.get("columns"),
                                                 context=context)
                fs._section.appendChild(self.views[vmodule])
                self.form.appendChild(fs)

        #print(data["values"])
        self.unserialize(data["values"])

        if self._hashArgs:  #Apply the default values (if any)
            self.unserialize(self._hashArgs)
            self._hashArgs = None

        self._lastData = data

        if hasMissing and not self.wasInitialRequest:
            conf["mainWindow"].log("warning",
                                   translate("Could not save entry!"))

        DeferredCall(self.performLogics)
예제 #16
0
파일: edit.py 프로젝트: Xeon2003/vi
    def __init__(self,
                 module,
                 applicationType,
                 key=0,
                 node=None,
                 skelType=None,
                 clone=False,
                 hashArgs=None,
                 context=None,
                 logaction="Entry saved!",
                 *args,
                 **kwargs):
        """
			Initialize a new Edit or Add-Widget for the given module.
			@param module: Name of the module
			@type module: String
			@param applicationType: Defines for what application this Add / Edit should be created. This hides additional complexity introduced by the hierarchy / tree-application
			@type applicationType: Any of EditWidget.appList, EditWidget.appHierarchy, EditWidget.appTree or EditWidget.appSingleton
			@param id: ID of the entry. If none, it will add a new Entry.
			@type id: Number
			@param rootNode: If applicationType==EditWidget.appHierarchy, the new entry will be added under this node, if applicationType==EditWidget,appTree the final node is derived from this and the path-parameter.
			Has no effect if applicationType is not appHierarchy or appTree or if an id have been set.
			@type rootNode: String
			@param path: Specifies the path from the rootNode for new entries in a treeApplication
			@type path: String
			@param clone: If true, it will load the values from the given id, but will save a new entry (i.e. allows "cloning" an existing entry)
			@type clone: Bool
			@param hashArgs: Dictionary of parameters (usually supplied by the window.hash property) which should prefill values.
			@type hashArgs: Dict
		"""
        if not module in conf["modules"].keys():
            conf["mainWindow"].log(
                "error",
                translate("The module '{module}' does not exist.",
                          module=module))
            assert module in conf["modules"].keys()

        super(EditWidget, self).__init__(*args, **kwargs)
        self.module = module

        # A Bunch of santy-checks, as there is a great chance to mess around with this widget
        assert applicationType in [
            EditWidget.appList, EditWidget.appHierarchy, EditWidget.appTree,
            EditWidget.appSingleton
        ]  #Invalid Application-Type?

        if applicationType == EditWidget.appHierarchy or applicationType == EditWidget.appTree:
            assert key is not None or node is not None  #Need either an id or an node

        if clone:
            assert key is not None  #Need an id if we should clone an entry
            assert not applicationType == EditWidget.appSingleton  # We cant clone a singleton
            if applicationType == EditWidget.appHierarchy or applicationType == EditWidget.appTree:
                assert node is not None  #We still need a rootNode for cloning
            if applicationType == EditWidget.appTree:
                assert node is not None  #We still need a path for cloning #FIXME

            self.clone_of = key
        else:
            self.clone_of = None

        # End santy-checks
        self.editIdx = EditWidget.__editIdx_  #Internal counter to ensure unique ids
        EditWidget.__editIdx_ += 1
        self.applicationType = applicationType
        self.key = key
        self.mode = "edit" if self.key or applicationType == EditWidget.appSingleton else "add"
        self.modified = False
        self.node = node
        self.skelType = skelType
        self.clone = clone
        self.bones = {}
        self.closeOnSuccess = False
        self.logaction = logaction
        self.sinkEvent("onChange")

        self.context = context
        self.views = {}

        self._lastData = {}  #Dict of structure and values received

        if hashArgs:
            self._hashArgs = parseHashParameters(hashArgs)
        else:
            self._hashArgs = None

        self.editTaskID = None
        self.wasInitialRequest = True  #Wherever the last request attempted to save data or just fetched the form

        # Action bar
        self.actionbar = ActionBar(self.module, self.applicationType,
                                   (self.mode if not clone else "clone"))
        self.appendChild(self.actionbar)

        editActions = []

        if self.mode == "edit":
            editActions.append("refresh")

        if module in conf["modules"] and conf["modules"][module]:
            editActions.extend(conf["modules"][module].get("editActions", []))

        if applicationType == EditWidget.appSingleton:
            self.actionbar.setActions(["save.singleton"] + editActions)
        else:
            self.actionbar.setActions(["save.close", "save.continue"] +
                                      editActions)

        # Set path
        if applicationType == EditWidget.appSingleton:
            conf["theApp"].setPath(module + "/" + self.mode)
        elif self.mode == "edit":
            conf["theApp"].setPath(module + "/" +
                                   (self.mode if not clone else "clone") +
                                   "/" + self.key)
        else:
            conf["theApp"].setPath(module + "/" + self.mode)

        # Input form
        self.form = html5.Form()
        self.appendChild(self.form)

        # Engage
        self.reloadData()
예제 #17
0
파일: task.py 프로젝트: phorward/viur-vi
 def setActiveTask(self):
     task = self.getSelectedTask()
     self.descr.removeAllChildren()
     self.descr.appendChild(
         html5.TextNode(
             task.get("descr") or translate("No description provided.")))
예제 #18
0
	def __init__(self, *args, **kwargs):
		super( ReloadAction, self ).__init__( translate("Reload"), *args, **kwargs )
		self["class"] = "icon reload"
예제 #19
0
파일: file.py 프로젝트: sveneberth/viur-vi
 def __init__(self, *args, **kwargs):
     super(DownloadAction, self).__init__(translate("Download"), *args,
                                          **kwargs)
     self["class"] = "icon download"
     self["disabled"] = True
     self.isDisabled = True
예제 #20
0
	def __init__(self, *args, **kwargs ):
		super( ReturnSelectionAction, self ).__init__( translate("Select"), *args, **kwargs )
		self["class"] = "icon activateselection"
예제 #21
0
    },

    # Callable tasks
    "tasks": {
        "server": [],
        "client": []
    },

    # Language
    "currentlanguage": "de",

    # Global holder to the currently logged-in user
    "currentUser": None,

    # A value displayed as "empty value"
    "empty_value": translate("-"),

    # Event dispatcher for initial startup Hash
    "initialHashEvent": EventDispatcher("initialHash"),

    # Actions in the top level bar
    "toplevelactions": ["tasks", "userstate", "logout"],

    # Number of rows to fetch in list widgets
    "batchSize": 20,

    # Show bone names instead of description
    "showBoneNames": False,

    # Globally enable/disable dataset preview in lists
    "internalPreview": True,
예제 #22
0
	def __init__(self, *args, **kwargs):
		super( EditAction, self ).__init__(  translate("Edit"), *args, **kwargs )
		self["class"] = "icon edit"
		self["disabled"]= True
		self.isDisabled=True
예제 #23
0
    def __init__(self,
                 moduleName,
                 boneName,
                 readOnly,
                 multiple=False,
                 languages=None,
                 multiLine=False,
                 *args,
                 **kwargs):
        super(StringEditBone, self).__init__(*args, **kwargs)
        self.moduleName = moduleName
        self.boneName = boneName
        self.readOnly = readOnly
        self.multiple = multiple
        self.languages = languages
        self.boneName = boneName
        self.currentTagToDrag = None
        self.currentLanguage = None

        if self.languages and self.multiple:
            self["class"].append("is_translated")
            self["class"].append("is_multiple")
            self.languagesContainer = html5.Div()
            self.appendChild(self.languagesContainer)
            self.buttonContainer = html5.Div()
            self.buttonContainer["class"] = "languagebuttons"
            self.appendChild(self.buttonContainer)
            self.langEdits = {}
            self.langBtns = {}

            for lang in self.languages:
                tagContainer = html5.Div()
                tagContainer["class"].append("lang_%s" % lang)
                tagContainer["class"].append("tagcontainer")
                tagContainer["style"]["display"] = "none"

                langBtn = html5.ext.Button(lang,
                                           callback=self.onLangBtnClicked)
                langBtn.lang = lang
                self.buttonContainer.appendChild(langBtn)

                if not self.readOnly:
                    addBtn = html5.ext.Button(translate("New"),
                                              callback=self.onBtnGenTag)
                    addBtn["class"].append("icon new tag")
                    addBtn.lang = lang
                    tagContainer.appendChild(addBtn)

                self.languagesContainer.appendChild(tagContainer)
                self.langEdits[lang] = tagContainer
                self.langBtns[lang] = langBtn

            self.setLang(self.languages[0])

        elif self.languages and not self.multiple:
            self["class"].append("is_translated")
            self.languagesContainer = html5.Div()
            self.appendChild(self.languagesContainer)
            self.buttonContainer = html5.Div()
            self.buttonContainer["class"] = "languagebuttons"
            self.appendChild(self.buttonContainer)
            self.langEdits = {}
            self.langBtns = {}

            for lang in self.languages:
                langBtn = html5.ext.Button(lang,
                                           callback=self.onLangBtnClicked)
                langBtn.lang = lang
                self.buttonContainer.appendChild(langBtn)

                if multiLine:
                    inputField = html5.Textarea()
                else:
                    inputField = html5.Input()
                    inputField["type"] = "text"

                inputField["style"]["display"] = "none"
                inputField["class"].append("lang_%s" % lang)

                if self.readOnly:
                    inputField["readonly"] = True

                self.languagesContainer.appendChild(inputField)
                self.langEdits[lang] = inputField
                self.langBtns[lang] = langBtn

            self.setLang(self.languages[0])

        elif not self.languages and self.multiple:
            self["class"].append("is_multiple")
            self.tagContainer = html5.Div()
            self.tagContainer["class"].append("tagcontainer")
            self.appendChild(self.tagContainer)

            if not self.readOnly:
                addBtn = html5.ext.Button(translate("New"),
                                          callback=self.onBtnGenTag)
                addBtn.lang = None
                addBtn["class"].append("icon new tag")

                self.tagContainer.appendChild(addBtn)

        else:  # not languages and not multiple:

            if multiLine:
                self.input = html5.Textarea()
            else:
                self.input = html5.Input()
                self.input["type"] = "text"

            self.appendChild(self.input)

            if self.readOnly:
                self.input["readonly"] = True
예제 #24
0
파일: list.py 프로젝트: phorward/viur-vi
	def __init__(self, *args, **kwargs):
		super( DeleteAction, self ).__init__( translate("Delete"), *args, **kwargs )
		self["class"] = "icon delete"
		self["disabled"]= True
		self.isDisabled=True
예제 #25
0
 def __init__(self, *args, **kwargs):
     super(AddNodeAction, self).__init__(translate("Add Node"), *args,
                                         **kwargs)
     self["class"] = "icon mkdir"
예제 #26
0
파일: list.py 프로젝트: phorward/viur-vi
	def __init__(self, *args, **kwargs ):
		super( ListPreviewInlineAction, self ).__init__( translate("Preview"), *args, **kwargs )
		self["class"] = "icon preview"
		self["disabled"] = True
		self.urls = None
예제 #27
0
 def test_happy(self) -> None:
     """Tests the happy path."""
     ctx = test_context.make_test_context()
     with LanguageContext(ctx, "hu"):
         self.assertEqual(i18n.translate("Area"), "Terület")
예제 #28
0
 def onMkDir(self, req):
     dirName = req.dirName
     conf["mainWindow"].log(
         "success", translate("Directory \"{name}\" created.",
                              name=dirName))
예제 #29
0
파일: list.py 프로젝트: sveneberth/viur-vi
    def __init__(self,
                 module,
                 filter=None,
                 columns=None,
                 selectMode=None,
                 filterID=None,
                 filterDescr=None,
                 batchSize=None,
                 context=None,
                 autoload=True,
                 *args,
                 **kwargs):
        """
			:param module: Name of the module we shall handle. Must be a list application!
			:type module: str
		"""
        if not module in conf["modules"].keys():
            conf["mainWindow"].log(
                "error",
                translate("The module '{module}' does not exist.",
                          module=module))
            assert module in conf["modules"].keys()

        super(ListWidget, self).__init__()
        self._batchSize = batchSize or conf[
            "batchSize"]  # How many rows do we fetch at once?
        self.isDetaching = False  #If set, this widget is beeing about to be removed - dont issue nextBatchNeeded requests
        self.module = module
        self.context = context

        self.actionBar = ActionBar(module, "list", currentAction="list")
        self.appendChild(self.actionBar)

        self.sideBar = SideBar()
        self.appendChild(self.sideBar)

        myView = None

        if filterID:
            if conf["modules"] and module in conf["modules"].keys():
                if "views" in conf["modules"][module].keys(
                ) and conf["modules"][module]["views"]:
                    for v in conf["modules"][module]["views"]:
                        if v["__id"] == filterID:
                            myView = v
                            break
            if myView and "extendedFilters" in myView.keys(
            ) and myView["extendedFilters"]:
                self.appendChild(CompoundFilter(myView, module, embed=True))

        checkboxes = (conf["modules"] and module in conf["modules"].keys() and
                      "checkboxSelection" in conf["modules"][module].keys()
                      and conf["modules"][module]["checkboxSelection"])
        indexes = (conf["modules"] and module in conf["modules"].keys()
                   and "indexes" in conf["modules"][module].keys()
                   and conf["modules"][module]["indexes"])

        self.table = DataTable(checkboxes=checkboxes,
                               indexes=indexes,
                               *args,
                               **kwargs)
        self.appendChild(self.table)
        self._currentCursor = None
        self._structure = None
        self._currentRequests = []
        self.columns = []

        self.selectMode = selectMode
        assert selectMode in [None, "single", "multi"]

        if self.selectMode and filter is None and columns is None:
            #Try to select a reasonable set of cols / filter
            if conf["modules"] and module in conf["modules"].keys():
                tmpData = conf["modules"][module]
                if "columns" in tmpData.keys():
                    columns = tmpData["columns"]
                if "filter" in tmpData.keys():
                    filter = tmpData["filter"]

        self.table.setDataProvider(self)
        self.filter = filter.copy() if isinstance(filter, dict) else {}
        self.columns = columns[:] if isinstance(columns, list) else []
        self.filterID = filterID  #Hint for the sidebarwidgets which predefined filter is currently active
        self.filterDescr = filterDescr  #Human-readable description of the current filter
        self._tableHeaderIsValid = False

        #Proxy some events and functions of the original table
        for f in [
                "selectionChangedEvent", "selectionActivatedEvent",
                "cursorMovedEvent", "tableChangedEvent", "getCurrentSelection"
        ]:
            setattr(self, f, getattr(self.table, f))

        self.actionBar.setActions(self.getDefaultActions(myView))

        if self.selectMode:
            self.selectionActivatedEvent.register(self)

        self.emptyNotificationDiv = html5.Div()
        self.emptyNotificationDiv.appendChild(
            html5.TextNode(translate("Currently no entries")))
        self.emptyNotificationDiv["class"].append("emptynotification")
        self.appendChild(self.emptyNotificationDiv)
        self.emptyNotificationDiv["style"]["display"] = "none"
        self.table["style"]["display"] = "none"
        self.filterDescriptionSpan = html5.Span()
        self.appendChild(self.filterDescriptionSpan)
        self.filterDescriptionSpan["class"].append("filterdescription")
        self.updateFilterDescription()

        if autoload:
            self.reloadData()
예제 #30
0
def findCollection(view, name):
    sidebar = schema.ns("osaf.app", view).sidebarCollection
    name = translate(name)  # search for the localized name
    for coll in sidebar:
        if coll.displayName == name:
            return coll
예제 #31
0
 def setPayedFailed(self, response):
     conf["mainWindow"].log("error", translate(self.txtFailure))
     self.failed += 1