示例#1
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, self.parent().parent().leafWidget):
             continue
         DeferredCall(self.doDownload, s.data, _delay=backOff)
         backOff += 50
     DeferredCall(self.enableViUnloadingWarning, _delay=backOff + 1000)
示例#2
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["limit"] = 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, icon="icons-download-file")
        self.parent().addClass("is-new")
        self.parent().addClass("log-progress")
        self.appendChild(html5.TextNode(translate("CSV-Export")))

        DeferredCall(self.nextChunk)
示例#3
0
    def __init__(self):
        super(TopBarWidget, self).__init__()

        self["class"] = "vi-topbar bar"

        self.sinkEvent("onClick")

        # language=HTML
        self.fromHTML("""
			<div class="vi-tb-left bar-group bar-group--left" [name]="topbarLeft">
				<div class="vi-tb-logo" [name]="topbarLogo"></div>
				<h1 class="vi-tb-title" [name]="moduleH1"></h1>
				<div class="item" [name]="moduleContainer">
					<div [name]="modulImg"></div>
					<div class="item-content" [name]="moduleName"></div>
				</div>
			</div>
			<nav class="vi-tb-right bar-group bar-group--right" [name]="topbarRight">
				<div class="input-group input-group--bar" [name]="iconnav">
				</div>
			</nav>
		""")

        if not conf["theApp"].isFramed:
            svg = embedsvg.get("logos-vi")
            if svg:
                self.topbarLogo.element.innerHTML = svg + self.topbarLogo.element.innerHTML
        else:
            self.topbarLogo.hide()
            self.moduleH1.hide()

        DeferredCall(self.setTitle, _delay=500)
示例#4
0
    def unserialize(self, data=None):
        """
			Applies the actual data to the bones.
		"""
        for key, bone in self.bones.items():
            if "setContext" in dir(bone) and callable(bone.setContext):
                bone.setContext(self.context)

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

        DeferredCall(self.performLogics)
示例#5
0
	def onLoad(self, *args, **kwargs):
		"""
			Internal callback - The state of our upload changed.
		"""
		if conf["core.version"][0] == 3:
			if self.xhr.status in [200, 204]:
				NetworkService.request(
					"file", "add", {
						"key": self.targetKey,
						"node": self.node,
						"skelType": "leaf"
					},
				    successHandler=self.onUploadAdded,
					secure=True
				)
			else:
				DeferredCall(self.onFailed, self.xhr.status, _delay=1000)
		else:

			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)
示例#6
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).removeClass("is-focused")

		self._currentRow = row
		if self._currentRow is not None:
			self.getTrByIndex(self._currentRow).addClass("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)
示例#7
0
    def handleInitialHash(self, pathList, params):
        assert self.canHandleInitialHash(pathList, params)

        if pathList[1] == "list":
            if self.mode != "group":
                self.addWidget(self.createWidget())
                self.focus()
            else:
                DeferredCall(self.focus, _delay=250)

        elif pathList[1] == "add":
            pane = Pane(translate("Add"),
                        closeable=True,
                        iconURL="icons-add",
                        iconClasses=[
                            "module_%s" % self.moduleName, "apptype_list",
                            "action_add"
                        ])
            edwg = EditWidget(self.moduleName,
                              EditWidget.appList,
                              hashArgs=(params or None))
            pane.addWidget(edwg)
            conf["mainWindow"].addPane(pane, parentPane=self)
            pane.focus()

        elif pathList[1] in ["edit", "clone"] and len(pathList) > 2:
            pane = Pane(translate("Edit"),
                        closeable=True,
                        iconURL="icons-edit",
                        iconClasses=[
                            "module_%s" % self.moduleName, "apptype_list",
                            "action_edit"
                        ])
            edwg = EditWidget(self.moduleName,
                              EditWidget.appList,
                              key=pathList[2],
                              hashArgs=(params or None),
                              clone=pathList[1] == "clone")
            pane.addWidget(edwg)
            conf["mainWindow"].addPane(pane, parentPane=self)
            pane.focus()
示例#8
0
	def onUploadAdded(self, req):
		self.responseValue = NetworkService.decode(req)
		DeferredCall(self.onSuccess, _delay=1000)
示例#9
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
			try:
				self.key = data["values"]["key"]
			except:
				self.key = None

			conf["mainWindow"].log("success",translate(self.logAction),modul=self.module,key=self.key,action=self.mode,data=data)

			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 ]:
					html5.ext.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:
					html5.ext.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.desciptionLabels = {}
		self.actionbar.resetLoadingState()
		self.dataCache = data
		self.modified = False

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

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

		errors = {}

		if conf["core.version"][0] == 3:
			for error in data["errors"]:
				errors[error["fieldPath"]] = error

		self.accordion.clearSegments()
		for key, bone in data["structure"]:

			if key in errors:
				bone["error"] = errors[key]
			else:
				bone[ "error" ] = None

			cat = defaultCat #meow!

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

			if cat not in segments:
				segments[cat] = self.accordion.addSegment(cat)

			boneFactory = boneSelector.select(self.module, key, tmpDict)(self.module, key, tmpDict)
			widget = boneFactory.editWidget()

			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.addClass("label", "vi-label", "vi-label--%s" % bone["type"].replace(".","-"), "vi-label--%s" % key)

			# Elements (TEMP TEMP TEMP)
			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"])
			# /Elements (TEMP TEMP TEMP)

			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"]) or \
					(bone["error"] and isinstance(bone["error"],str) and "dependency error:" in bone["error"]):
				descrLbl.addClass("is-required")

			if bone["error"] and (
				(bone["error"]["severity"]%2==0 and bone["required"]) or\
				(bone["error"]["severity"]%2 == 1)
			):
				#todo if severity = 1 dependency error, we need to mark futher bones

				descrLbl.addClass("is-invalid")
				descrLbl["title"] = bone["error"]

				segments[cat].addClass("is-incomplete is-active")

				hasMissing = True

			elif not self.wasInitialRequest: #
				descrLbl.addClass( "is-valid" )
			else:
				pass # first Call no highlighting

			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(shortText=key if conf["showBoneNames"] else bone.get("descr", key), longText=bone["params"]["tooltip"]))

			segments[cat].addWidget(containerDiv)
			containerDiv.addClass("vi-bone", "vi-bone--%s" % bone["type"].replace(".","-"), "vi-bone--%s" % key)

			if "." in bone["type"]:
				for t in bone["type"].split("."):
					containerDiv.addClass("vi-bone--%s" % t)

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

			#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 and not adminCat:
				firstCat = segments[cat]
			elif adminCat and cat == adminCat:
				firstCat = segments[cat]


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


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

		# Show default category
		if firstCat:
			firstCat.activate()

		self.accordion.buildAccordion("asc")  # order and add to dom

		# 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]

				if vmodule not in segments:
					segments[vmodule] = self.accordion.addSegment(vmodule, vtitle or vdescr.get("name", vmodule),directAdd=True)
					segments[vmodule].addClass("editview")

				if vclass:
					segments[vmodule].addClass(*vclass)

				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)
				segments[vmodule].addWidget(self.views[vmodule])

		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!"),icon="icons-cancel",modul=self.module,key=self.key,action=self.mode,data=data)

		DeferredCall(self.performLogics)
示例#10
0
	def onBoneChange(self, bone):
		self.modified = True
		DeferredCall(self.performLogics)
示例#11
0
	def onChange(self, event):
		self.modified = True
		DeferredCall(self.performLogics)
示例#12
0
 def onChange(self, event):
     DeferredCall(self.performLogics)