Exemple #1
0
    def onLoad(self, *args, **kwargs):
        """
			Internal callback - The state of our upload changed.
		"""
        if self.xhr.status == 200:
            self.responseValue = json.loads(self.xhr.responseText)
            DeferredCall(self.onSuccess, _delay=1000)
        else:
            DeferredCall(self.onFailed, self.xhr.status, _delay=1000)
Exemple #2
0
 def onClick(self, sender=None):
     selection = self.parent().parent().getCurrentSelection()
     if not selection:
         return
     backOff = 50
     self.disableViUnloadingWarning()
     for s in selection:
         if not isinstance(s, LeafFileWidget):
             continue
         DeferredCall(self.doDownload, s.data, _delay=backOff)
         backOff += 50
     DeferredCall(self.enableViUnloadingWarning, _delay=backOff + 1000)
Exemple #3
0
    def enable(self):
        self.pwform.show()
        self.otpform.hide()
        self.editform.hide()

        super(UserPasswordLoginHandler, self).enable()
        DeferredCall(self.focusLaterIdiot)
Exemple #4
0
    def __init__(self):
        #DOM.setAttribute( self.element, "class", "vi_topbar")
        super(TopBarWidget, self).__init__()

        self["class"] = "vi_topbar"
        anav = html5.Nav()
        anav["class"].append("iconnav")
        self.iconnav = html5.Ul()

        #self.logoContainer = html5.Div()
        #self.logoContainer["class"].append("logo")
        #self.appendChild( self.logoContainer )

        self.sinkEvent("onClick")

        self.modulH1 = html5.H1()
        self.modulH1._setClass("module")
        self.appendChild(self.modulH1)

        self.modulContainer = html5.Div()
        self.modulContainer["class"].append("currentmodul")
        self.appendChild(self.modulContainer)

        self.modulImg = html5.Label()
        self.modulContainer.appendChild(self.modulImg)

        self.moduleName = html5.Span()
        self.modulContainer.appendChild(self.moduleName)

        anav.appendChild(self.iconnav)
        self.appendChild(anav)

        DeferredCall(self.setTitle, _delay=500)
Exemple #5
0
    def __init__(self,
                 widget,
                 selection,
                 encoding=None,
                 language=None,
                 separator=None,
                 lineSeparator=None,
                 *args,
                 **kwargs):
        super(ExportCsv, self).__init__()

        if encoding is None or encoding not in ["utf-8", "iso-8859-15"]:
            encoding = "utf-8"

        if language is None or language not in conf["server"].keys():
            language = conf["currentlanguage"]

        self.widget = widget
        self.module = widget.module
        self.params = self.widget.getFilter().copy()
        self.params["amount"] = 99
        self.data = []
        self.structure = None
        self.separator = separator or ";"
        self.lineSeparator = lineSeparator or "\n"
        self.encoding = encoding
        self.lang = language

        conf["mainWindow"].log("progress", self)
        self.parent()["class"].append("is_new")
        self.parent()["class"].append("log_progress")
        self.appendChild(html5.TextNode(translate("CSV-Export")))

        DeferredCall(self.nextChunk)
Exemple #6
0
 def stackPane(self, pane, focus=False):
     assert self.currentPane is not None, "Cannot stack a pane. There's no current one."
     self.addPane(pane, parentPane=self.currentPane)
     if focus and not self.nextPane:
         # We defer the call to focus, as some widgets stack more than one pane at once.
         # If we focus directly, they will stack on each other, instead of the pane that
         # currently has focus
         self.nextPane = pane
         DeferredCall(self.focusNextPane)
Exemple #7
0
	def unserialize(self, data = None):
		"""
			Applies the actual data to the bones.
		"""
		for bone in self.bones.values():
			if "setContext" in dir(bone) and callable(bone.setContext):
				bone.setContext(self.context)

			if data is not None:
				bone.unserialize(data)

		DeferredCall(self.performLogics)
Exemple #8
0
    def onClick(self, event=None, *args, **kwargs):
        if not self.childDomElem:
            self.childDomElem = html5.Ul()
            self.childDomElem["style"]["display"] = "none"
            self.appendChild(self.childDomElem)

        if not self.childPanes:
            self.lock()
            DeferredCall(self.loadChildren, _delay=100)

        if self.isExpanded:
            self.collapse()
        else:
            self.expand()

        if event:
            event.stopPropagation()
Exemple #9
0
    def __init__(self,
                 descr=None,
                 iconURL=None,
                 iconClasses=None,
                 closeable=False,
                 collapseable=True,
                 focusable=True,
                 path=None):
        super(Pane, self).__init__()

        self.parentPane = None
        self.sinkEvent("onClick")
        self.groupPrefix = None

        self.descr = descr
        self.iconURL = iconURL
        self.iconClasses = iconClasses
        self.collapseable = collapseable
        self.focusable = focusable
        self.path = path

        self.childPanes = []

        self.widgetsDomElm = html5.Div()
        self.widgetsDomElm["class"].append("has_no_child")
        self.childDomElem = None

        self.img = None
        self.label = html5.A()
        self.label["class"].append("button")
        self.appendChild(self.label)

        self.closeBtn = html5.ext.Button(translate("Close"),
                                         self.onBtnCloseReleased)
        self.closeBtn.addClass("closebtn")
        self.appendChild(self.closeBtn)

        if not closeable:
            self.closeBtn.hide()

        self.closeable = closeable
        self.isExpanded = False
        self.defaultImgSrc = self.iconURL

        DeferredCall(self.setText, _delay=250)
Exemple #10
0
    def setCursorRow(self, row, removeExistingSelection=True):
        """
			Move the cursor to row 'row'.
			If removeExistingSelection is True, the current selection (if any) is invalidated.
		"""
        if self._currentRow is not None:
            self.getTrByIndex(self._currentRow)["class"].remove("is_focused")

        self._currentRow = row
        if self._currentRow is not None:
            self.getTrByIndex(self._currentRow)["class"].append("is_focused")
            self.cursorMovedEvent.fire(self, row)

        if removeExistingSelection:
            for row in self._selectedRows[:]:
                self.removeSelectedRow(row)
            self.selectionChangedEvent.fire(self, self.getCurrentSelection())

        DeferredCall(self.focusRow, row)
Exemple #11
0
    def log(self, type, msg):
        """
			Adds a message to the log
			:param type: The type of the message.
			:type type: "success", "error", "warning", "info", "progress"
			:param msg: The message to append
			:type msg: str
		"""
        assert type in ["success", "error", "warning", "info", "progress"]

        liwrap = html5.Li()
        liwrap["class"].append("log_" + type)
        liwrap["class"].append("is_new")

        spanDate = html5.Span()
        spanDate.appendChild(
            html5.TextNode(datetime.now().strftime("%H:%M:%S")))
        spanDate["class"].append("date")
        liwrap.appendChild(spanDate)

        if isinstance(msg, html5.Widget):
            #Append that widget directly
            liwrap.appendChild(msg)

        else:
            #Create a span element for that message
            spanMsg = html5.Span()
            spanMsg.appendChild(html5.TextNode(html5.utils.unescape(msg)))
            spanMsg["class"].append("msg")
            liwrap.appendChild(spanMsg)

        DeferredCall(self.removeNewCls, liwrap, _delay=2500)
        self.logUL.appendChild(liwrap)

        if len(self.logUL._children) > 1:
            self.logUL.element.removeChild(liwrap.element)
            self.logUL.element.insertBefore(
                liwrap.element, self.logUL.element.children.item(0))
Exemple #12
0
	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 = {}
		firstCat = None
		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():
				fieldSets[cat] = EditWidgetFieldset(cat)

			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)

			descrLbl = html5.Label(key if conf["showBoneNames"] else bone.get("descr", key))
			descrLbl["class"].append(key)
			descrLbl["class"].append(bone["type"].replace(".","_"))

			# Elements
			if ("params" in bone.keys()
			    and isinstance(bone["params"], dict)
			    and "elements.source" in bone["params"].keys()):
				descrLbl.addClass("elements-%s" % bone["params"]["elements.source"])

			descrLbl["for"] = "vi_%s_%s_%s_%s_bn_%s" % (self.editIdx, self.module, self.mode, cat, key)

			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")

					# Put info into message center
					conf["mainWindow"].log("info", "%s: %s" % (bone.get("descr", key), translate(bone["error"])))

					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()
			elif bone["visible"] and not firstCat:
				firstCat = fieldSets[cat]

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

		# Hide all fieldSets where all fields are invisible
		for fs in fieldSets.values():
			fs.checkVisibility()

		# Show default category
		if firstCat:
			firstCat.removeClass("inactive")
			firstCat.addClass("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

		# 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")
				vactions = view.get("actions")

				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 = EditWidgetFieldset(vmodule, vtitle or vdescr.get("name", vmodule))
				fs.addClass("editview", "inactive")

				if vclass:
					fs.addClass(*vclass)

				fieldSets[vmodule] = EditWidgetFieldset(vmodule, vtitle or vdescr.get("name", vmodule))

				if vvariable:
					context = self.context.copy() if self.context else {}

					if "=" in vvariable:
						vkey, vvalue = vvariable.split("=", 1)
						if vvalue[0] == "$":
							vvalue = data["values"].get(vvalue[1:])
					else:
						vkey = vvariable
						vvalue = data["values"].get("key")

					context[vkey] = vvalue

				else:
					context = self.context

				self.views[vmodule] = ListWidget(
					vmodule,
					filter=vfilter or vdescr.get("filter", {}),
					columns=vcolumns or vdescr.get("columns"),
					context=context,
					actions=vactions
				)

				fs._section.appendChild(self.views[vmodule])
				self.form.appendChild(fs)

		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)
Exemple #13
0
	def onBoneChange(self, bone):
		self.modified = True
		DeferredCall(self.performLogics)
Exemple #14
0
	def onChange(self, event):
		self.modified = True
		DeferredCall(self.performLogics)
Exemple #15
0
	def onChange(self, event):
		DeferredCall(self.performLogics)
Exemple #16
0
    def startup(self):
        config = conf["mainConfig"]
        assert config

        if not conf["currentUser"]:
            self.getCurrentUser()
            return

        conf["server"] = config.get("configuration", {})

        if "vi.name" in conf["server"]:
            conf["vi.name"] = str(conf["server"]["vi.name"])

        self.userLoggedOutMsg = UserLogoutMsg()
        self.topBar.invoke()

        moduleGroups = []

        # Save module groups
        if ("configuration" in config.keys()
                and isinstance(config["configuration"], dict)):

            if ("modulGroups" in config["configuration"].keys() and isinstance(
                    config["configuration"]["modulGroups"], list)):
                alert(
                    "Hello! Your project is still using 'admin.modulGroups' for its module grouping information.\n"
                    "Please rename it to 'admin.moduleGroups' (yes, with 'e') to avoid this alert message.\n\n"
                    "Thank you!")

                moduleGroups = config["configuration"]["modulGroups"]

            if ("moduleGroups" in config["configuration"].keys() and
                    isinstance(config["configuration"]["moduleGroups"], list)):
                moduleGroups = config["configuration"]["moduleGroups"]

        # Modules
        groupPanes = {}
        panes = []
        userAccess = conf["currentUser"].get("access", [])
        predefinedFilterCounter = 1

        groupedModules = {}

        # First create group panes, if configured
        for group in moduleGroups:
            groupedModules[group["prefix"]] = []
            groupPanes[group["prefix"]] = GroupPane(group["name"],
                                                    iconURL=group.get("icon"))
            groupPanes[group["prefix"]].groupPrefix = group["prefix"]
            panes.append((group["name"], group.get("sortIndex"),
                          groupPanes[group["prefix"]]))

        # Sort all modules first

        # read Hash to register startup module
        currentActiveGroup = None
        path = None
        urlHash = conf["startupHash"]
        if urlHash:

            if "?" in urlHash:
                hashStr = urlHash[1:urlHash.find("?")]
            else:
                hashStr = urlHash[1:]
            path = [x for x in hashStr.split("/") if x]

        sortedModules = []
        topLevelModules = {}

        for module, info in config["modules"].items():
            if not "root" in userAccess and not any(
                [x.startswith(module) for x in userAccess]):
                # Skip this module, as the user couldn't interact with it anyway
                continue

            sortedModules.append((module, info))

            groupName = info["name"].split(":")[0] + ": "

            if groupName not in groupPanes.keys():
                topLevelModules.update({module: info})
            else:
                if path and module == path[0]:
                    currentActiveGroup = groupName

                groupedModules[groupName].append((module, info))

        conf["vi.groupedModules"] = groupedModules

        sortedModules.sort(key=lambda entry: "%d-%010d-%s" % (
            1 if entry[1].get("sortIndex") is None else 0, entry[1].get(
                "sortIndex", 0), entry[1].get("name")))

        # When create module panes
        for module, info in sortedModules:
            if "views" in info.keys() and info["views"]:
                for v in info[
                        "views"]:  # Work-a-round for PyJS not supporting id()
                    v["__id"] = predefinedFilterCounter
                    predefinedFilterCounter += 1

            if currentActiveGroup or module in topLevelModules:
                handlerCls = HandlerClassSelector.select(module, info)
                assert handlerCls is not None, "No handler available for module '%s'" % module

                info["visibleName"] = info["name"]
                handler = None

                if info["name"] and currentActiveGroup and info[
                        "name"].startswith(currentActiveGroup):
                    info["visibleName"] = info["name"].replace(
                        currentActiveGroup, "")
                    handler = handlerCls(module, info)
                    groupPanes[currentActiveGroup].addChildPane(handler)

                if not handler and module in topLevelModules:
                    handler = handlerCls(module, info)
                    panes.append(
                        (info["visibleName"], info.get("sortIndex"), handler))

                info["_handler"] = handler

            conf["modules"][module] = info

    # Sorting our top level entries
        panes.sort(key=lambda entry: "%d-%010d-%s" %
                   (1 if entry[1] is None else 0, entry[1] or 0, entry[0]))

        # Add panes in the created order
        for name, idx, pane in panes:
            self.addPane(pane)

        # Finalizing!
        viInitializedEvent.fire()
        DeferredCall(self.checkInitialHash)
        self.unlock()
Exemple #17
0
    def startup(self):
        config = conf["mainConfig"]
        assert config

        if not conf["currentUser"]:
            self.getCurrentUser()
            return

        conf["server"] = config.get("configuration", {})

        if "vi.name" in conf["server"]:
            conf["vi.name"] = str(conf["server"]["vi.name"])

        self.userLoggedOutMsg = UserLogoutMsg()
        self.topBar.invoke()

        moduleGroups = []

        # Save module groups
        if ("configuration" in config.keys()
                and isinstance(config["configuration"], dict)):

            if ("modulGroups" in config["configuration"].keys() and isinstance(
                    config["configuration"]["modulGroups"], list)):

                alert(
                    "Hello! Your project is still using 'admin.modulGroups' for its module grouping information.\n"
                    "Please rename it to 'admin.moduleGroups' (yes, with 'e') to avoid this alert message.\n\n"
                    "Thank you!")

                moduleGroups = config["configuration"]["modulGroups"]

            if ("moduleGroups" in config["configuration"].keys() and
                    isinstance(config["configuration"]["moduleGroups"], list)):

                moduleGroups = config["configuration"]["moduleGroups"]

        # Modules
        groupPanes = {}
        panes = []
        userAccess = conf["currentUser"].get("access", [])
        predefinedFilterCounter = 1

        # First create group panes, if configured
        for group in moduleGroups:
            groupPanes[group["prefix"]] = GroupPane(group["name"],
                                                    iconURL=group.get("icon"))
            panes.append((group["name"], group.get("sortIndex"),
                          groupPanes[group["prefix"]]))

        # Sort all modules first
        sortedModules = [(x, y) for x, y in config["modules"].items()]
        sortedModules.sort(key=lambda entry: "%d-%010d-%s" % (
            1 if entry[1].get("sortIndex") is None else 0, entry[1].get(
                "sortIndex", 0), entry[1].get("name")))

        # When create module panes
        for module, info in sortedModules:
            if not "root" in userAccess and not any(
                [x.startswith(module) for x in userAccess]):
                #Skip this module, as the user couldn't interact with it anyway
                continue

            conf["modules"][module] = info

            if "views" in conf["modules"][module].keys(
            ) and conf["modules"][module]["views"]:
                for v in conf["modules"][module][
                        "views"]:  #Work-a-round for PyJS not supporting id()
                    v["__id"] = predefinedFilterCounter
                    predefinedFilterCounter += 1

            handlerCls = HandlerClassSelector.select(module, info)
            assert handlerCls is not None, "No handler available for module '%s'" % module

            conf["modules"][module]["visibleName"] = conf["modules"][module][
                "name"]
            handler = None

            for k in groupPanes.keys():
                if info["name"].startswith(k):
                    conf["modules"][module]["visibleName"] = conf["modules"][
                        module]["name"].replace(k, "")
                    handler = handlerCls(module, info)
                    groupPanes[k].addChildPane(handler)
                    break

            if not handler:
                handler = handlerCls(module, info)
                panes.append(
                    (info["visibleName"], info.get("sortIndex"), handler))

            conf["modules"][module]["_handler"] = handler

        # Sorting our top level entries
        panes.sort(key=lambda entry: "%d-%010d-%s" %
                   (1 if entry[1] is None else 0, entry[1] or 0, entry[0]))

        # Push the panes, ignore group panes with no children (due to right restrictions)
        for name, idx, pane in panes:
            #print("idx", name, idx)

            # Don't display GroupPanes without children.
            if (isinstance(pane, GroupPane) and
                (not pane.childPanes or all(c["style"].get("display") == "none"
                                            for c in pane.childPanes))):
                continue

            self.addPane(pane)

        # Finalizing!
        viInitializedEvent.fire()
        DeferredCall(self.checkInitialHash)
        self.unlock()