def __init__(self, text="", action=None): Label.__init__(self, text) self.action = action self.hoverColourChange = ColourChange(200) self.addAnimation(self.hoverColourChange) self.hoverColourChange.addKeyFrame(0, (0, 0, 0)) self.hoverColourChange.addKeyFrame(1, (100, 100, 100)) self.hoverColourChange.circular = True
class BrowserDetect: def onModuleLoad(self): self.l = Label() RootPanel().add(self.l) self.display() def display(self): self.l.setText("Browser not detected/supported")
def __init__(self, **kwargs): Renderer.__init__(self, **kwargs) self.label = Label(padding=self.padding, overflow=pango.EllipsizeMode.END) self.label.graphics = self.graphics self._prev_dict = {} self._editor = Entry()
def __init__(self, action=None): Label.__init__(self, "") self.focused = False self.hoverColourChange = ColourChange(200) self.addAnimation(self.hoverColourChange) self.hoverColourChange.addKeyFrame(0, (0, 0, 0)) self.hoverColourChange.addKeyFrame(1, (100, 100, 100)) self.hoverColourChange.circular = True self.clean = "" self.action = action
def welcome(self): """ Welcome screen. """ header = Label('Bienvenue', color=BLACK, size='huge') message = Label('Appuyer pour commencer', color=BLACK, size='medium') self.container.add(header) self.container.add(message) def onClick(position): """ Window click callback. """ self.container.remove(header) self.container.remove(message) self.window.onWindowClick = None self.prompt('Voulez vous configurer la connection internet ?', lambda r: self.wifi(r)) self.window.onWindowClick = onClick
def onModuleLoad(self): self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.remote_php = EchoServicePHP() self.remote_py = EchoServicePython() self.status=Label() self.text_area = TextArea() self.text_area.setText(r"{'Test'} [\"String\"]") self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) self.button_php = Button("Send to PHP Service", self) self.button_py = Button("Send to Python Service", self) buttons = HorizontalPanel() buttons.add(self.button_php) buttons.add(self.button_py) buttons.setSpacing(8) info = r"<h2>JSON-RPC Example</h2><p>This example demonstrates the calling of server services with <a href=\"http://json-rpc.org/\">JSON-RPC</a>." info += "<p>Enter some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives." panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(buttons) panel.add(self.status) RootPanel().add(panel)
def createSettings(self): """ Creates and configures widget for photo configuration. """ self.effects = self.camera.effects() self.currentEffect = 0 effectPanel = Panel(orientation='horizontal', padding=0) effectPanel.add(Image('resources/icons/filter.png')) container = Panel(orientation='horizontal', padding=10) prevEffect = Label('<', size='large') nextEffect = Label('>', size='large') self.effectLabel = Label(self.effects[self.currentEffect], size='large') container.add(prevEffect) container.add(self.effectLabel) container.add(nextEffect) effectPanel.add(container) self.sidebar.add(effectPanel)
def __init__(self, title, message, affirmative_label, decline_label="Cancel", width=500, modal=False): Dialog.__init__(self, title=title, width=width, modal=modal) scrollbox = ScrollArea(Label(markup=message, padding=5, overflow=pango.WrapMode.WORD), scroll_horizontal=False, border=0, margin=2, margin_right=3, height=150) affirmative = Button(affirmative_label, id="affirmative_button") affirmative.connect("on-click", self._on_button_click) decline = Button(decline_label, id="decline_button") decline.connect("on-click", self._on_button_click) self.box.contents = VBox([ scrollbox, HBox([HBox(), decline, affirmative], expand=False, padding=10) ])
def get_hero(): global heroes global labels_heroes h_values = heroes.values() h_sum = sum(h_values) r = rand(h_sum) current_sum = 0 for key, value in heroes.items(): current_sum += value if (r < current_sum): print(key, '->', current_sum, 'random:', r) hero_name = key # create hero object if (hero_name == 'knight'): hero = knight() Player.heroes_objects.append(hero) print('knight created!') Player.own_heroes.append( hero_name) # add hero to player's own list of heroes Player.own_heroes_cnt += 1 msg = Label(screen, str(hero_name), 100, 200 + Player.own_heroes_cnt * 25, 16, (241, 196, 15)) labels_heroes.append(msg) print('Now you have in collection:', Player.own_heroes) break
def setTemplateText(self, text): """ Set the template text; if the template is not HTML, a subclass could override this to pre-process the text into HTML before passing it to the default implementation. """ if self.allowEdit: self.originalText = text # If we have children, remove them all first since we are trashing their DOM for child in List(self.children): self.remove(child) DOM.setInnerHTML(self.getElement(), text) self.elementsById = {} self.links = [] self.metaTags = {} self.forms = [] self.metaTagList = [] # Make the ids unique and store a pointer to each named element for node in DOM.walkChildren(self.getElement()): #console.log("Passing node with name %s", node.nodeName) if node.nodeName == "META": name = node.getAttribute("name") content = node.getAttribute("content") console.log("Found meta %o name %s content %s", node, name, content) self.metaTags[name] = content self.metaTagList.append(node) elif node.nodeName == "BODY": self.body = node elif node.nodeName == "TITLE": self.title = DOM.getInnerText(node) elif node.nodeName == "FORM": self.forms.append(node) nodeId = DOM.getAttribute(node, "id") if nodeId: self.elementsById[nodeId] = node DOM.setAttribute(node, "id", self.id+":"+node.id) nodeHref = DOM.getAttribute(node, "href") if nodeHref: self.links.append(node) self.loaded = True if self.attached: self.attachWidgets() self.widgetsAttached = True if self.allowEdit: self.editor = None self.editButton = Label("edit "+unescape(self.templateName)) self.editButton.addStyleName("link") self.editButton.addStyleName("ContentPanelEditLink") self.editButton.addClickListener(EventDelegate("onClick", self, self.onEditContentClick)) ComplexPanel.insert(self, self.editButton, self.getElement(), len(self.children)) self.notifyLoadListeners()
def __init__(self, camera, size=(640, 480)): """ Default constructor. """ self.inCapture = False self.camera = camera self.window = Window(size=size) self.currentMode = PHOTO_MODE self.root = Panel(orientation='horizontal', ) self.sidebar = Panel(orientation='vertical', padding=10) self.mode = Panel(orientation='horizontal', padding=10) self.modeLabel = Label('Photo', size='large') self.bind()
def onError(self, html, statusCode): if statusCode == 404 and self.allowEdit: self.editor = None self.originalText = "" DOM.setInnerHTML(self.getElement(), '') self.editButton = Label("create "+unescape(self.templateName)) self.editButton.addStyleName("link") self.editButton.addStyleName("ContentPanelEditLink") self.editButton.addClickListener(EventDelegate("onClick", self, self.onEditContentClick)) ComplexPanel.insert(self, self.editButton, self.getElement(), len(self.children)) return
def __init__(self): # Grap all the methods of View super().__init__(self) # Label for outputs self.label=Label(frame=self.bounds.inset(0, 4, 0, 36), flex='WH') # Only some configuration for better look self.label.font=('Charter',12) self.label.text_color ='#ffffff' self.background_color = '#319b9b' self.add_subview(self.label) # This updates the view delay(self.update,0.3)
class JSONRPCExample: def onModuleLoad(self): self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.remote_php = EchoServicePHP() self.remote_py = EchoServicePython() self.status=Label() self.text_area = TextArea() self.text_area.setText(r"{'Test'} [\"String\"]") self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) self.button_php = Button("Send to PHP Service", self) self.button_py = Button("Send to Python Service", self) buttons = HorizontalPanel() buttons.add(self.button_php) buttons.add(self.button_py) buttons.setSpacing(8) info = r"<h2>JSON-RPC Example</h2><p>This example demonstrates the calling of server services with <a href=\"http://json-rpc.org/\">JSON-RPC</a>." info += "<p>Enter some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives." panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(buttons) panel.add(self.status) RootPanel().add(panel) def onClick(self, sender): self.status.setText(self.TEXT_WAITING) if sender == self.button_php: id = self.remote_php.echo(self.text_area.getText(), self) else: id = self.remote_py.echo(self.text_area.getText(), self) if id<0: self.status.setText(self.TEXT_ERROR) def onRemoteResponse(self, response, request_info): self.status.setText(response) def onRemoteError(self, code, message, request_info): self.status.setText("Server Error or Invalid Response: ERROR " + code + " - " + message)
def check_gem_clicked(gem, mouse_x, mouse_y): global label_gems_cnt if gem.rect.collidepoint(mouse_x, mouse_y): print('[Gem clicked]') if Player.gems > 0: Player.gems -= 1 label_gems_cnt = Label(screen, str(Player.gems), 150, 20, 16, (241, 196, 15)) get_hero() print('Opened a gem. Gems remained:', Player.gems) else: print('No more gems to open!')
def init(): global screen global enemy global gem global label_gems global label_gems_cnt global label_team print("init()") # randomizer init random.seed() # pygame init pygame.init() screen = pygame.display.set_mode((Set.d_width, Set.d_height)) # game objects init enemy = Enemy(screen) gem = Gem(screen) label_gems = Label(screen, 'Gems:', 100, 20, 16, (241, 196, 15)) label_gems_cnt = Label(screen, str(Player.gems), 150, 20, 16, (241, 196, 15)) label_team = Label(screen, 'TEAM', 100, 200, 16, (241, 196, 15))
def __init__(self, player, bounds, font): super().__init__(bounds, None) self.money_count = Label(Rect(0, 0, 500, 500), Color('yellow'), font, '-') self.append_child(self.money_count) self.wood_count = Label(Rect(105, 0, 500, 500), Color('brown'), font, '-') self.append_child(self.wood_count) self.meat_count = Label(Rect(220, 0, 500, 500), Color('red'), font, '-/-') self.append_child(self.meat_count) self.player = player
def onModuleLoad(self): self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.METHOD_ECHO = "Echo" self.METHOD_REVERSE = "Reverse" self.METHOD_UPPERCASE = "UPPERCASE" self.METHOD_LOWERCASE = "lowercase" self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, self.METHOD_UPPERCASE, self.METHOD_LOWERCASE] self.remote_php = EchoServicePHP() self.remote_py = EchoServicePython() self.status=Label() self.text_area = TextArea() self.text_area.setText(r"{'Test'} [\"String\"]") #self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) self.method_list = ListBox() #self.method_list.setMultipleSelect(True) self.method_list.setVisibleItemCount(1) for method in self.methods: self.method_list.addItem(method) self.method_list.setSelectedIndex(0) method_panel = HorizontalPanel() method_panel.add(HTML("Remote string method to call: ")) method_panel.add(self.method_list) method_panel.setSpacing(8) self.button_php = Button("Send to PHP Service", self) self.button_py = Button("Send to Python Service", self) buttons = HorizontalPanel() buttons.add(self.button_php) buttons.add(self.button_py) buttons.setSpacing(8) info = r"<h2>JSON-RPC Example</h2><p>This example demonstrates the calling of server services with <a href=\"http://json-rpc.org/\">JSON-RPC</a>." info += "<p>Enter some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives.</p>" panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(method_panel) panel.add(buttons) panel.add(self.status) RootPanel().add(panel)
def __init__(self): self.sStrings=[["foo0", "bar0", "baz0", "toto0", "tintin0"], ["foo1", "bar1", "baz1", "toto1", "tintin1"], ["foo2", "bar2", "baz2", "toto2", "tintin2"], ["foo3", "bar3", "baz3", "toto3", "tintin3"], ["foo4", "bar4", "baz4", "toto4", "tintin4"]] self.combo=ListBox() self.list=ListBox() self.echo=Label() self.combo.setVisibleItemCount(1) self.combo.addChangeListener(self) self.list.setVisibleItemCount(10) self.list.setMultipleSelect(True) for i in range(len(self.sStrings)): self.combo.addItem("List " + i) self.combo.setSelectedIndex(0) self.fillList(0) self.list.addChangeListener(self) horz = HorizontalPanel() horz.setVerticalAlignment(HasAlignment.ALIGN_TOP) horz.setSpacing(8) horz.add(self.combo) horz.add(self.list) panel = VerticalPanel() panel.setHorizontalAlignment(HasAlignment.ALIGN_LEFT) panel.add(horz) panel.add(self.echo) self.setWidget(panel) self.echoSelection()
def __init__(self, image): super().__init__(self) x, y = get_screen_size() if x > y: img_view = Label() img_view.text = 'Only in vertical position' img_view.frame = (0, 0, x, 15) else: y /= 4.4 img_view = ImageView() img_view.image = image img_view.frame = (0, 0, x, y) self.add_subview(img_view) self.frame = (0, 0, x, y)
def __init__(self, contact): # The popup's constructor's argument is a boolean specifying that it # auto-close itself when the user clicks outside of it. PopupPanel.__init__(self, True) inner = VerticalPanel() nameLabel = Label(contact.name) emailLabel = Label(contact.email) inner.add(nameLabel) inner.add(emailLabel) panel = HorizontalPanel() panel.setSpacing(4) panel.add(Image(contact.photo)) panel.add(inner) self.add(panel) self.setStyleName("mail-ContactPopup") nameLabel.setStyleName("mail-ContactPopupName") emailLabel.setStyleName("mail-ContactPopupEmail")
def onModuleLoad(self): b = Button("Click me", greet) RootPanel().add(b) if (1 or 0) and 0: RootPanel().add(Label("or FAILED")) else: RootPanel().add(Label("or OK")) if 0 & 1 == 0: RootPanel().add(Label("& OK")) else: RootPanel().add(Label("& FAILED")) if 1 | 1 != 1: RootPanel().add(Label("| FAILED")) else: RootPanel().add(Label("| OK"))
def prompt(self, question, callback): """ Prompt screen (Yes / No question only) """ header = Label(question, color=BLACK, size='medium') panel = Panel(orientation='horizontal', padding=20) def createPromptCallback(callback, answer): def delegate(): self.container.remove(header) self.container.remove(panel) callback(answer) return delegate yes = Label(' Oui ', color=WHITE, background=GRAY, size='medium') no = Label(' Non ', color=WHITE, background=GRAY, size='medium') yes.onClick = createPromptCallback(callback, True) no.onClick = createPromptCallback(callback, False) panel.add(yes) panel.add(no) self.container.add(header) self.container.add(panel) self.window.invalidate()
def create_options(self, options): self.drawed = False _y = self.y _x = self.x for opt in options: self.options.append({ "name": opt, "element": Label(text=opt, size=self.size, font_name=self.font_name, x=_x, y=_y, text_align=self.text_align, color=self.color) }) if self.horizontal: _x += self.offset else: _y += self.offset
def __init__(self): Sink.__init__(self) self.sStrings = [["foo0", "bar0", "baz0", "toto0", "tintin0"], ["foo1", "bar1", "baz1", "toto1", "tintin1"], ["foo2", "bar2", "baz2", "toto2", "tintin2"], ["foo3", "bar3", "baz3", "toto3", "tintin3"], ["foo4", "bar4", "baz4", "toto4", "tintin4"]] self.combo = ListBox() self.list = ListBox() self.echo = Label() self.combo.setVisibleItemCount(1) self.combo.addChangeListener(self) self.list.setVisibleItemCount(10) self.list.setMultipleSelect(True) for i in range(len(self.sStrings)): self.combo.addItem("List %d" % i) self.combo.setSelectedIndex(0) self.fillList(0) self.list.addChangeListener(self) horz = HorizontalPanel() horz.setVerticalAlignment(HasAlignment.ALIGN_TOP) horz.setSpacing(8) horz.add(self.combo) horz.add(self.list) panel = VerticalPanel() panel.setHorizontalAlignment(HasAlignment.ALIGN_LEFT) panel.add(horz) panel.add(self.echo) self.initWidget(panel) self.echoSelection()
class ResourceMenu(UIElement): def __init__(self, player, bounds, font): super().__init__(bounds, None) self.money_count = Label(Rect(0, 0, 500, 500), Color('yellow'), font, '-') self.append_child(self.money_count) self.wood_count = Label(Rect(105, 0, 500, 500), Color('brown'), font, '-') self.append_child(self.wood_count) self.meat_count = Label(Rect(220, 0, 500, 500), Color('red'), font, '-/-') self.append_child(self.meat_count) self.player = player def update(self, event): if super().update(event): return True self.update_values() def update_values(self): self.money_count.set_text(f'{self.player.money}') self.wood_count.set_text(f'{self.player.wood}') self.meat_count.set_text(f'{self.player.meat}/{self.player.max_meat}')
def __init__(self, text): Button.__init__(self, text) self.color = "#444" self.get_min_size = lambda: (0, Label.get_min_size(self)[1])
class TemplatePanel(ComplexPanel): """ Panel which allows you to attach or insert widgets into a pre-defined template. We don't do any caching of our own, since the browser will do caching for us, and probably more efficiently. """ templateRoot = "" """Set staticRoot to change the base path of all the templates that are loaded; templateRoot should have a trailing slash""" def __init__(self, templateName, allowEdit=False): ComplexPanel.__init__(self) self.loaded = False # Set after widgets are attached self.widgetsAttached = False self.id = None self.templateName = None self.title = None self.elementsById = {} self.metaTags = {} self.body = None self.links = [] self.forms = [] self.metaTagList = [] self.loadListeners = [] self.toAttach = [] self.toInsert = [] self.setElement(DOM.createDiv()) self.editor = None self.allowEdit = allowEdit if templateName: self.loadTemplate(templateName) def getTemplatePath(self, templateName): return self.templateRoot+'tpl/'+templateName+'.html' def loadTemplate(self, templateName): self.templateName = templateName self.id = templateName + str(hash(self)) self.httpReq = HTTPRequest() self.httpReq.asyncGet(self.getTemplatePath(templateName), TemplateLoader(self)) def getCurrentTemplate(self): """Return the template that is currently loaded, or is loading""" return self.templateName def isLoaded(self): """Return True if the template is finished loading""" return self.loaded def areWidgetsAttached(self): """Return True if the template is loaded and attachWidgets() has been called""" return self.widgetsAttached def setTemplateText(self, text): """ Set the template text; if the template is not HTML, a subclass could override this to pre-process the text into HTML before passing it to the default implementation. """ if self.allowEdit: self.originalText = text # If we have children, remove them all first since we are trashing their DOM for child in List(self.children): self.remove(child) DOM.setInnerHTML(self.getElement(), text) self.elementsById = {} self.links = [] self.metaTags = {} self.forms = [] self.metaTagList = [] # Make the ids unique and store a pointer to each named element for node in DOM.walkChildren(self.getElement()): #console.log("Passing node with name %s", node.nodeName) if node.nodeName == "META": name = node.getAttribute("name") content = node.getAttribute("content") console.log("Found meta %o name %s content %s", node, name, content) self.metaTags[name] = content self.metaTagList.append(node) elif node.nodeName == "BODY": self.body = node elif node.nodeName == "TITLE": self.title = DOM.getInnerText(node) elif node.nodeName == "FORM": self.forms.append(node) nodeId = DOM.getAttribute(node, "id") if nodeId: self.elementsById[nodeId] = node DOM.setAttribute(node, "id", self.id+":"+node.id) nodeHref = DOM.getAttribute(node, "href") if nodeHref: self.links.append(node) self.loaded = True if self.attached: self.attachWidgets() self.widgetsAttached = True if self.allowEdit: self.editor = None self.editButton = Label("edit "+unescape(self.templateName)) self.editButton.addStyleName("link") self.editButton.addStyleName("ContentPanelEditLink") self.editButton.addClickListener(EventDelegate("onClick", self, self.onEditContentClick)) ComplexPanel.insert(self, self.editButton, self.getElement(), len(self.children)) self.notifyLoadListeners() def onError(self, html, statusCode): if statusCode == 404 and self.allowEdit: self.editor = None self.originalText = "" DOM.setInnerHTML(self.getElement(), '') self.editButton = Label("create "+unescape(self.templateName)) self.editButton.addStyleName("link") self.editButton.addStyleName("ContentPanelEditLink") self.editButton.addClickListener(EventDelegate("onClick", self, self.onEditContentClick)) ComplexPanel.insert(self, self.editButton, self.getElement(), len(self.children)) return # Show the page we got in an iframe, which will hopefully show the error better than we can. # DOM.setInnerHTML(self.getElement(), '<iframe src="'+self.getTemplatePath(self.templateName)+'"/>') def onTimeout(self, text): self.onError("Page loading timed out: "+text) def getElementsById(self): """Return a dict mapping an id to an element with that id inside the template; useful for post-processing""" return self.elementsById def getLinks(self): """Return a list of all the A HREF= elements found in the template.""" return self.links def getForms(self): """Return a list of all the FORM elements found in the template.""" return self.forms def onAttach(self): if not self.attached: SimplePanel.onAttach(self) if self.loaded and not self.widgetsAttached: self.attachWidgets() self.widgetsAttached = True def attachWidgets(self): """ Attach and insert widgets into the DOM now that it has been loaded. If any widgets were attached before loading, they will have been queued and the default implementation will attach them. Override this in subclasses to attach your own widgets after loading. """ for attach in self.toAttach: self.attach(attach.name, attach.widget) for insert in self.toInsert: self.insert(insert.name, insert.widget) def getElementById(self, id): return self.elementsById[id] def insert(self, id, widget): """ Insert a widget into the element with the given id, at the end of its children. """ if not self.loaded: self.toInsert.append(PendingAttachOrInsert(id, widget)) else: element = self.getElementById(id) if element: self.adopt(widget, element) self.children.append(widget) else: console.error("Page error: No such element "+id) return widget def attachToElement(self, element, widget): events = DOM.getEventsSunk(widget.getElement()) widget.unsinkEvents(events) widget.setElement(element) widget.sinkEvents(events) self.adopt(widget, None) self.children.append(widget) def replaceElement(self, element, widget): """ Replace an existing element with the given widget """ DOM.getParent(element).replaceChild(widget.getElement(), element) self.adopt(widget, None) self.children.append(widget) def attach(self, id, widget): """ Attach a widget onto the element with the given id; the element currently associated with the widget is discarded. """ if not self.loaded: self.toAttach.append(PendingAttachOrInsert(id, widget)) else: element = self.getElementById(id) if element: self.attachToElement(element, widget) else: console.error("Page error: No such element "+id) return widget def getMeta(self, name): """ Get the value of a meta-variable found in the template, or None if no meta tags were found with the given name. """ return self.metaTags.get(name) def getTitle(self): """ Return a user-friendly title for the page """ if self.title: return self.title else: return self.templateName def addLoadListener(self, listener): """ The listener should be a function or an object implementing onTemplateLoaded. It will be called this TemplatePanel instance after the template has been loaded and after attachWidgets() is called. """ self.loadListeners.append(listener) def removeLoadListener(self, listener): self.loadListeners.remove(listener) def notifyLoadListeners(self): for listener in self.loadListeners: if listener.onTemplateLoaded: listener.onTemplateLoaded(self) else: listener(self) def onEditContentClick(self, sender): if self.editor: editor = self.editor self.editor = None ComplexPanel.remove(self, editor) self.editButton.setText("edit "+unescape(self.templateName)) else: self.editor = RichTextEditor(self.originalText) self.editor.addSaveListener(self) ComplexPanel.insert(self, self.editor, self.getElement(), len(self.children)) self.editButton.setText("close editor") def getTemplateSaveUrl(self, templateName): """ Get the URL to post a template to when it is saved in the editor. """ return self.getTemplatePath(templateName) def saveTemplateText(self, html): """ Save the text. This method can be overridden to use a different save method. The default is to POST to the template save URL, passing a single parameter "content" with the html string. To change the target of the POST, override getTemplateSaveUrl(). To preprocess the html, override this method in a subclass and perform processing there. """ HTTPRequest().asyncPost(self.getTemplateSaveUrl(self.templateName), "content="+encodeURIComponent(html), ContentSaveHandler(self)) def onSave(self, sender): """ Called when the user clicks save in the content editor. """ html = self.editor.getHTML() self.saveTemplateText(html) def onSaveComplete(self): """ Called when the template was successfully POSTed to the server; it reloads the template. Subclasses which don't use the default method of saving may want to call this after they successfully save the template. """ self.loadTemplate(self.templateName)
def __init__(self, markup="", size=16, background_color="#999", **kwargs): Label.__init__(self, markup=markup, size=size, background_color=background_color, **kwargs)
class JSONRPCExample: def onModuleLoad(self): self.TEXT_WAITING = "Waiting for response..." self.TEXT_ERROR = "Server Error" self.METHOD_ECHO = "Echo" self.METHOD_REVERSE = "Reverse" self.METHOD_UPPERCASE = "UPPERCASE" self.METHOD_LOWERCASE = "lowercase" self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, self.METHOD_UPPERCASE, self.METHOD_LOWERCASE] self.remote_php = EchoServicePHP() self.remote_py = EchoServicePython() self.status=Label() self.text_area = TextArea() self.text_area.setText(r"{'Test'} [\"String\"]") #self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) self.method_list = ListBox() #self.method_list.setMultipleSelect(True) self.method_list.setVisibleItemCount(1) for method in self.methods: self.method_list.addItem(method) self.method_list.setSelectedIndex(0) method_panel = HorizontalPanel() method_panel.add(HTML("Remote string method to call: ")) method_panel.add(self.method_list) method_panel.setSpacing(8) self.button_php = Button("Send to PHP Service", self) self.button_py = Button("Send to Python Service", self) buttons = HorizontalPanel() buttons.add(self.button_php) buttons.add(self.button_py) buttons.setSpacing(8) info = r"<h2>JSON-RPC Example</h2><p>This example demonstrates the calling of server services with <a href=\"http://json-rpc.org/\">JSON-RPC</a>." info += "<p>Enter some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives.</p>" panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(method_panel) panel.add(buttons) panel.add(self.status) RootPanel().add(panel) def onClick(self, sender): self.status.setText(self.TEXT_WAITING) method = self.methods[self.method_list.getSelectedIndex()] text = self.text_area.getText() print repr(text) # demonstrate proxy & callMethod() if sender == self.button_php: if method == self.METHOD_ECHO: id = self.remote_php.echo(text, self) elif method == self.METHOD_REVERSE: id = self.remote_php.callMethod("reverse", [text], self) elif method == self.METHOD_UPPERCASE: id = self.remote_php.uppercase(text, self) elif method == self.METHOD_LOWERCASE: id = self.remote_php.lowercase(text, self) else: if method == self.METHOD_ECHO: id = self.remote_py.echo(text, self) elif method == self.METHOD_REVERSE: id = self.remote_py.reverse(text, self) elif method == self.METHOD_UPPERCASE: id = self.remote_py.uppercase(text, self) elif method == self.METHOD_LOWERCASE: id = self.remote_py.lowercase(text, self) if id<0: self.status.setText(self.TEXT_ERROR) def onRemoteResponse(self, response, request_info): self.status.setText(response) def onRemoteError(self, code, message, request_info): self.status.setText("Server Error or Invalid Response: ERROR " + code + " - " + message)
class LabelRenderer(Renderer): padding = 5 expand = True color = "#333" #: font color color_current = "#fff" #: font color when the row is selected color_disabled = "#aaa" #: color of the text when item is disabled color_disabled_current = "#fff" #: selected row font color when item is disabled def __init__(self, **kwargs): Renderer.__init__(self, **kwargs) self.label = Label(padding=self.padding, overflow=pango.EllipsizeMode.END) self.label.graphics = self.graphics self._prev_dict = {} self._editor = Entry() def __setattr__(self, name, val): Widget.__setattr__(self, name, val) if name.startswith("padding") and hasattr(self, "label"): setattr(self.label, name, val) def get_min_size(self, row): return max(self.min_width or 0, 10), max(self.min_height or 0, self.label.vertical_padding + 15) def get_mouse_cursor(self): if self.editable: return gdk.CursorType.XTERM return False def show_editor(self, target, cell, event=None): if not self.editable: return self._target, self._cell = target, cell target.add_child(self._editor) self._editor.x, self._editor.y = cell["x"], cell["y"] self._editor.alloc_w, self._editor.alloc_h = cell["width"], cell["height"] self._editor.text = cell["data"] if event: event.x, event.y = self._editor.from_scene_coords(event.x, event.y) self._editor._Entry__on_mouse_down(self._editor, event) self._target = target self._editor.grab_focus() def hide_editor(self): if self._target: self._target.remove_child(self._editor) self._target.rows[self._cell["row"]][self._cell["col"]] = self._editor.text self._target = self._cell = None def set_data(self, data): # apply data to the renderer self._prev_dict = {} if isinstance(data, dict): for key, val in data.iteritems(): self._prev_dict[key] = getattr(self.label, key, "") # store original state setattr(self.label, key, val) else: self.label.text = data def restore_data(self): # restore renderer's data representation to the original state for key, val in self._prev_dict.iteritems(): setattr(self.label, key, val) def render(self, context, w, h, data, state, enabled=True): self.label.alloc_w = w if enabled: self.label.color = self.color_current if state == "current" else self.color else: self.label.color = self.color_disabled_current if state == "current" else self.color_disabled context.save() context.translate((w - self.label.width) * self.x_align, (h - self.label.height) * self.y_align) self.label._draw(context) context.restore()
def onModuleLoad(self): self.l = Label() RootPanel().add(self.l) self.display()
class LabelRenderer(Renderer): padding = 5 expand = True color = "#333" #: font color color_current = "#fff" #: font color when the row is selected color_disabled = "#aaa" #: color of the text when item is disabled color_disabled_current = "#fff" #: selected row font color when item is disabled def __init__(self, **kwargs): Renderer.__init__(self, **kwargs) self.label = Label(padding=self.padding, overflow=pango.EllipsizeMode.END) self.label.graphics = self.graphics self._prev_dict = {} self._editor = Entry() def __setattr__(self, name, val): Widget.__setattr__(self, name, val) if name.startswith("padding") and hasattr(self, "label"): setattr(self.label, name, val) def get_min_size(self, row): return max(self.min_width or 0, 10), max(self.min_height or 0, self.label.vertical_padding + 15) def get_mouse_cursor(self): if self.editable: return gdk.CursorType.XTERM return False def show_editor(self, target, cell, event=None): if not self.editable: return self._target, self._cell = target, cell target.add_child(self._editor) self._editor.x, self._editor.y = cell['x'], cell['y'] self._editor.alloc_w, self._editor.alloc_h = cell['width'], cell[ 'height'] self._editor.text = cell['data'] if event: event.x, event.y = self._editor.from_scene_coords(event.x, event.y) self._editor._Entry__on_mouse_down(self._editor, event) self._target = target self._editor.grab_focus() def hide_editor(self): if self._target: self._target.remove_child(self._editor) self._target.rows[self._cell['row']][ self._cell['col']] = self._editor.text self._target = self._cell = None def set_data(self, data): # apply data to the renderer self._prev_dict = {} if isinstance(data, dict): for key, val in data.iteritems(): self._prev_dict[key] = getattr(self.label, key, "") #store original state setattr(self.label, key, val) else: self.label.text = data def restore_data(self): # restore renderer's data representation to the original state for key, val in self._prev_dict.iteritems(): setattr(self.label, key, val) def render(self, context, w, h, data, state, enabled=True): self.label.alloc_w = w if enabled: self.label.color = self.color_current if state == "current" else self.color else: self.label.color = self.color_disabled_current if state == "current" else self.color_disabled context.save() context.translate((w - self.label.width) * self.x_align, (h - self.label.height) * self.y_align) self.label._draw(context) context.restore()
def __init__(self, markup="", size=16, background_color = "#999", **kwargs): Label.__init__(self, markup=markup, size=size, background_color=background_color, **kwargs)
class Lists(Sink): def __init__(self): Sink.__init__(self) self.sStrings = [["foo0", "bar0", "baz0", "toto0", "tintin0"], ["foo1", "bar1", "baz1", "toto1", "tintin1"], ["foo2", "bar2", "baz2", "toto2", "tintin2"], ["foo3", "bar3", "baz3", "toto3", "tintin3"], ["foo4", "bar4", "baz4", "toto4", "tintin4"]] self.combo = ListBox() self.list = ListBox() self.echo = Label() self.combo.setVisibleItemCount(1) self.combo.addChangeListener(self) self.list.setVisibleItemCount(10) self.list.setMultipleSelect(True) for i in range(len(self.sStrings)): self.combo.addItem("List %d" % i) self.combo.setSelectedIndex(0) self.fillList(0) self.list.addChangeListener(self) horz = HorizontalPanel() horz.setVerticalAlignment(HasAlignment.ALIGN_TOP) horz.setSpacing(8) horz.add(self.combo) horz.add(self.list) panel = VerticalPanel() panel.setHorizontalAlignment(HasAlignment.ALIGN_LEFT) panel.add(horz) panel.add(self.echo) self.initWidget(panel) self.echoSelection() def onChange(self, sender): print sender, self.list, self.combo if sender is self.combo: print "fill list" self.fillList(self.combo.getSelectedIndex()) elif sender is self.list: print "echo " self.echoSelection() else: print "oops" def onShow(self): pass def fillList(self, idx): self.list.clear() strings = self.sStrings[idx] for i in range(len(strings)): self.list.addItem(strings[i]) self.echoSelection() def echoSelection(self): msg = "Selected items: " print msg, self.list.getItemCount() for i in range(self.list.getItemCount()): if self.list.isItemSelected(i): msg += "%d" % i + self.list.getItemText(i) + " " self.echo.setText(msg)
class Lists(Sink): def __init__(self): self.sStrings=[["foo0", "bar0", "baz0", "toto0", "tintin0"], ["foo1", "bar1", "baz1", "toto1", "tintin1"], ["foo2", "bar2", "baz2", "toto2", "tintin2"], ["foo3", "bar3", "baz3", "toto3", "tintin3"], ["foo4", "bar4", "baz4", "toto4", "tintin4"]] self.combo=ListBox() self.list=ListBox() self.echo=Label() self.combo.setVisibleItemCount(1) self.combo.addChangeListener(self) self.list.setVisibleItemCount(10) self.list.setMultipleSelect(True) for i in range(len(self.sStrings)): self.combo.addItem("List " + i) self.combo.setSelectedIndex(0) self.fillList(0) self.list.addChangeListener(self) horz = HorizontalPanel() horz.setVerticalAlignment(HasAlignment.ALIGN_TOP) horz.setSpacing(8) horz.add(self.combo) horz.add(self.list) panel = VerticalPanel() panel.setHorizontalAlignment(HasAlignment.ALIGN_LEFT) panel.add(horz) panel.add(self.echo) self.setWidget(panel) self.echoSelection() def onChange(self, sender): if sender == self.combo: self.fillList(self.combo.getSelectedIndex()) elif sender == self.list: self.echoSelection() def onShow(self): pass def fillList(self, idx): self.list.clear() strings = self.sStrings[idx] for i in range(len(strings)): self.list.addItem(strings[i]) self.echoSelection() def echoSelection(self): msg = "Selected items: " for i in range(self.list.getItemCount()): if self.list.isItemSelected(i): msg += self.list.getItemText(i) + " " self.echo.setText(msg)