def test_fromFile(): """ Ensure UITemplate creates a dictionary structure from an XML File correctly """ assert UITemplate.fromFile( "testTemplate.xml", formatType=UITemplate.XML) == EXPECTED_STRUCTURE #xml file assert UITemplate.fromFile( "testTemplate.shpaml", formatType=UITemplate.SHPAML) == EXPECTED_STRUCTURE #shpaml file
class ContentControl(PageControls.TemplateControl): template = UITemplate.fromFile("Pages/Documentation/Template.wui") def initUI(self, ui, request): ui.results.replaceWith(self.results) ui.document.replaceWith(self.document) ui.search.clientSide.focus() ui.search.clientSide.on("keyup", self.results.clientSide.get(timeout=500)) def setUIData(self, ui, request): """ Any data populating that occurs as a result of the data in the request should be done here. """ pass def processPost(self, ui, request): """ Any unique processing that needs to be done on a post should be done here. Note: There is corresponding process(Get|Delete|Put) methods. """ pass def validPost(self, ui, request): """ Any validation of post data should occur here: with true being returned only if the data is valid. Note: There is corresponding valid(Get|Delete|Put) methods. """ return True
def getTemplateGenerationTimes(): template = "div#AllProducts\n" templateElements = [] for product in Factory.products.keys(): template += " > %(product)s#test%(product)s\n" % {'product': product} template = UITemplate.fromSHPAML(template) startTime = time.time() for x in xrange(100): templateElement = TemplateElement(template=template, factory=Factory) templateElement.setScriptContainer(templateElement.addChildElement(ScriptContainer())) templateElements.append(templateElement) doneSection() results['templateInit'] = time.time() - startTime html = "" startTime = time.time() for templateElement in templateElements: html += templateElement.toHtml() doneSection() generationTime = (time.time() - startTime) results['templateToHtml'] = generationTime results['templateToHtmlSize'] = len(html) results['templateCreate'] = results['templateInit'] + results['templateToHtml']
def getTemplateGenerationTimes(): template = "div#AllProducts\n" templateElements = [] for product in Factory.products.keys(): template += " > %(product)s#test%(product)s\n" % {'product': product} template = UITemplate.fromSHPAML(template) startTime = time.time() for x in xrange(100): templateElement = TemplateElement(template=template, factory=Factory) templateElement.setScriptContainer( templateElement.addChildElement(ScriptContainer())) templateElements.append(templateElement) doneSection() results['templateInit'] = time.time() - startTime html = "" startTime = time.time() for templateElement in templateElements: html += templateElement.toHTML() doneSection() generationTime = (time.time() - startTime) results['templateToHtml'] = generationTime results['templateToHtmlSize'] = len(html) results[ 'templateCreate'] = results['templateInit'] + results['templateToHtml']
class ContentControl(PageControls.TemplateControl): template = UITemplate.fromFile(APP_DIR + "Template.wui") def initUI(self, ui, request): """ The initial setup of the interface (such as dynamically adding widgets that are not present in the view) should be done here. """ pass def setUIData(self, ui, request): """ Any data populating that occurs as a result of the data in the request should be done here. """ pass def processPost(self, ui, request): """ Any unique processing that needs to be done on a post should be done here. Note: There is corresponding process(Get|Delete|Put) methods. """ pass def validPost(self, ui, request): """ Any validation of post data should occur here: with true being returned only if the data is valid. Note: There is corresponding valid(Get|Delete|Put) methods. """ return True
class TemplateControl(ElementControl): """ Defines an ElementControl that is rendered from a WUI Template NOTE: When subclassing set the template attribute - aka template = UITemplate.fromFile("myFile.wui") """ template = UITemplate.Template("empty") def __init__(self, id=None, name=None, parent=None, parentHandler=None, initScripts=None, **kwargs): ElementControl.__init__(self, id, name, parent, parentHandler, initScripts, **kwargs) templateDefinition = TemplateElement(template=self.template, factory=self.elementFactory) for control in templateDefinition.allChildren(): if isinstance(control, PageControl): self.registerControl(control.__class__) def buildUI(self, request): return TemplateElement(template=self.template, factory=self.elementFactory)
def test_fromSHPAML(): """ Ensure UITemplate creates a dictionary structure from SHPAML correctly """ shpmal = """ container randomattribute=Hello childelement#SomeRandomId name=SomeRandomName > childishchildelement """ assert UITemplate.fromSHPAML(shpmal) == EXPECTED_STRUCTURE
def test_fromXML(): """ Ensure UITemplate creates a dictionary structure from XML correctly """ xml = """<container randomattribute="Hello"> <childelement id="SomeRandomId" name="SomeRandomName"> <childishchildelement /> </childelement> </container>""" assert UITemplate.fromXML(xml) == EXPECTED_STRUCTURE
def updatePreview(self, redrawTree=True): if not unicode(self.ui.wuiXML.toPlainText()) or unicode( self.ui.wuiXML.toPlainText()) == self.oldXML: return selected = app.focusWidget() try: self.structure = UITemplate.fromXML( unicode(self.ui.wuiXML.toPlainText())) structureCopy = copy.deepcopy(self.structure) self.highlightSelected(structureCopy) element = GuiBuilderConfig.Factory.buildFromTemplate(structureCopy) scriptContainer = GuiBuilderConfig.Factory.build('ScriptContainer') validTemplate = True except Exception as e: validTemplate = False self.ui.wuiXML.setText(self.oldXML) self.ui.wuiSHPAML.setText(self.oldSHPAML) self.ui.splitter.setStyleSheet( "#splitter{background-color:#ffc0c0;}") if selected: selected.setStyleSheet("background-color: #ffc0c0;") print("Exception thrown trying to render template: " + str(e)) if validTemplate: if redrawTree: self.ui.splitter.setStyleSheet( "#splitter{background-color:rgb(204, 204, 204);}") if selected: selected.setStyleSheet("") self.oldXML = unicode(self.ui.wuiXML.toPlainText()) self.oldSHPAML = unicode(self.ui.wuiSHPAML.toPlainText()) element.setScriptContainer(scriptContainer) element.addChildElement(scriptContainer) scrollPosition = self.ui.preview.page().mainFrame().scrollPosition( ) if scrollPosition: self.scrollPosition = QPoint(scrollPosition.x(), scrollPosition.y()) self.ui.preview.setHtml(self.html(element.toHTML()), QUrl.fromLocalFile(sharedFilesRoot + "/")) if redrawTree: self.updateTree() self.disconnect(self.ui.wuiSHPAML, SIGNAL("textChanged()"), self.updateXML) self.convertTreeToTemplate() self.connect(self.ui.wuiSHPAML, SIGNAL("textChanged()"), self.updateXML) self.updateSaveIndicator()
class MainControl(PageControls.TemplateControl): """ Defines how the frame of the page will appear, you can subclass this on a per page basis to change the frame. """ template = UITemplate.fromFile("WebBot/Page.wui") def initUI(self, ui, request): """ On initializing the main control frame per-request a content control is added which must be defined on a per-page basis to define the content of the page. """ ui.pageContents.replaceWith(self.contentControl)
class Document(PageControls.TemplateControl): template = UITemplate.fromFile("Pages/Documentation/Document.wui") def initUI(self, ui, request): openDocument = request.fields.get('load') if openDocument: ui.display.setVisibleElement(ui.openDocument) html = ui.openDocument.addChildElement(self.buildElement('straightHTML')) htmlDoc = pydoc.HTMLDoc() product = GuiBuilderConfig.Factory.build(openDocument.lower(), "", "") if product: html.html = htmlDoc.docclass(product.__class__) html.html = html.html.replace('href="', 'href="Documentation?load=').replace(".html", "")
def getBigTableGenerationTime(): template = UITemplate.fromSHPAML("> dom-table#bigTableTest") table = [dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10) for x in xrange(1000)] startTime = time.time() templateElement = TemplateElement(template=template, factory=Factory) for rowData in table: row = templateElement.bigTableTest.addChildElement(DOM.TR()) for data in rowData.itervalues(): row.addChildElement(DOM.TD()).addChildElement(TextNode(data)) doneSection() html = templateElement.toHtml() results['bigTable'] = time.time() - startTime results['bigTableSize'] = len(html)
class MainControl(PageControls.TemplateControl): template = UITemplate.fromFile("WebBot/Page.wui") def initUI(self, ui, request): ui.pageContents.replaceWith(self.contentControl) for pageName, page in PAGES: newLink = ui.pageLinks.addChildElement(Buttons.Link(href=page)) button = newLink.addChildElement(Buttons.ToggleButton(page + "Link", text=pageName)) if page in request.path: button.toggleOn() newLink.setDestination("Home") def setUIData(self, ui, request): ui.version.setText(WebElements.__version__)
def getBigTableGenerationTime(): template = UITemplate.fromSHPAML("> dom-table#bigTableTest") table = [ dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10) for x in xrange(1000) ] startTime = time.time() templateElement = TemplateElement(template=template, factory=Factory) for rowData in table: row = templateElement.bigTableTest.addChildElement(DOM.TR()) for data in itervalues(rowData): row.addChildElement(DOM.TD()).addChildElement(TextNode(data)) doneSection() html = templateElement.toHTML() results['bigTable'] = time.time() - startTime results['bigTableSize'] = len(html)
class ContentControl(PageControls.TemplateControl): template = UITemplate.fromFile("Pages/QuickStart/Template.wui") def initUI(self, ui, request): """ The initial setup of the interface (such as dynamically adding widgets that are not present in the view) should be done here. """ ui.helloWorldPython.code = HELLOWORLD_IN ui.helloWorldHTML.code = HELLOWORLD_OUT ui.combineExample.code = COMBINE_EXAMPLE ui.xmlTemplateExample.code = XML_TEMPLATE_EXAMPLE ui.shpamlTemplateExample.code = SHPAML_TEMPLATE_EXAMPLE ui.loadTemplateExample.code = LOAD_TEMPLATE_EXAMPLE ui.customElementExample.code = CUSTOM_ELEMENT_EXAMPLE ui.usingCustomElementsExample.code = USING_CUSTOM_ELEMENT_EXAMPLE ui.addingRowsExample.code = ADDING_ROWS_EXAMPLE ui.passingDataExample.code = PASSING_DATA_EXAMPLE ui.changeOrderExample.code = CHANGE_ORDER_EXAMPLE ui.myTable.addRows(EXAMPLE_TABLE_DATA) ui.myTable2.addRows(EXAMPLE_TABLE_DATA) ui.myTable2.columns = ('Email', 'Phone', 'Name') def setUIData(self, ui, request): """ Any data populating that occurs as a result of the data in the request should be done here. """ pass def processPost(self, ui, request): """ Any unique processing that needs to be done on a post should be done here. Note: There is corresponding process(Get|Delete|Put) methods. """ pass def validPost(self, ui, request): """ Any validation of post data should occur here: with true being returned only if the data is valid. Note: There is corresponding valid(Get|Delete|Put) methods. """ return True
def updatePreview(self, redrawTree=True): if not self.ui.wuiXML.toPlainText() or self.ui.wuiXML.toPlainText() == self.oldXML: return selected = app.focusWidget() try: self.structure = UITemplate.fromXML(unicode(self.ui.wuiXML.toPlainText())) structureCopy = copy.deepcopy(self.structure) self.highlightSelected(structureCopy) element = GuiBuilderConfig.Factory.buildFromTemplate(structureCopy) scriptContainer = GuiBuilderConfig.Factory.build('ScriptContainer') validTemplate = True except Exception as e: validTemplate = False self.ui.wuiXML.setText(self.oldXML) self.ui.wuiSHPAML.setText(self.oldSHPAML) self.ui.splitter.setStyleSheet("#splitter{background-color:#ffc0c0;}") if selected: selected.setStyleSheet("background-color: #ffc0c0;"); print("Exception thrown trying to render template: " + str(e)) if validTemplate: if redrawTree: self.ui.splitter.setStyleSheet("#splitter{background-color:rgb(204, 204, 204);}") if selected: selected.setStyleSheet(""); self.oldXML = self.ui.wuiXML.toPlainText() self.oldSHPAML = self.ui.wuiSHPAML.toPlainText() element.setScriptContainer(scriptContainer) element.addChildElement(scriptContainer) scrollPosition = self.ui.preview.page().mainFrame().scrollPosition() if scrollPosition: self.scrollPosition = QPoint(scrollPosition.x(), scrollPosition.y()) self.ui.preview.setHtml(self.html(element.toHTML()), QUrl.fromLocalFile(sharedFilesRoot + "/")) if redrawTree: self.updateTree() self.disconnect(self.ui.wuiSHPAML, SIGNAL("textChanged()"), self.updateXML) self.convertTreeToTemplate() self.connect(self.ui.wuiSHPAML, SIGNAL("textChanged()"), self.updateXML) self.updateSaveIndicator()
class Results(PageControls.TemplateControl): template = UITemplate.fromFile("Pages/Documentation/Results.wui") grabFields = ('search', ) def setUIData(self, ui, request): search = request.fields.get('search', '') if not search: usedProducts = [] for data in GuiBuilderConfig.sections: name = data['Name'] numberOfElements = len(data['Factory'].products) elements = data['Factory'].products.iteritems() section = ui.sections.addChildElement(self.buildElement("Accordion", name)) section.setLabel(name) section.toggle.attributes['tooltip'] = data['Factory'].__doc__ section.style['width'] = "100%" elementsContainer = section.addChildElement(self.buildElement("multiSelect")) elementsContainer.style['height'] = "%dpx" % (numberOfElements * 20) elementsContainer.style['width'] = "100%" elementsContainer.addJavascriptEvent('onchange', self.document.clientSide.get(load= ClientSide.Script("WebElements.selectedOption(this).value"))) for elementName, element in elements: if element in usedProducts: continue else: elementsContainer.addOption(elementName) ui.sections[0].addClass("First") ui.sections[-1].addClass("Last") return results = ui.sections.addChildElement(self.buildElement("multiSelect")) results.addClass("Results") results.style['width'] = "100%" results.addOptions([productName for productName in ELEMENTS if search.lower() in productName.lower()]) results.style['height'] = "%dpx" % (len(results.childElements) * 20) results.addJavascriptEvent('onchange', self.document.clientSide.get(load= ClientSide.Script("WebElements.selectedOption(this).value"))) return results
def __convertDictToNode(self, structure, node): if type(structure) in (str, unicode): structure = UITemplate.Template('textnode', properties=(('text', structure), )) create = structure.create if not create: return newNode = QTreeWidgetItem(node) newNode.setText(0, create) newNode.setIcon(0, self.elementIcon(create)) newNode.setText(1, structure.id) newNode.setText(2, structure.name) newNode.setText(3, structure.accessor) newNode.setText(4, self.newElementKey()) newNode.setExpanded( not self.collapsedMap.get(int(newNode.text(4)), False)) self.resizeTreeColumns() if self.selectedKey != None: if int(newNode.text(4)) == int(self.selectedKey): newNode.setSelected(True) self.ui.tree.setCurrentItem(newNode) self.ui.tree.scrollTo(self.ui.tree.currentIndex()) childElements = structure.childElements or () propertyDict = dict(structure.properties) propertyDict.update({ 'id': structure.id, 'name': structure.name, 'accessor': structure.accessor }) self.propertyMap[unicode(newNode.text(4))] = propertyDict for childElement in childElements: self.__convertDictToNode(childElement, newNode)
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' from WebElements import UITemplate EXPECTED_STRUCTURE = UITemplate.Template( 'container', properties=(("randomattribute", "Hello"), ), childElements=(UITemplate.Template( 'childelement', id="SomeRandomId", name="SomeRandomName", childElements=(UITemplate.Template("childishchildelement"), )), )) def test_fromFile(): """ Ensure UITemplate creates a dictionary structure from an XML File correctly """ assert UITemplate.fromFile( "testTemplate.xml", formatType=UITemplate.XML) == EXPECTED_STRUCTURE #xml file assert UITemplate.fromFile( "testTemplate.shpaml", formatType=UITemplate.SHPAML) == EXPECTED_STRUCTURE #shpaml file
class DynamicForm(RequestHandler): """ Defines the base dynamic form - a page made where any section can be updated independently from the rest """ template = UITemplate.fromSHPAML("> document") elementFactory = Factory formatted = False resourceFiles = ('js/WebBot.js', 'stylesheets/Site.css') if csrf: sharedFields = ('csrfmiddlewaretoken', ) def renderResponse(self, request): """ Override the response rendering to render the main document structure of the page """ document = self.elementFactory.buildFromTemplate(self.template) request.response.scripts = ScriptContainer() request.response.scripts.addScript("\n".join(self.initScripts)) document.setScriptContainer(request.response.scripts) document.setProperty('title', self.title(request)) document.addChildElement(ResourceFile()).setProperty( "file", self.favicon(request)) for resourceFile in set( self.requestResourceFiles(request) + self.resourceFiles): document.addChildElement(ResourceFile()).setProperty( "file", resourceFile) if csrf: token = document.body.addChildElement( HiddenValue('csrfmiddlewaretoken')) token.setValue(csrf(request.native)['csrf_token']) document.body += self.mainControl document.body += request.response.scripts self.modifyDocument(document, request) return document.toHTML(formatted=self.formatted, request=request) def modifyDocument(self, document, request): """ Override to change the structure of the base document """ pass def title(self, request): """ Returns the title of the page - by default this is the class name of the DynamicForm subclass override this method to change that """ return self.__class__.__name__ def favicon(self, request): """ Returns the title of the page - by default this is the class name of the DynamicForm subclass override this method to change that """ return "images/favicon.png" def requestResourceFiles(self, request): """ Returns the resource files that should be loaded with this page by request - override this to change """ return () class MainControl(PageControls.PageControl): """ Override this controller to define how the body of the page should render """ pass
class BasicTemplateControl(PageControls.TemplateControl): template = UITemplate.fromSHPAML("> label@label text=TemplateLabel")
class TemplateControl(ElementControl): """ Defines an ElementControl that is rendered from a WUI Template NOTE: When subclassing set the template attribute - aka template = UITemplate.fromFile("myFile.wui") """ template = UITemplate.Template("empty") def __init__(self, id=None, name=None, parent=None, parentHandler=None, initScripts=None, **kwargs): ElementControl.__init__(self, id, name, parent, parentHandler, initScripts, **kwargs) self.autoRegister = [] def _postConnections(self): """ After all connections are made we automatically cache replacement actions where possible. """ templateDefinition = TemplateElement(template=self.template, factory=self.elementFactory) for control in templateDefinition.allChildren(): if isinstance(control, PageControl): self.registerControl(control.__class__) if isinstance(control, PageControlPlacement): self.autoRegister.append( (control.id, self._findRelativeControl(control.control))) def _findRelativeControl(self, name): control = self if name.startswith(".."): control = control.parentHandler name = name[2:] while name.startswith("."): startFrom = control.parentHandler name = name[1:] for controlName in name.split("."): control = getattr(control, controlName) return control def buildUI(self, request): """ Builds an instance of the defined template """ return TemplateElement(template=self.template, factory=self.elementFactory) def _modifyUI(self, ui, request): """ Automatically replaces any defined controls that exist on the template. """ for controlAccessor, control in self.autoRegister: placement = getattr(ui, controlAccessor) if not placement or not placement.parent: continue placement.replaceWith(control)
def test_fromFile(): """ Ensure UITemplate creates a dictionary structure from an XML File correctly """ assert UITemplate.fromFile("testTemplate.xml", formatType=UITemplate.XML) == EXPECTED_STRUCTURE #xml file assert UITemplate.fromFile("testTemplate.shpaml", formatType=UITemplate.SHPAML) == EXPECTED_STRUCTURE #shpaml file