def onTaskListAvailable(self, req): data = NetworkService.decode(req) if not "skellist" in data.keys() or not data["skellist"]: conf["tasks"]["server"] = [] self.hide() return conf["tasks"]["server"] = data["skellist"]
def onSetDefaultRootNode(self, req): """ We requested the list of rootNodes for that module and that request just finished. Parse the respone and set our rootNode to the first rootNode received. """ data = NetworkService.decode(req) if len(data) > 0: self.setRootNode(data[0]["key"], self.node)
def onCompletion(self, req): """ Pass the rows received to the datatable. :param req: The network request that succeed. """ if not req in self._currentRequests: return self.loadedPages += 1 self.currentPage = self.loadedPages self._currentRequests.remove(req) self.actionBar.resetLoadingState() self.entryActionBar.resetLoadingState() self.tableBottomActionBar.resetLoadingState() data = NetworkService.decode(req) if data["structure"] is None: if self.table.getRowCount(): # We cant load any more results self.targetPage = self.loadedPages #reset targetpage to maximum self.requestingFinishedEvent.fire() self.table.setDataProvider(None) self.table.onTableChanged(None, self.table.getRowCount()) else: self.table["style"]["display"] = "none" self.emptyNotificationDiv.addClass("is-active") self.updateEmptyNotification() return self.table["style"]["display"] = "" self.emptyNotificationDiv.removeClass("is-active") self._structure = data["structure"] if not self._tableHeaderIsValid: if not self.columns: self.columns = [] for boneName, boneInfo in data["structure"]: if boneInfo["visible"]: self.columns.append(boneName) self.setFields(self.columns) if data["skellist"] and "cursor" in data.keys(): self._currentCursor = data["cursor"] self.table.setDataProvider(self) else: self.requestingFinishedEvent.fire() self.table.setDataProvider(None) self.table.extend(data["skellist"], writeToModel=True) #if targetPage higher than loadedPage, request next Batch if self.targetPage > self.loadedPages: self.onNextBatchNeeded()
def nextChunkComplete(self, req): answ = NetworkService.decode(req) if self.structure is None: self.structure = answ["structure"] if not answ["skellist"]: self.exportToFile() return self.data.extend(answ["skellist"]) self.nextChunk(answ["cursor"])
def _onRequestViewsAvailable(self, req): self.requestedViews = NetworkService.decode(req) self._buildViewPanes(self.requestedViews, register=True, requested=True) self.unlock() if not self.isExpanded: if self.mode == "normal": super(ListHandler, self).onClick() elif self.childPanes: self.childPanes[0].onClick()
def onRootNodesAvailable(self, req): res = NetworkService.decode(req) for node in res: option = html5.Option() option["value"] = node["key"] option.appendChild(html5.TextNode(node["name"])) if node["key"] == self.parent().parent().rootNode: option["selected"] = True self.appendChild(option) if len(self.children()) > 1: self.show() else: self.hide()
def onUserTestSuccess(self, req): """ We received a response from the server """ try: data = NetworkService.decode(req) except: self.showMessage() return if self.isCurrentlyFailed: if conf["currentUser"] != None and conf["currentUser"][ "key"] == data["values"]["key"]: self.hideMessage()
def onRequestSucceded(self, req): """ The NetworkRequest for a (sub)node finished. Create a new HierarchyItem for each entry received and add them to our view """ if not req in self._currentRequests: # Prevent inserting old (stale) data self.actionBar.resetLoadingState() return self._currentRequests.remove(req) data = NetworkService.decode(req) if req.node == self.rootNode: ol = self.entryFrame else: tmp = self.itemForKey(req.node) if not tmp: ol = self.entryFrame else: ol = tmp.ol for skel in data["skellist"]: if req.reqType == "leaf": hi = self.leafWidget(self.module, skel, data["structure"], self) else: hi = self.nodeWidget(self.module, skel, data["structure"], self) ol.appendChild(hi) if hi.data["key"] in self._expandedNodes: hi.toggleExpand() if not hi.childrenLoaded: hi.childrenLoaded = True self.loadNode(hi.data["key"]) ol.sortChildren(self.getChildKey) if not ol._children and ol != self.entryFrame: ol.parent().addClass("has-no-child") if data["skellist"] and data["cursor"]: self.loadNode(req.node, data["cursor"], reqType=req.reqType) self.actionBar.resetLoadingState()
def showErrorMsg(self, req=None, code=None): """ Removes all currently visible elements and displays an error message """ try: print(req.result) print(NetworkService.decode(req)) except: pass if code and (code==401 or code==403): txt = translate("Access denied!") else: txt = translate("An error occurred: {code}", code=code or 0) conf["mainWindow"].log("error", txt) if self.wasInitialRequest: conf["mainWindow"].removeWidget(self)
def onSkeyAvailable(self, req): """ Internal callback - the Security-Key is known. Only for core 2.x needed """ formData = html5.jseval("new FormData();") formData.append("file", req.file) if self.context: for k, v in self.context.items(): formData.append(k, v) if req.node and str(req.node) != "null": formData.append("node", req.node) formData.append("skey", NetworkService.decode(req)) self.xhr = html5.jseval("new XMLHttpRequest()") self.xhr.open("POST", req.destUrl) self.xhr.onload = self.onLoad self.xhr.upload.onprogress = self.onProgress self.xhr.send(formData)
def onPathRequestSucceded(self, req): """ Rebuild the displayed path-list according to request data """ answ = NetworkService.decode(req) skel = answ["values"] if skel["parententry"] and skel["parententry"] != skel["key"]: c = BreadcrumbNodeWidget(self.module, skel, [], self) NetworkService.request(self.module, "view/node/%s" % skel["parententry"], successHandler=self.onPathRequestSucceded) else: c = BreadcrumbNodeWidget(self.module, { "key": self.rootNode, "name": "root" }, [], self) c.addClass("is-rootnode") self.pathList.prependChild(c)
def onUploadUrlAvailable(self, req): """ Internal callback - the actual upload url (retrieved by calling /file/getUploadURL) is known. """ if conf["core.version"][0] == 3: params = NetworkService.decode(req)["values"] formData = html5.jseval("new FormData();") #if self.context: # for k, v in self.context.items(): # formData.append(k, v) #if req.node and str(req.node) != "null": # formData.append("node", req.node) for key, value in params["params"].items(): if key == "key": self.targetKey = value[:-16] # Truncate source/file.dat fileName = req.file.name value = value.replace("file.dat", fileName) formData.append(key, value) formData.append("file", req.file) self.xhr = html5.jseval("new XMLHttpRequest()") self.xhr.open("POST", params["url"]) self.xhr.onload = self.onLoad self.xhr.upload.onprogress = self.onProgress self.xhr.send(formData) else: r = NetworkService.request("", "/vi/skey", successHandler=self.onSkeyAvailable) r.file = req.file r.node = req.node r.destUrl = req.result
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
def onUploadAdded(self, req): self.responseValue = NetworkService.decode(req) DeferredCall(self.onSuccess, _delay=1000)
def onCurrentUserAvailable(self, req): data = NetworkService.decode(req) conf["currentUser"] = data["values"] self.update()
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)