def main(test_gen_out): pyjd.setup("public/uitest.html") t = RunTests(test_gen_out) t.add(LabelTest) t.add(EventTest) t.add(DOMTest) pyjd.run()
def onLogin(self, sender, username, logged_in): if logged_in: self.logged_in(username) else: self.logged_out() def logged_out(self): self.login_username = None self.loginpanel.setStatus("") # reset status display if self.maindisplay.center is not None: self.maindisplay.remove(self.afterloginpanel.getPanel()) self.maindisplay.add(self.loginpanel.getPanel(), DockPanel.CENTER) def logged_in(self, username): self.login_username = username if self.maindisplay.center is not None: self.maindisplay.remove(self.loginpanel.getPanel()) self.maindisplay.add(self.afterloginpanel.getPanel(), DockPanel.CENTER) #====================================================== if __name__ == '__main__': # for pyjd, set up a web server and load the HTML from there: # this convinces the browser engine that the AJAX will be loaded # from the same URI base as the URL, it's all a bit messy... pyjd.setup("http://127.0.0.1:8080/proxiedpyjamas/gui/public/GNUmedWebPyJD.html") app = gmTopLevelLayer() app.onModuleLoad() pyjd.run()
else: if AsyncUpload.is_old_browser(): Window.alert("Hmmm, your browser doesn't support this.") else: el = self.field.getElement() files = getattr(el, 'files') #TODO implement loop for multiple file uploads file = JS("@{{files}}[0]") #otherwise pyjs thinks it's a string? AsyncUpload.asyncUpload(self.url, file, self) def onload(self, status): self.progress.setText('100%') def onerror(self, status): Window.alert("oh noes we got an " + str(status)) def onprogress(self, loaded, total): if self.progress.getText() == '100%': return progress = (loaded / total) p = int(progress * 100) self.progress.setText(str(p) + '%') if __name__ == '__main__': #Well it makes no sense whatsoever to run this as desktop!! pyjd.setup("public/Upload.html") app = Upload() app.onModuleLoad() pyjd.run()
txt = self.focussed and 'yes. now press keys' or 'no. keys fail now' self.add(HTML('focus: %s' % txt)) def onKeyDown(self, sender, keyCode, modifiers = None): self.add(HTML('keyDOWN: %d' % keyCode)) def heightset(fred): DOM.setStyleAttribute(doc().body, 'height', '100%') def marginset(fred): DOM.setStyleAttribute(doc().body, 'margin', '0px') if __name__ == '__main__': pyjd.setup("public/ClickableRootPanel.html") bh = Button("Click me to set body height to 100%", heightset, StyleName='teststyle') b = Button("Click me to set body margin to 0", marginset, StyleName='teststyle') h = HTML("<b>Hello World</b> - watch for focus highlighting after click", StyleName='teststyle') panel = FocusPanel(Widget=h) gp = RootPanelListener(panel, StyleName='rootstyle') # as this is replacing the 'normal' usage of RootPanel(), # it is necessary to add this in 'by hand' so that the # window-close notification is 'hooked into', and so when # the browser window is closed, cleanups (onDetach) will
if code != 0: self.status.setText("HTTP error %d: %s" % (code, message)) else: code = errobj['code'] self.status.setText("JSONRPC Error %s: %s" % (code, message)) class EchoServicePHP(JSONProxy): def __init__(self): JSONProxy.__init__(self, "services/EchoService.php", ["echo", "reverse", "uppercase", "lowercase", "nonexistant"]) class EchoServicePython(JSONProxy): def __init__(self): JSONProxy.__init__(self, "services/EchoService.py", ["echo", "reverse", "uppercase", "lowercase", "nonexistant"]) if __name__ == '__main__': # for pyjd, set up a web server and load the HTML from there: # this convinces the browser engine that the AJAX will be loaded # from the same URI base as the URL, it's all a bit messy... # Use the second pyjd.setup if you're using apache-php locally # as described in the README pyjd.setup("http://127.0.0.1:8000/public/JSONRPCExample.html") #pyjd.setup("http://127.0.0.1/examples/jsonrpc/public/JSONRPCExample.html") app = JSONRPCExample() app.onModuleLoad() pyjd.run()
if not isinstance(fields, list): fields = [fields] block = false for j in fields: field = memory.get_field_info(j) if str(field[1]) == "AMS_READ": if j == "Publish Block": if field[4] == "true": block = true else: subtree.addItem(j + " = " + str(field[4])) else: if j == "Block" and not block: continue PN = HorizontalPanel() PN.add(Label(Text=j + " =")) tb = TextBox(Text=str(field[4])) boxes[tb] = [i, j, memory] tb.addChangeListener(self.textboxlistener) PN.add(tb) subtree.addItem(PN) self.tree.addItem(subtree) self.panel.add(self.tree) if __name__ == "__main__": pyjd.setup() app = AMSSnoopObjects() app.onModuleLoad() pyjd.run()
def loadPageList(self): HTTPRequest().asyncGet("sidebar.html", PageLoader(self, "sidebar", "contents")) HTTPRequest().asyncGet("header.html", PageLoader(self, "header", "contents")) HTTPRequest().asyncGet("footer.html", PageLoader(self, "footer", "contents")) HTTPRequest().asyncGet("contents.txt", PageListLoader(self, "contents")) def loadPages(self, pages, purpose): if purpose == 'contents': self.pages = {} self.page_list = pages elif purpose == 'faq': self.faq_pages = {} self.faq_list = pages for l in pages: title = l[0] desc = l[1] HTTPRequest().asyncGet(desc, PageLoader(self, title, purpose)) if __name__ == '__main__': pyjd.setup("http://127.0.0.1/pyjamas/doc/pyjs_site/public/index.html") app = Tabs() app.onModuleLoad() pyjd.run()
grid.setWidget(2, 0, CaptionPanel('Subclassing Timer() (<em>again</em>)', ptb, StyleName='left')) grid.setWidget(2, 1, ptb.box) grid.setWidget(2, 2, HTML('''This is the same as the previous example and is here to demonstrate creating multiple timers (each with their own state) which is difficult to do without sublcassing''', StyleName='desc')) # random color randomcolor = RandomColor() grid.setWidget(3, 0, CaptionPanel('Using onTimer()', randomcolor.hpanel, StyleName='left')) grid.setWidget(3, 1, randomcolor.colorpanel) grid.setWidget(3, 2, HTML(RandomColor.__doc__, StyleName='desc')) # add it all to the root panel RootPanel().add(grid) # kickstart the slider handle (see above concerning a # potential bug) randomcolor.initialize() def onModuleLoad(): timerdemo() if __name__ == '__main__': pyjd.setup("public/timerdemo.html") onModuleLoad() pyjd.run()
self.toHtml() elif wid == self.m_select: self.selectNodes(True) elif wid == self.m_cursor: self.selectNodes(False) def toHtml(self): self.m_tb.setHtml(self.m_html.getText()) def selectNodes(self, fullSel): startNode = int(self.m_startNode.getText()) startOffset = int(self.m_startOffset.getText()) if fullSel: endNode = int(self.m_endNode.getText()) endOffset = int(self.m_endOffset.getText()) else: endNode = startNode endOffset = startOffset self.m_tb.selectNodes(startNode, startOffset, endNode, endOffset) if __name__ == '__main__': pyjd.setup("public/SelectionTest.html") app = SelectionTest() app.onModuleLoad() pyjd.run()
self.curSink = info.getInstance() self.sink_list.setSinkSelection(info.getName()) self.description.setHTML(info.getDescription()) if (affectHistory): History.newItem(info.getName()) self.sinkContainer.add(self.curSink, DockPanel.CENTER) self.sinkContainer.setCellWidth(self.curSink, "100%") self.sinkContainer.setCellHeight(self.curSink, "100%") self.sinkContainer.setCellVerticalAlignment(self.curSink, HasAlignment.ALIGN_TOP) self.curSink.onShow() def loadSinks(self): self.sink_list.addSink(IntroTab.init()) self.sink_list.addSink(TooltipTab.init()) self.sink_list.addSink(AutoCompleteTab.init()) self.sink_list.addSink(Canvas2DTab.init()) self.sink_list.addSink(CanvasTab.init()) def showIntro(self): self.show(self.sink_list.find("Intro")) if __name__ == '__main__': pyjd.setup("./public/AddonsGallery.html") app = AddonsGallery() app.onModuleLoad() pyjd.run()
if self.page < self.min_page: self.page = self.min_page elif self.page > self.max_page: self.page = self.max_page total_pages = (self.max_page - self.min_page) + 1 self.g.setHTML(0, 4, "<b>page %d of %d</b>" % (self.page, total_pages)) if self.page >= self.max_page: self.addb.setEnabled(False) else: self.addb.setEnabled(True) if self.page <= self.min_page: self.subb.setEnabled(False) else: self.subb.setEnabled(True) for y in range(1, 5): for x in range(5): self.g.setText(y, x, "%d (%d,%d)" % (self.page, x, y)) def AppInit(): return GridWidget() if __name__ == '__main__': pyjd.setup("./GridTest.html") g = GridWidget() RootPanel().add(g) pyjd.run()
""" Event handler for the upload form. """ def onClick(self, sender): self.form.submit() def onSubmitComplete(self, event): """ When the form submission is successfully completed, this event is fired. Assuming the service returned a response of type text/plain, we can get the result text here (see the FormPanel documentation for further explanation). """ # Window.alert(event.getResults()) pass def onSubmit(self, event): """ This event is fired just before the form is submitted. We can take this opportunity to perform validation. """ # if (self.upload.getFilename().length == 0): # Window.alert("The file field must not be empty") # event.setCancelled(True) pass if __name__ == '__main__': pyjd.setup("http://localhost:8080/content/OpenPowerSystem.html") app = OpenPowerSystem() pyjd.run() # dummy in pyjs # EOF -------------------------------------------------------------------------
import pyjd # this is dummy in pyjs. from pyjamas.ui.RootPanel import RootPanel from pyjamas.ui.Button import Button from pyjamas.ui.HTML import HTML from pyjamas.ui.Label import Label from pyjamas import Window def greet(fred): fred.setText("No, really click me!") Window.alert("Hello, AJAX!") if __name__ == '__main__': pyjd.setup("public/Hello.html?fred=foo#me") b = Button("Click me", greet, StyleName='teststyle') h = HTML("<b>Hello World</b> (html)", StyleName='teststyle') l = Label("Hello World (label)", StyleName='teststyle') base = HTML("Hello from %s" % pygwt.getModuleBaseURL(), StyleName='teststyle') RootPanel().add(b) RootPanel().add(h) RootPanel().add(l) RootPanel().add(base) pyjd.run()
# Crossword Puzzle Loader Demo # Copyright (C) 2011 Camille Dalmeras # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pyjd from pyjamas.ui.RootPanel import RootPanel from pyjamas.ui.InputBox import InputBox if __name__ == '__main__': pyjd.setup("./public/inputbox.html") app = InputBox(MatchPattern="^[0-9,A-Z,:]*$") app.setMaxLength(20) app.setText("hello") RootPanel("keypad").add(app) pyjd.run()
def onModuleLoad(self): self.vertpanel = VerticalSplitPanel() self.vertpanel.setSize("500px", "350px") self.vertpanel.setSplitPosition("30%") self.vertpanel.setStyleAttribute("background", "red") self.horzpanel = HorizontalSplitPanel() self.horzpanel.setSize("500px", "350px") self.horzpanel.setSplitPosition("50%") self.horzpanel.setStyleAttribute("background", "yellow") randomText = "" for i in range(200): randomText += "hello %d " % i self.vertpanel.setTopWidget(HTML(randomText)) self.vertpanel.setBottomWidget(HTML(randomText)) self.horzpanel.setLeftWidget(HTML(randomText)) self.horzpanel.setRightWidget(HTML(randomText)) RootPanel().add(self.vertpanel) RootPanel().add(self.horzpanel) if __name__ == '__main__': pyjd.setup("./public/SplitPanel.html") app = SplitPanel() app.onModuleLoad() pyjd.run()
import pyjd # this is dummy in pyjs. import pygwt from Index import Index if __name__ == '__main__': pyjd.setup("public/Main.html") app = Index() app.onModuleLoad() pyjd.run()
self.fTabs = DecoratedTabPanel(Size=("600px", "100%")) self.fTabs.add(self.createImage("rembrandt/JohannesElison.jpg"), red, True) self.fTabs.add(self.createImage("rembrandt/SelfPortrait1640.jpg"), green, True) self.fTabs.add(self.createImage("rembrandt/LaMarcheNocturne.jpg"), "1642") self.fTabs.add(self.createImage("rembrandt/TheReturnOfTheProdigalSon.jpg"), "1662") self.fTabs.selectTab(0) dp = DecoratorTitledPanel("Tabs", "bluetitle", "bluetitleicon", ["bluetop", "bluetop2", "bluemiddle", "bluebottom"]) dp.add(self.fTabs) RootPanel().add(dp) def createImage(self, imageUrl): image = Image(imageUrl) image.setStyleName("ks-images-Image") p = VerticalPanel() p.setHorizontalAlignment(HasAlignment.ALIGN_CENTER) p.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE) p.add(image) return p if __name__ == '__main__': pyjd.setup("./public/Tabs.html") app = Tabs() app.onModuleLoad() pyjd.run()
def greet(fred): global sc txt = fred.getText() if txt == "Click me lots": sc = StyleSheetCssChanger(newcolours) fred.setText("Did it work?") elif txt == "Did it work?": sc.remove() fred.setText("It did!") elif txt == "It did!": sc = StyleSheetCssChanger(morenewcolours) fred.setText("Play again!") elif txt != "Ok enough now": fred.setText("Ok enough now") sc.remove() if __name__ == '__main__': pyjd.setup("public/CSSMess.html?fred=foo#me") b = Button("Click me lots", greet, StyleName='teststyle') h = HTML("<b>CSSMess World</b> (html)", StyleName='teststyle') l = Label("CSSMess World (label)", StyleName='teststyle') base = HTML("CSSMess from %s" % pygwt.getModuleBaseURL(), StyleName='teststyle') RootPanel().add(b) RootPanel().add(h) RootPanel().add(l) RootPanel().add(base) StyleSheetCssFileChanger("./CSSMess.css") pyjd.run()
This application depends on puremvc for python,\n\ which doesn't seem to be available.\n\ See README. """) from puremvc.patterns.facade import Facade from ApplicationConstants import Command import controller, components class AppFacade(Facade): def __init__(self): self.initializeFacade() self.initializeController() self.registerCommand(Command.STARTUP, controller.StartupCommand) self.registerCommand(Command.DELETE_USER, controller.DeleteUserCommand) self.registerCommand(Command.ADD_ROLE_RESULT, controller.AddRoleResultCommand) @staticmethod def getInstance(): return AppFacade() if __name__ == '__main__': pyjd.setup("./public/EmployeeAdmin.html") app = AppFacade.getInstance() pyjsApp = components.PyJsApp() app.sendNotification(Command.STARTUP, pyjsApp.appFrame) pyjd.run()
self.restart(no_of_bomb) else: self.row, self.column = level if level[0] <= current_level[0] and level[1] <= current_level[1]: self.grid.resize(*level) self.restart(no_of_bomb) else: self.grid_panel.remove(self.grid) self.create_grid() self.start(no_of_bomb) def restart(self, no_of_bomb=0): for one in self.get_all_cells(): one.count = 0 one.state = 0 one.setStyleName('blank') DOM.setInnerHTML(one.getElement(), '') self.start(no_of_bomb) if __name__ == '__main__': pyjd.setup("./public/minesweeper.html") LOG = HTMLPanel('', StyleName='log') SCORES = HTMLPanel('', StyleName='scores') game = Game(8, 8) RootPanel('content').add(game) RootPanel('content').add(SCORES) RootPanel('content').add(LOG) pyjd.run()
def onClick(self, sender): log.debug('Text'+str(sender)) def _event_targets_title(self, event): target = DOM.eventGetTarget(event) return target and DOM.isOrHasChild(self.title.getElement(), target) def onBrowserEvent(self, event): etype = DOM.eventGetType(event) if etype == "click": if self._event_targets_title(event): return ClickHandler.onBrowserEvent(self, event) class Text(HTML, ClickHandler): def __init__(self, text): HTML.__init__(self, text) ClickHandler.__init__(self, preventDefault=True) self.addClickListener(self) def onClick(self, sender): log.debug('Text'+str(sender)) if __name__ == "__main__": pyjd.setup("./Override.html") board = Board() RootPanel().add(board) pyjd.run()
s.save(self.printable) s.message = "called from storing object via self.printable" s.call() s.save(getattr(self,'printable')) s.message = "called from storing object using getattr(self, 'printable') " s.call() s.save(global_printable) s.message = "called from storing object using global_printable" s.call() @staticmethod def printable(text): log(text) class StoringObject: def save(self,func): self.func = func def call(self): self.func(self.message) if __name__ == '__main__': pyjd.setup("MainTest.html") app = MainTest() app.onModuleLoad() pyjd.run()
class getRec: def onCompletion(self, text): result = loads(text) findMovie(result['movie_id']) findRating(result['movie_id']) mainpage.mid = result['movie_id'] class Site: def __init__(self): self.mid = None HTTPRequest().asyncGet("http://student02.cse.nd.edu:40001/recommendations/156", getRec(self)) if __name__=='__main__': pyjd.setup("public/primer.html") mainpage = Site() l = Label("Enter movie ID:") movie = Label("Movie Title Displayed Here if Found") movieRating = Label("Movie Rating Displayed Here if Found") poster = Image() b1 = Button("Up",upvote) b2 = Button("Down", downvote) absolute = AbsolutePanel() absolute.add(poster,50,25) absolute.add(b1,0,100) absolute.add(b2,250,100) absolute.add(movie,50,0) absolute.add(movieRating,50,315) absolute.setWidth("100%") absolute.setHeight("100%")
if addendum: title.append(addendum) html5.document.title = conf["vi.title.delimiter"].join(title) def setPath(self, path = ""): hash = html5.window.top.location.hash if "?" in hash and not "?" in path: hash = hash.split("?", 1)[1] if hash: hash = "?" + hash else: hash = "" html5.window.top.location.hash = path + hash if __name__ == '__main__': pyjd.setup("public/main.html") # Configure vi as network render prefix network.NetworkService.prefix = "/vi" conf["currentlanguage"] = i18n.getLanguage() # Application app = Application() html5.Body().appendChild(app) pyjd.run()
def onControlValueChanged(self, sender, old_value, new_value): if sender == self.label: self.b.setControlPos(new_value) self.b.setValue(new_value, 0) if sender == self.b: self.label.setControlPos(new_value) self.label.setValue(new_value, 0) class ControlDemo: def onModuleLoad(self): p = HorizontalPanel() p.setSpacing(10) sc = SliderClass(False) p.add(sc) sc = SliderClass(True) p.add(sc) sc = SliderClass(True) p.add(sc) RootPanel().add(p) if __name__ == '__main__': pyjd.setup("./public/ControlDemo.html") app = ControlDemo() app.onModuleLoad() pyjd.run()
self.sinkContainer.setCellHeight(self.curSink, "100%") self.sinkContainer.setCellVerticalAlignment(self.curSink, HasAlignment.ALIGN_TOP) self.curSink.onShow() def loadSinks(self): HTTPRequest().asyncGet("slides.txt", SlideListLoader(self)) def setSlides(self, slides): for l in slides: name = l[0] desc = l[1] self.sink_list.add(Slide.init(name, desc)) #Show the initial screen. initToken = History.getToken() if len(initToken): self.onHistoryChanged(initToken) else: self.showInfo() def showInfo(self): self.show(self.sink_list.sinks[0], False) if __name__ == '__main__': pyjd.setup("http://127.0.0.1/examples/slideshow/public/Slideshow.html") app = Slideshow() app.onModuleLoad() pyjd.run()
def onElementMousemove(self,sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) s = self.desc[self.elements.index(sender)] self.set_status('Mousemove on Element '+s+' at '+str(x)+', '+str(y)) DOM.eventCancelBubble(event,True) def onElementDblClick(self,sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) s = self.desc[self.elements.index(sender)] self.set_status('Doubleclick on Element '+s+' at '+str(x)+', '+str(y)) DOM.eventCancelBubble(event,True) def onElementContextmenu(self, sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) s = self.desc[self.elements.index(sender)] self.set_status('Contextmenue on Element '+s+' at '+str(x)+', '+str(y)) DOM.eventCancelBubble(event,True) DOM.eventPreventDefault(event) if __name__ == "__main__": pyjd.setup("public/events.html") events=Events() RootPanel().add(events) events.draw() pyjd.run()
class App: def onModuleLoad(self): text = TextBox() df1 = DateField() df2 = DateField(format='%Y/%m/%d') b = Button("Show Calendar", self) self.cal = Calendar(MinDate=(2012, 5, 10), MaxDate=(2014, 6, 8)) vp = VerticalPanel() vp.setSpacing(10) vp.add(df1) vp.add(b) vp.add(df2) RootPanel().add(vp) def onClick(self, sender): p = CalendarPopup(self.cal) x = sender.getAbsoluteLeft() + 10 y = sender.getAbsoluteTop() + 10 p.setPopupPosition(x, y) p.show() if __name__ == '__main__': pyjd.setup("./public/DateField.html") # dummy in pyjs app = App() app.onModuleLoad() pyjd.run() # dummy in pyjs
from ApplicationConstants import Notification from controller.StartupCommand import StartupCommand from view.components.AppFrame import AppFrame class AppFacade(Facade): def __init__(self): self.initializeFacade() self.initializeController() self.registerCommand(Notification.STARTUP, StartupCommand) @staticmethod def getInstance(): return AppFacade() # workaround for pyjd xulrunner issue: timesheet uses XMLHttpRequest. class TimerCls: def __init__(self): self.app = AppFacade.getInstance() Timer(1, self) def onTimer(self, tid): appFrame = AppFrame() self.app.sendNotification(Notification.STARTUP, appFrame) if __name__ == '__main__': pyjd.setup("http://127.0.0.1/examples/timesheet/public/TimeSheet.html") t = TimerCls() pyjd.run()
isBold = False while True: i = doc.find("``") if i == -1: break if isBold: doc = doc[:i] + '</b></font>' + doc[i + 2:] else: doc = doc[:i] + '<font face="monospace"><b>' + doc[i + 2:] isBold = not isBold return doc def srcToHTML(self, src): """ Convert the given source code to HTML. The source code is already in HTML format, but has extra tags to make it a complete HTML file. We extract and return just the text between the <body> tags. """ i = src.find('<body') i = src.find('>', i) j = src.find('</body>') return src[i + 1:j] if __name__ == '__main__': pyjd.setup("./public/Showcase.html") app = Showcase() app.onModuleLoad() pyjd.run()
self.view_path = view_path #self.prev_keys = [] #self.next_key = None self.loadPage(first_key) def loadPage(self, startkey=None): limit = int(self.page_size)+1 view_url = self.db_url+self.view_path+'?limit=%d'%limit if startkey is not None: view_url += '&startkey="%s"'%startkey else: self.prev_keys = [] self.first_button.setEnabled(False) self.next_button.setEnabled(False) self.prev_button.setEnabled(False) HTTPRequest().asyncGet(None, None, url=view_url, handler=ViewLoader(self)) if __name__ == '__main__': pyjd.setup("public/viewer.html") full_url = Window.getLocation().getHref() db_url = '/'.join(full_url.split('/')[:4])+'/' view_url = '_all_docs' viewer = Viewer(db_url, RootPanel(), Window.alert, page_size=10) viewer.onModuleLoad() viewer.setView(view_url) pyjd.run()
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Distributed as part of pyjamas (http://pyj.be) import pyjd # dummy in pyjs from Photos import Photos from pyjamas.ui.RootPanel import RootPanel class PicasaWeb: def onModuleLoad(self): self.photos = Photos() RootPanel().add(self.photos) if __name__ == '__main__': # for pyjd, set up a web server and load the HTML from there: # this convinces the browser engine that the AJAX will be loaded # from the same URI base as the URL, it's all a bit messy... pyjd.setup("public/PicasaWeb.html") app = PicasaWeb() app.onModuleLoad() pyjd.run()
def updatePageDisplay(self): if self.page<self.min_page: self.page=self.min_page elif self.page>self.max_page: self.page=self.max_page total_pages=(self.max_page-self.min_page) + 1 self.g.setHTML(0, 4, "<b>page %d of %d</b>" % (self.page, total_pages)) if self.page>=self.max_page: self.addb.setEnabled(False) else: self.addb.setEnabled(True) if self.page<=self.min_page: self.subb.setEnabled(False) else: self.subb.setEnabled(True) for y in range(1, 5): for x in range(5): self.g.setText(y, x, "%d (%d,%d)" % (self.page, x, y)) def AppInit(): return GridWidget() if __name__ == '__main__': pyjd.setup("./GridTest.html") g = GridWidget() RootPanel().add(g) pyjd.run()
class XMLload: def onModuleLoad(self): HTTPRequest().asyncGet("contacts.xml", XMLloader(self)) def onError(self, text, code): # FIXME pass def onTimeout(self, text): # FIXME pass def doStuff(self, xmldoc): contacts = xmldoc.getElementsByTagName("contact") len = contacts.length for i in range(len): contactsDom = contacts.item(i) firstNames = contactsDom.getElementsByTagName("firstname") firstNameNode = firstNames.item(0) firstName = firstNameNode.firstChild.nodeValue RootPanel().add(HTML("firstname: %s" % str(firstName))) if __name__ == '__main__': pyjd.setup("./public/XMLload.html") app = XMLload() app.onModuleLoad() pyjd.run()
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Distributed as part of pyjamas (http://pyjs.org) import pyjd # dummy in pyjs from Photos import Photos from pyjamas.ui.RootPanel import RootPanel class PicasaWeb: def onModuleLoad(self): self.photos=Photos() RootPanel().add(self.photos) if __name__ == '__main__': # for pyjd, set up a web server and load the HTML from there: # this convinces the browser engine that the AJAX will be loaded # from the same URI base as the URL, it's all a bit messy... pyjd.setup("public/PicasaWeb.html") app = PicasaWeb() app.onModuleLoad() pyjd.run()
self.tab_graffle = TabRaphaelContainer() self.tab_graffle.set_headline( 'This is a simple example of the Raphael Graffle') self.tab_graffle.set_raphael(graffle.Graffle(width=600, height=300)) self.tabs.add(self.tab_graffle, 'Graffle') self.tab_spinner = TabRaphaelContainer() self.tab_spinner.set_headline('This Raphael Spinner Example') self.tab_spinner.set_raphael(spinner.Spinner(width=600, height=300)) self.tabs.add(self.tab_spinner, 'Spinner') self.tabs.selectTab(0) self.tabs.setWidth("100%") self.tabs.setHeight("100%") RootPanel().add(self.tabs) def draw(self): self.tab_spinner.raphael.draw() self.tab_graffle.raphael.draw() #self.tab_events.raphael.draw() if __name__ == "__main__": pyjd.setup("public/raphael_showcase.html") app = ShowCaseApp() app.onModuleLoad() app.draw() app.tab_graffle.raphael.connect() app.tab_events.raphael.connect() pyjd.run()
import pyjd # dummy in pyjs from pyjamas.ui.RootPanel import RootPanel from DayFilterWidget import DayFilterWidget from SchoolCalendarWidget import SchoolCalendarWidget class DynaTable: def onModuleLoad(self): slot = RootPanel("calendar") if slot is not None: calendar = SchoolCalendarWidget(15) slot.add(calendar) slot = RootPanel("days") if slot is not None: filterWidget = DayFilterWidget(calendar) slot.add(filterWidget) if __name__ == '__main__': pyjd.setup("http://127.0.0.1/examples/dynamictable/public/DynaTable.html") # dummy in pyjs app = DynaTable() app.onModuleLoad() pyjd.run() # dummy in pyjd
#self.setSpacing('10px') pool = StudentContainer(1, 20, 'pool_1') for item in [['Fred', 12], ['Jane', 10], ['Sam', 18], ['Ginger', 8], ['Mary', 4]]: pool.addStudent(name=item[0], age=item[1]) self.append(pool) self.append(StudentContainer(6, 13, 'pool_2')) self.append(StudentContainer(11, 20, 'pool_3')) self.setSpacing('10px') def containerFromId(self, id): for item in self.children: if item.getID() == id: return item class MultiTargetDemo(DNDDemo): def __init__(self): self.drop_widget = ClassContainer() self.title = 'Drop with Validation' self.id = 'multi' DNDDemo.__init__(self) if __name__ == '__main__': pyjd.setup("./public/DNDTest.html") j = RootPanel() j.add(DNDDemos()) pyjd.run()
self.sinkContainer.setCellVerticalAlignment(self.curSink, HasAlignment.ALIGN_TOP) self.curSink.onShow() def loadSinks(self): HTTPRequest().asyncGet("contents.txt", ChapterListLoader(self)) def setChapters(self, chapters): for l in chapters: name = l[0] desc = l[1] self.sink_list.addSink(Chapter.init(name, desc)) #Show the initial screen. initToken = History.getToken() if len(initToken): self.onHistoryChanged(initToken) else: self.showInfo() def showInfo(self): self.show(self.sink_list.sinks[0], False) if __name__ == '__main__': pyjd.setup("http://127.0.0.1/pyjamas/doc/book/public/Bookreader.html") app = Bookreader() app.onModuleLoad() pyjd.run()
import pyjd from pyjamas.ui.RootPanel import RootPanel from pyjamas.ui.Image import Image from pyjamas.ui.Anchor import Anchor if __name__ == '__main__': pyjd.setup("public/Anchor.html") root = RootPanel() image = Image('http://pyj.be/img/pyjamas.128x128.png') anchor = Anchor(Widget=image, Href='http://pyj.be', Title='Pyjs website') root.add(anchor) pyjd.run()
for i in range(self.numSectors): alpha = beta * i - math.pi/2 cos = math.cos(alpha) sin = math.sin(alpha) data=','.join(['M',str(self.cx + self.r1 * cos),str(self.cy + self.r1 * sin),'L',str(self.cx + self.r2 * cos),str(self.cy + self.r2 * sin)]) path = self.canvas.path(data=data,attrs=pathParams) self.opacity.append(1.0 * i / self.numSectors ) self.sectors.append(path) period = 1000/self.numSectors self._timer = Timer(notify=self) self._timer.scheduleRepeating(period) def onTimer(self, timerID): """ Respond to our timer firing. """ self.opacity.insert(0, self.opacity.pop()) for i in range(self.numSectors): self.sectors[i].setAttr("opacity", self.opacity[i]) ############################################################################# if __name__ == "__main__": pyjd.setup("public/spinner.html") spinner=Spinner() RootPanel().add(spinner) spinner.draw() pyjd.run()
"rotate CCW", "reload", "reset", ] for buttonName in buttons: newButton = Button(buttonName, listener=self.clickListener) panel.add(newButton) RootPanel().add(HTML("Hello <b>World</b>")) def clickListener(self, e): button = e.getText() if button == "zoom in": mainUI.svg.zoom_in() elif button == "zoom out": mainUI.svg.zoom_out() elif button == "rotate CW": mainUI.svg.rot_CW() elif button == "rotate CCW": mainUI.svg.rot_CCW() elif button == "reset": mainUI.svg.reset_transforms() elif button == "reload": mainUI.svg.change_floorplan() if __name__ == "__main__": pyjd.setup("./public/svg_test.html") ui = mainUI() pyjd.run()
elif request_info.method == 'getSong': self.status.setText(self.status.getText() + " - song received") song_obj = songs.Song(response) self.status.setText(self.status.getText() + "; id: %i; num-chords: %i" % (song_obj.id, len(song_obj.chords) ) ) self.songHtml.setHTML(song_obj.getHtml()) #self.textArea.setText(song_obj.text) else: # Unknown response received form the server self.status.setText(self.status.getText() + "none!") def onRemoteError(self, code, errobj, request_info): message = errobj['message'] self.status.setText("Server Error or Invalid Response: ERROR %s - %s" % (code, message)) class DataService(JSONProxy): def __init__(self): JSONProxy.__init__(self, "/services/", ["getAllSongs", "addSong", "deleteSong", "getSong"]) if __name__ == "__main__": """ For running Pyjamas-Desktop. """ pyjd.setup("public/softrchordapp.html") #pyjd.setup("http://127.0.0.1:8000/site_media/output/softchordapp.html") app = SoftChordApp() app.onModuleLoad() pyjd.run()
result = loads(text) findMovie(result['movie_id']) findRating(result['movie_id']) mainpage.mid = result['movie_id'] class Site: def __init__(self): self.mid = None HTTPRequest().asyncGet( "http://student02.cse.nd.edu:40001/recommendations/156", getRec(self)) if __name__ == '__main__': pyjd.setup("public/primer.html") mainpage = Site() l = Label("Enter movie ID:") movie = Label("Movie Title Displayed Here if Found") movieRating = Label("Movie Rating Displayed Here if Found") poster = Image() b1 = Button("Up", upvote) b2 = Button("Down", downvote) absolute = AbsolutePanel() absolute.add(poster, 50, 25) absolute.add(b1, 0, 100) absolute.add(b2, 250, 100) absolute.add(movie, 50, 0) absolute.add(movieRating, 50, 315) absolute.setWidth("100%") absolute.setHeight("100%")
def loadPageList(self): HTTPRequest().asyncGet("sidebar.html", PageLoader(self, "sidebar", "contents")) HTTPRequest().asyncGet("header.html", PageLoader(self, "header", "contents")) HTTPRequest().asyncGet("footer.html", PageLoader(self, "footer", "contents")) HTTPRequest().asyncGet("contents.txt", PageListLoader(self, "contents")) def loadPages(self, pages, purpose): if purpose == 'contents': self.pages = {} self.page_list = pages elif purpose == 'faq': self.faq_pages = {} self.faq_list = pages for l in pages: title = l[0] desc = l[1] HTTPRequest().asyncGet(desc, PageLoader(self, title, purpose)) if __name__ == '__main__': pyjd.setup("./public/index.html") app = Tabs() app.onModuleLoad() pyjd.run()
import pyjd from pyjamas.ui.RootPanel import RootPanel from pyjamas.ui.Panel import Panel from pyjamas.ui.HTML import HTML class MainWindow(Panel): def __init__(self): self.setSize("100%", "100%") self.setTitle("Hello World!") def get_open_games(self): return True def join_game(self): return True def quit(self): return True if __name__ == '__main__': pyjd.setup("public/zillaclient.html") panel = MainWindow() RootPanel().add(panel) RootPanel().setTitle("Hello World!") RootPanel().add(HTML("""Created by Zilla Team""")) pyjd.run()
import pyjd # this is dummy in pyjs. from pyjamas.ui.RootPanel import RootPanel from pyjamas.ui.Label import Label from pyjamas import Window if __name__ == '__main__': pyjd.setup("") RootPanel().add(Label("Hello World")) Window.alert("Hello World")
import pyjd # this is dummy in pyjs. from pyjamas import Window from pyjamas.ui.Tree import Tree from pyjamas.ui.TreeItem import TreeItem from pyjamas.ui.CheckBox import CheckBox from pyjamas.ui.RootPanel import RootPanel def onCb1(sender): Window.alert('onCb1 ' + str(sender) + str(sender.isChecked())) def onCb2(sender): Window.alert('onCb2 ' + str(sender) + str(sender.isChecked())) def main(): root = RootPanel() tree = Tree() cb1 = CheckBox('test 1') cb1.addClickListener(onCb1) root.add(cb1) cb2 = CheckBox('test 2') cb2.addClickListener(onCb2) item = TreeItem(cb2) tree.addItem(item) root.add(tree) if __name__ == '__main__': pyjd.setup("./public/TreeItemTest.html") main() pyjd.run()
# Hours self.saveContext() self.rotate( ((2*pi)/12)*hours + pi) self.fillRect(-2,-2,4,self.width * 0.2) self.restoreContext() self.restoreContext() self.drawImage(self.clock.getElement(),0,0) def AppInit(): img_url = Window.getLocation().getSearchVar("img") if not img_url: img_url = 'images/chrome_clock.png' solar = SolarCanvas(img_url) solar.isActive = True solar.onTimer() return solar if __name__ == '__main__': pyjd.setup("./public/Widgets.html") app = Widgets() app.onModuleLoad() pyjd.run()
self.editor.add_btn.setEnabled(False) def onKeyPress(self, sender, keycode, modifiers): '''Let users input using keyboard. ''' project_name = self.editor.get_name_txt() status = self.editor.get_status() data = [project_name, status] if keycode == KeyboardListener.KEY_ESCAPE: pass # TODO: should we do something useful here? elif keycode == KeyboardListener.KEY_ENTER: if self.editor.add_btn.getText() == 'Add' and self.editor.add_btn.isEnabled(): self.controller.process_msg(ADD_ROW_MSG, data) elif self.editor.add_btn.getText() == 'Change' and self.editor.add_btn.isEnabled(): self.controller.process_msg(EDT_ROW_MSG, self.grid.selected_row, data) if __name__ == '__main__': pyjd.setup("projects.html") view = Projects_View() view.onModuleLoad() model = Projects_Model() controller = Projects_Controller() controller.register(model, view) view.register(controller) pyjd.run()
self.toplevel.set(self.buoy) self.buoy.cast_off() RootPanel().add(self.toplevel) def onFlare(self, service, prefixes): if self.toplevel: self.toplevel.set(service) def onTitlesChanged(self, titles): browser_title = '' for title in reversed(titles): browser_title += title + ' - ' browser_title = browser_title[:-3] Window.setTitle(browser_title) def onBreadcrumbsChanged(self, crumbs): self.crumbs.clear() for n, crumb in enumerate(crumbs): if n < len(crumbs) - 1: self.crumbs.add(Hyperlink(text=crumb['label'], TargetHistoryToken=crumb['token'])) self.crumbs.add(Label('>')) else: self.crumbs.add(HTML('<b>%s</b>' % crumb['label'])) if __name__ == '__main__': pyjd.setup("public/Navigate.html") app = Navigate() app.onModuleLoad() pyjd.run()
class Game(SimplePanel): def __init__(self, level): self.level = level SimplePanel.__init__(self) self.start_game() def start_game(self): dim = self.level grid = Grid(dim, dim) grid.setStyleName("grid") for i in range(dim): for j in range(dim): gc = GridCell(i, j) grid.setWidget(i, j, gc) self.add(grid) def next_level(self): self.remove(self.getWidget()) self.level += 1 self.start_game() if __name__ == '__main__': pyjd.setup("public/lightout.html") game = Game(3) RootPanel().get('game').add(game) #RootPanel().add(game) pyjd.run()
import pyjd # this is dummy in pyjs. from pyjamas.ui.RootPanel import RootPanel from pyjamas.ui.HTML import HTML from pyjamas.ui.VerticalPanel import VerticalPanel from pyjamas import Window from editor import Editor from viewer import Viewer if __name__ == '__main__': pyjd.setup("public/cbrow.html") full_url = Window.getLocation().getHref() db_url = '/'.join(full_url.split('/')[:4])+'/' editor_panel = VerticalPanel() editor = Editor(db_url, editor_panel) viewer = Viewer(db_url, RootPanel(), editor.loadDocument) sep = HTML('<hr style="height:10" />') editor.onModuleLoad() viewer.onModuleLoad() RootPanel().add(sep) RootPanel().add(editor_panel) viewer.setView('_all_docs') pyjd.run()
def onToggleUD(self, sender): self.label.setText(" Toggle2 isdown: " + str(self.toggle2.isDown())) def onClick(self, sender): if sender == self.button: if self.i: self.i = False text = ">>>>UP<<<<" self.toggle.setCurrentFace(self.toggle.getUpFace()) else: self.i = True text = ">>>DOWN<<<" self.toggle.setCurrentFace(self.toggle.getDownFace()) #self.label.setText("self.toggle.style_name: "+ # self.toggle.style_name+", self.toggle.getStyleName():"+ # self.toggle.getStyleName()+" ") self.label.setText(text) elif sender == self.toggle: text = ">>>DOWN<<<" if self.i: text = ">>>>UP<<<<" self.i = not self.i self.label.setText(text + " isdown: " + str(self.toggle.isDown())) if __name__ == "__main__": pyjd.setup("./public/Toggle.html") app = Toggle() app.onModuleLoad() pyjd.run()
sc = None def greet(fred): global sc txt = fred.getText() if txt == "Click me lots": sc = StyleSheetCssText(newcolours) fred.setText("Did it work?") elif txt == "Did it work?": sc.remove() fred.setText("It did!") elif txt == "It did!": sc = StyleSheetCssText(morenewcolours) fred.setText("Play again!") elif txt != "Ok enough now": fred.setText("Ok enough now") sc.remove() if __name__ == '__main__': pyjd.setup("public/CSSMess.html?fred=foo#me") b = Button("Click me lots", greet, StyleName='teststyle') h = HTML("<b>CSSMess World</b> (html)", StyleName='teststyle') l = Label("CSSMess World (label)", StyleName='teststyle') base = HTML("CSSMess from %s" % pygwt.getModuleBaseURL(), StyleName='teststyle') RootPanel().add(b) RootPanel().add(h) RootPanel().add(l) RootPanel().add(base) StyleSheetCssFile("./CSSMess.css") pyjd.run()
str(AMSJavascript.sent) + ' AMSJavascript.recv ' + str(AMSJavascript.recv)) return if self.commobj.commname == 'No AMS publisher running': self.status.setText(self.commobj.commname) else: self.status.setText('Memories for AMS Comm: ' + str(AMSJavascript.sent) + str(AMSJavascript.recv) + self.commobj.commname) result = self.commobj.get_memory_list() if self.tree: self.panel.remove(self.tree) self.tree = Tree() for i in result: subtree = TreeItem(i) memory = self.commobj.memory_attach(i) fields = memory.get_field_list() for j in fields: field = memory.get_field_info(j) subtree.addItem(j + ' = ' + str(field[4])) self.tree.addItem(subtree) self.panel.add(self.tree) if __name__ == '__main__': pyjd.setup() app = AMSJavascriptExample() app.onModuleLoad() pyjd.run()
vp.add(lb) vp.add(canvas) self.layout.add(vp) if self.currentDemo.getControls() is not None: self.layout.add(self.currentDemo.getControls()) RootPanel().add(self.layout) self.currentDemo.drawDemo() def onChange(self, listBox): choice = listBox.getSelectedIndex() self.swapDemo(self.demos[choice]) """ * Changes the current demo for the input demo """ def swapDemo(self, newDemo): self.currentDemo.stopDemo() self.layout.remove(self.currentDemo.getControls()) self.currentDemo = newDemo self.layout.add(self.currentDemo.getControls()) self.currentDemo.drawDemo() if __name__ == '__main__': pyjd.setup("./public/GWTCanvasDemo.html") app = GWTCanvasDemo() app.onModuleLoad() pyjd.run()
self.title.setText('Wiki page for: ' + token) self.remote.find_one(token, self) def onChange(self, sender): if sender == self.t: self.remote.insert(self.name, self.t.getText(), self) def onRemoteResponse(self, response, request_info): if request_info.method == 'find_one': self.h.setHTML(response['content']) self.t.setText(response['content']) def onRemoteError(self, code, message, request_info): log.debug('remote error! ' + str(message)) log.debug('remote error! ' + str(request_info)) def onKeyUp(self, sender, keycode, modifiers): if sender == self.t: self.h.setHTML(self.t.getText()) class DataService(JSONProxy): def __init__(self): JSONProxy.__init__(self, '/json', ['find_one', 'insert']) if __name__ == '__main__': pyjd.setup("http://127.0.0.1:8080/Wiki.html") Wiki() pyjd.run()
msg = name + ' ' + action + ' (' + str(x) + ', ' + str(y) + ')' self.msgarea1.setText(msg) log.debug(msg) def onMouseMove(self, sender, x, y): self._mouseActionMessage(sender.areaname, "move", x, y) def onMouseDown(self, sender, x, y): self._mouseActionMessage(sender.areaname, "down", x, y) def onMouseUp(self, sender, x, y): self._mouseActionMessage(sender.areaname, "up", x, y) def onMouseEnter(self, sender): self._mouseActionMessage(sender.areaname, "enter") def onMouseLeave(self, sender): self._mouseActionMessage(sender.areaname, "leave") def onClick(self, sender): msg = "you clicked on baby katie's " + sender.areaname self.msgarea2.setText(msg) log.debug(msg) if __name__ == '__main__': pyjd.setup("http://127.0.0.1/examples/maparea/public/MapAreaDemo.html") app = MapAreaDemo() app.onModuleLoad() pyjd.run()
def __init__(self, Parent, *args, **kwargs): self.Parent = Parent self.focussed = False RootPanelCls.__init__(self, *args, **kwargs) ClickHandler.__init__(self) KeyboardHandler.__init__(self) self.addClickListener(self) def onClick(self, Sender): self.focussed = not self.focussed self.Parent.setFocus(self.focussed) if __name__ == '__main__': pyjd.setup("public/Space.html") c = GameCanvas(800, 600) panel = FocusPanel(Widget=c) RootPanel().add(panel) panel.addKeyboardListener(c) panel.setFocus(True) RootPanel().add( HTML(""" <hr/> Left/Right arrows turn, Up key thrusts, Space bar fires<br/> <a href="http://rumsey.org/blog/?p=215">About Space Game</a> by <a href="http://rumsey.org/blog/">Ogre</a><br/> Written entirely in Python, using <a href="http://pyjs.org/">Pyjamas</a></br> Copyright © 2009 Joe Rumsey """)) #c.getElement().focus()