def create(self, engine, application): self._application = application self._engine = engine self._running = False self._controlsPanel = pychan.loadXML( 'data/gui/widget_events_controls.xml') self._controlsPanel.position = (0, 0) self._controlsPanel.mapEvents({ "controlBtn": self._toggleWindow, }) self._outputBox = self._controlsPanel.findChild(name="outputBox") self._window = pychan.loadXML('data/gui/widget_events_window.xml') self._window.capture(event_name="widgetHidden", callback=cbwa(self._widgetHiddenCallback, self._window.name)) self._window.capture(event_name="widgetShown", callback=cbwa(self._widgetShownCallback, self._window.name)) self._window.capture(event_name="widgetMoved", callback=cbwa(self._widgetMovedCallback, self._window.name)) self._window.mapEvents({ "testButtonHide/ancestorHidden": cbwa(self._widgetHiddenCallback, self._window.findChild(name="testButtonHide").name), "testButtonShow/ancestorShown": cbwa(self._widgetShownCallback, self._window.findChild(name="testButtonShow").name), "testButtonMove/ancestorMoved": cbwa(self._widgetMovedCallback, self._window.findChild(name="testButtonMove").name) })
def _loadGui(self, type, guifile, imports): """ _loadGui Function Loads a pychan GUI file to one of the four GUI slots, then loads a python package to run to initilise the gui Keyword Arguments type - String, the type of GUI being loaded guifile - String, name of the pychan file being loaded imports - Boolean """ if type == 'MAIN': self._mainmenu = menuhandler.MenuHandler(guifile, self) elif type == 'HUD': self._hud = hudhandler.HUDHandler(guifile, self) elif type == 'SETTINGS': self._settingsmenu = settingshandler.SettingsHandler(guifile, self) elif type == 'ABOUT': self._aboutmenu = abouthandler.AboutHandler(guifile, self) elif type == 'PAUSE': self._pause = pychan.loadXML('gui/' + guifile + '.xml') if imports: guiinit = __import__('scripts.gui.' + guifile) guiinit.run() elif type == 'LOAD': self._loadingmenu = pychan.loadXML('gui/' + guifile + '.xml') if imports: guiinit = __import__('scripts.gui.' + guifile) guiinit.run() else: pass
def __init__(self, guifile, world): self._world = world self._options = {} self._popupoptions = {} self._window = pychan.loadXML("gui/settings.xml") self._popup = pychan.loadXML("gui/settingspopup.xml") self._dynamicbuttons = [ "resolutionDrop" , "fullscreenButton" , "windowedButton" , "openGLButton" , "SDLButton" , "soundonButton" , "soundoffButton" , "applyButton" , "closeButton" ] self._popupbuttons = [ "okButton" , "cancelButton" ] for button in self._dynamicbuttons: self._options[button] = self._window.findChild(name=button) for button in self._popupbuttons: self._popupoptions[button] = self._popup.findChild(name=button) self._options["resolutionDrop"].items = [ u"640x480" , u"800x480" , u"800x600" , u"1024x600" , u"1024x768" , u"1280x768" , u"1440x900" , u"1280x960" ] i = 0 self._resolution = 0 for resolution in self._options["resolutionDrop"].items: if self._world._setting.get("FIFE", "ScreenResolution", "800x600") == resolution: self._options["resolutionDrop"]._setSelected(i) self._resolution = i break else: i = i + 1 if self._world._setting.get("FIFE", "FullScreen", True): self._options["fullscreenButton"].toggled = True self._fullscreen = True else: self._options["windowedButton"].toggled = True self._fullscreen = False if self._world._setting.get("FIFE", "RenderBackend", "OpenGL") == "OpenGL": self._options["openGLButton"].toggled = True self._openGL = True else: self._options["SDLButton"].toggled = True self._openGL = False if self._world._setting.get("FIFE", "PlaySounds", True): self._options["soundonButton"].toggled = True self._sound = True else: self._options["soundoffButton"].toggled = True self._sound = False self._window.mapEvents({ "closeButton" : self._apply }) self._popup.mapEvents({ "okButton" : self._popupOkay , "closeButton" : self._popupCancel })
def initalizeMainMenu(self, new_game, load_game, quit_game): """Initialized the main menu and sets the callbacks""" # Set a simple background to display the main screen. xml_file = vfs.VFS.open('gui/main_menu_background.xml') self.main_menu_background = pychan.loadXML(xml_file) # Initialize the main menu screen. screen_mode = self.engine.getRenderBackend().getCurrentScreenMode() self.main_menu_background.width = screen_mode.getWidth() self.main_menu_background.height = screen_mode.getHeight() xml_file = vfs.VFS.open('gui/main_menu.xml') self.main_menu = pychan.loadXML(xml_file) self.main_menu.adaptLayout() self.new_game_callback = new_game self.load_game_callback = load_game self.quit_callback = quit_game menu_events = {} menu_events["newButton"] = self.newGame menu_events["loadButton"] = self.loadGame menu_events["settingsButton"] = self.displaySettings menu_events["quitButton"] = self.quitGame self.main_menu.mapEvents(menu_events) self.initializeQuitDialog() self.initializeSettingsMenu()
def __init__(self, settings_file='settings-dist.xml'): setting = Setting(settings_file=settings_file) super(GuichanDesignerApplication, self).__init__(setting=setting) # PyChanDesigner fonts pychan.loadFonts('fonts/freefont.fontdef') pychan.setupModalExecution(self.mainLoop, self.breakFromMainLoop) # pychan default settings need an overwrite, because we don't like some aspects (like opaque widgets) screen_width, screen_height = \ [int(dimension) for dimension in setting.get('FIFE', 'ScreenResolution').split('x')] self.xml_script_path = '' self.active_widget = None self.selected_widget = None self.widget_stack = [] self.logger = logging.getLogger('PychanDesignerApplication') self.xml_editor = pychan.loadXML('gui/xml_editor.xml') self.console = pychan.loadXML('gui/console.xml') with file('gui/pychan_designer.xml') as xml_file: self.gui = pychan.loadXML(xml_file) self.gui.min_size = (screen_width, screen_height) self.gui.max_size = (screen_width, screen_height) editor = self.gui.findChild(name='editor') editor.content = self.xml_editor self.gui.mapEvents( { 'exitButton': self.quit, 'reloadButton': self.reloadXml, 'applyButton': self.applyXml, 'saveButton': self.saveXml, 'xmlEditorTab': self.showXmlEditor, 'consoleTab': self.showConsole, } ) self.gui.adaptLayout() self.gui.show()
def _loadWidget(self, widget): """ Loads a widget """ if os.path.isfile(self._settings_gui_xml): return pychan.loadXML(widget) else: return pychan.loadXML(StringIO(widget))
def __init__(self, controller, gui_file): self.controller = controller if isinstance(gui_file, pychan.Widget): self.gui = gui_file elif isinstance(gui_file, StringTypes): xml_file = vfs.VFS.open(gui_file) self.gui = pychan.loadXML(xml_file) else: self.gui = pychan.loadXML(gui_file)
def load_xml_translated(filename): """Just like pychan's load_xml, but translates strings according to the data specified in guitranslations.py""" global translated_widgets try: untranslated = pychan.loadXML(xml_files[filename]) except (IOError, ValueError), e: print 'PLEASE REPORT: invalid path', filename , 'in translation!', e untranslated = pychan.loadXML(filename)
def load_xml_translated(filename): """Just like pychan's load_xml, but translates strings according to the data specified in guitranslations.py""" global translated_widgets try: untranslated = pychan.loadXML("content/gui/%s" % filename) except (IOError, ValueError), e: print "PLEASE REPORT: invalid path", filename, "in translation!", e untranslated = pychan.loadXML(filename)
def load_xml_translated(filename): """Just like pychan's load_xml, but translates strings according to the data specified in guitranslations.py""" global translated_widgets try: untranslated = pychan.loadXML(xml_files[filename]) except (IOError, ValueError), e: print 'PLEASE REPORT: invalid path', filename, 'in translation!', e untranslated = pychan.loadXML(filename)
def _loadWidget(self, widget): """ Loads a widget """ if os.path.isfile(self._settings_gui_xml): return pychan.loadXML(widget) else: try: return pychan.loadXML(BytesIO(widget)) except TypeError: return pychan.loadXML(StringIO(widget))
def __init__(self, world, setting): self._world = world self._setting = setting self._widget = pychan.loadXML('gui/mainmenu.xml') self._continue = self._widget.findChild(name="continue") self._newgame = self._widget.findChild(name="new_game") self._credits = self._widget.findChild(name="credits") self._highscores = self._widget.findChild(name="high_scores") self._quit = self._widget.findChild(name="quit") self._widget.position = (0,0) eventMap = { 'continue': self._world.continueGame, 'new_game': self._world.newGame, 'settings': self._setting.onOptionsPress, 'credits': self._world.showCredits, 'high_scores': self._world.showHighScores, 'quit': self._world.quit, } self._widget.mapEvents(eventMap) self._continueMinWidth = self._continue.min_width self._continueMinHeight = self._continue.min_height self._continueMaxWidth = self._continue.max_width self._continueMaxHeight = self._continue.max_height
def __init__(self, guifile, world): self._world = world self._menuicons = {} self._hud = pychan.loadXML("gui/menu.xml") self._dynamicbuttons = ( 'newbutton' , 'loadbutton' , 'savebutton' , 'settingsbutton' , 'aboutbutton' , 'exitbutton' ) self._menu = self._hud.findChild(name='menu') self._menu.mapEvents({ 'newbutton/mousePressed' : self._new , 'newbutton/mouseEntered' : pychan.tools.attrSetCallback(image="gui/icons/buttons/new.png", do__adaptLayout=True) , 'newbutton/mouseExited' : pychan.tools.attrSetCallback(image="gui/icons/buttons/new2.png", do__adaptLayout=True) , 'loadbutton/mousePressed' : self._load , 'loadbutton/mouseEntered' : pychan.tools.attrSetCallback(image="gui/icons/buttons/load.png", do__adaptLayout=True) , 'loadbutton/mouseExited' : pychan.tools.attrSetCallback(image="gui/icons/buttons/load2.png", do__adaptLayout=True) , 'savebutton/mousePressed' : self._save , 'savebutton/mouseEntered' : pychan.tools.attrSetCallback(image="gui/icons/buttons/save.png", do__adaptLayout=True) , 'savebutton/mouseExited' : pychan.tools.attrSetCallback(image="gui/icons/buttons/save2.png", do__adaptLayout=True) , 'settingsbutton/mousePressed' : self._settings, 'settingsbutton/mouseEntered' : pychan.tools.attrSetCallback(image="gui/icons/buttons/settings.png", do__adaptLayout=True) , 'settingsbutton/mouseExited' : pychan.tools.attrSetCallback(image="gui/icons/buttons/settings2.png", do__adaptLayout=True) , 'aboutbutton/mousePressed' : self._about , 'aboutbutton/mouseEntered' : pychan.tools.attrSetCallback(image="gui/icons/buttons/about.png", do__adaptLayout=True) , 'aboutbutton/mouseExited' : pychan.tools.attrSetCallback(image="gui/icons/buttons/about2.png", do__adaptLayout=True) , 'exitbutton/mousePressed' : self._exit , 'exitbutton/mouseEntered' : pychan.tools.attrSetCallback(image="gui/icons/buttons/exit.png", do__adaptLayout=True) , 'exitbutton/mouseExited' : pychan.tools.attrSetCallback(image="gui/icons/buttons/exit2.png", do__adaptLayout=True) }) for button in self._dynamicbuttons: self._menuicons[button] = self._menu.findChild(name=button) self._menu.removeAllChildren()
def create(self): """ creates the gui sceleton """ if self.container is not None: return self.container = pychan.loadXML('gui/objectselector.xml') self.container.position_technique = 'explicit' self.container.position = _POSITION self.container.name = self.getName() self.container.set_orientation = self.set_orientation self.container.capture(self.mouse_clicked, "mouseClicked") vert_wrapper = self.container.findChild(name='vertical_wrapper') hor_wrapper = self.container.findChild(name='horizontal_wrapper') self.wrappers[1]['wrapper'] = vert_wrapper self.wrappers[1]['image_mode_wrapper'] = vert_wrapper.findChild(name="image_mode_wrapper") self.wrappers[1]['text_mode_wrapper'] = vert_wrapper.findChild(name="text_mode_wrapper") self.wrappers[1]['image_mode_wrapper'].hide() self.wrappers[1]['text_mode_wrapper'].hide() self.wrappers[0]['wrapper'] = hor_wrapper self.wrappers[0]['image_mode_wrapper'] = hor_wrapper.findChild(name="image_mode_wrapper") self.wrappers[0]['text_mode_wrapper'] = hor_wrapper.findChild(name="text_mode_wrapper") self.wrappers[0]['image_mode_wrapper'].hide() self.wrappers[0]['text_mode_wrapper'].hide() self.container.removeChild(vert_wrapper) self.container.removeChild(hor_wrapper) self.set_orientation(orientation=self._orientation) self.container.afterUndock = self.on_undock self.container.afterDock = self.on_dock
def start(self): self.labelCount = 4 self.widget = pychan.loadXML(self.xmlFile) self.tabarea = self.widget.findChild(name='tabarea') self.widget.mapEvents({ 'closeButton':self.stop, }) #self.tabarea.layout = 'vertical' label = self.tabarea.findChild(name='label1') label.tab.mapEvents({ 'close1': self.closeTab, }) label = self.tabarea.findChild(name='label2') label.tab.mapEvents({ 'close2': self.closeTab, }) label = self.tabarea.findChild(name='label3') label.tab.mapEvents({ 'close3': self.closeTab, }) label = self.tabarea.findChild(name='label4') label.tab.mapEvents({ 'create': self.createTab, }) self.widget.show()
def start(self): """ load XML file and setup callbacks """ self.widget = pychan.loadXML(self.xmlFile) self.widget.mapEvents({ 'base_rslider': self.update_basecolor, 'base_gslider': self.update_basecolor, 'base_bslider': self.update_basecolor, 'base_aslider': self.update_basecolor, 'background_rslider': self.update_background_color, 'background_gslider': self.update_background_color, 'background_bslider': self.update_background_color, 'background_aslider': self.update_background_color, 'closeButton':self.stop, }) # alpha value needs to be set, otherwise you don't see colors ;-) self.widget.findChild(name="base_aslider").setValue(float(255)) self.widget.findChild(name="background_aslider").setValue(float(255)) # init stuff self.update_basecolor() self.update_background_color() self.widget.show()
def __init__(self, engine, callback=None, onCancel=None, map=None, layer=None): self.engine = engine self.callback = callback self.onCancel = onCancel self._widget = pychan.loadXML('gui/cameradialog.xml') if map: self._widget.distributeData({ 'mapBox': unicode(map.getId()), }) if layer: self._widget.distributeData({ 'layerBox': unicode(layer.getId()), }) self._widget.mapEvents({ 'okButton': self._finished, 'cancelButton': self._cancelled }) self._widget.show()
def start(self): self.widget = pychan.loadXML(self.xmlFile) self.window = self.widget self.hbox1 = self.widget.findChild(name="hbox1") self.hbox2 = self.widget.findChild(name="hbox2") self.widgets = [self.widget, self.hbox1, self.hbox2] eventMap = { 'closeButton': self.stop, 'text1': self.requestModalWindow, 'text2': self.releaseModalWindow, 'text3': self.requestMouseModalWindow, 'text4': self.releaseMouseModalWindow, 'text5': self.requestModalHBox1, 'text6': self.releaseModalHBox1, 'text7': self.requestMouseModalHBox1, 'text8': self.releaseMouseModalHBox1, 'text9': self.requestModalHBox2, 'text10': self.releaseModalHBox2, 'text11': self.requestMouseModalHBox2, 'text12': self.releaseMouseModalHBox2, } self.widget.mapEvents(eventMap) self.widget.show() self.updateColor()
def onAboutButtonPress(self): #self.youWin() # TODO FIXME XXX remove if not self.window: self.window = pychan.loadXML('gui/xml/help.xml') self.window.mapEvents({ 'closeButton' : self.window.hide }) self.window.distributeData({ 'helpText' : open("misc/infotext.txt").read() }) self.window.show()
def load_uh_widget(filename, style=None, center_widget=False): """Loads a pychan widget from an xml file and applies uh-specific modifications """ # load widget try: widget = loadXML(BytesIO(get_widget_xml(filename))) except (IOError, ValueError) as error: log = logging.getLogger('gui') log.error('PLEASE REPORT: invalid path %s in translation!\n> %s', filename, error) raise # translate widget = translate_widget(widget, filename) if style: widget.stylize(style) # format headline for w in widget.findChildren(): if w.name.startswith("headline") or w.name == "name": w.stylize('headline') elif w.name.startswith("uni_") or w.comment.startswith("uni_"): w.font = 'unifont' elif w.name.startswith("transparent_"): w.stylize('transparent') if center_widget: widget.position_technique = "center:center" return widget
def start(self): self.widget = pychan.loadXML(self.xmlFile) self.widget.mapEvents( {"xslider": self.update, "yslider": self.update, "pbarslider": self.update, "closeButton": self.stop} ) self.update() self.widget.show()
def buildGui(self): self.gui = pychan.loadXML('gui/objectselector.xml') # Add search field self._searchfield = self.gui.findChild(name="searchField") self._searchfield.capture(self._search) self._searchfield.capture(self._search, "keyPressed") self.gui.findChild(name="searchButton").capture(self._search) # Add the drop down with list of namespaces self.namespaces = self.gui.findChild(name="namespaceDropdown") self.namespaces.items = self.engine.getModel().getNamespaces() self.namespaces.selected = 0 # TODO: Replace with SelectionEvent, once pychan supports it self.namespaces.capture(self.update_namespace, "action") self.namespaces.capture(self.update_namespace, "mouseWheelMovedUp") self.namespaces.capture(self.update_namespace, "mouseWheelMovedDown") self.namespaces.capture(self.update_namespace, "keyReleased") # Object list self.mainScrollArea = self.gui.findChild(name="mainScrollArea") self.objects = None if self.mode == 'list': self.setTextList() else: # Assuming self.mode is 'preview' self.setImageList() # Action buttons self.gui.findChild(name="toggleModeButton").capture(self.toggleMode) self.gui.findChild(name="closeButton").capture(self.hide) # Preview area self.gui.findChild(name="previewScrollArea").background_color = self.gui.base_color self.preview = self.gui.findChild(name="previewIcon")
def __init__(self, engine, regions, callback=None, onCancel=None, region=None): self.engine = engine self.model = engine.getModel() self.regions = regions if not region is None and isinstance(region, str): region = regions[region] self.region = region self.callback = callback self.onCancel = onCancel self._widget = pychan.loadXML('gui/regiondialog.xml') if region: self._widget.distributeData({ "regionBox": unicode(region.name), "xPosBox": unicode(region.rect.x), "yPosBox": unicode(region.rect.y), "widthBox": unicode(region.rect.w), "heightBox": unicode(region.rect.h), }) self._widget.mapEvents({ 'okButton': self._finished, 'cancelButton': self._cancelled }) self._widget.show()
def start(self): self.widget = pychan.loadXML(self.xmlFile) self.window = self.widget self.hbox1 = self.widget.findChild(name="hbox1") self.hbox2 = self.widget.findChild(name="hbox2") self.widgets = [self.widget, self.hbox1, self.hbox2] eventMap = { 'closeButton':self.stop, 'text1': self.requestModalWindow, 'text2': self.releaseModalWindow, 'text3': self.requestMouseModalWindow, 'text4': self.releaseMouseModalWindow, 'text5': self.requestModalHBox1, 'text6': self.releaseModalHBox1, 'text7': self.requestMouseModalHBox1, 'text8': self.releaseMouseModalHBox1, 'text9': self.requestModalHBox2, 'text10': self.releaseModalHBox2, 'text11': self.requestMouseModalHBox2, 'text12': self.releaseMouseModalHBox2, } self.widget.mapEvents(eventMap) self.widget.show() self.updateColor()
def __init__(self, engine, regions, callback=None, onCancel=None, region=None): self.engine = engine self.model = engine.getModel() self.regions = regions if not region is None and isinstance(region, str): region = regions[region] self.region = region self.callback = callback self.onCancel = onCancel self._widget = pychan.loadXML('gui/regiondialog.xml') if region: self._widget.distributeData({ "regionBox" : unicode(region.name), "xPosBox" : unicode(region.rect.x), "yPosBox" : unicode(region.rect.y), "widthBox" : unicode(region.rect.w), "heightBox" : unicode(region.rect.h), }) self._widget.mapEvents({ 'okButton' : self._finished, 'cancelButton' : self._cancelled }) self._widget.show()
def __init__(self, gameplay, setting): self._gameplay = gameplay self._setting = setting self._widget = pychan.loadXML("gui/mainMenu.xml") self._continue = self._widget.findChild(name="continue") self._newgame = self._widget.findChild(name="new_game") self._settings = self._widget.findChild(name="settings") self._credits = self._widget.findChild(name="credits") self._quit = self._widget.findChild(name="quit") self._widget.position = (0,0) eventMap = { 'settings': self._setting.onOptionsPress, 'credits': self._gameplay.showCredits, 'quit': self._gameplay.quit, } self._widget.mapEvents(eventMap) self._continueMinWidth = self._continue.min_width self._continueMinHeight = self._continue.min_height self._continueMaxWidth = self._continue.max_width self._continueMaxHeight = self._continue.max_height
def __init__(self, engine, settings): self.engine = engine self.settings = settings # available options screen_modes = self.engine.getDeviceCaps().getSupportedScreenModes() resolutions = list(set([(mode.getWidth(), mode.getHeight()) for mode in screen_modes])) self.resolutions = ["{0}x{1}".format(item[0], item[1]) for item in sorted(resolutions)[1:]] self.render_backends = ['OpenGL', 'SDL'] self.lighting_models = range(3) # selected options self.resolution = self.settings.get("FIFE", "ScreenResolution") self.render_backend = self.settings.get("FIFE", "RenderBackend") self.lighting_model = self.settings.get("FIFE", "Lighting") self.fullscreen = self.settings.get("FIFE", "FullScreen") self.sound = self.settings.get("FIFE", "PlaySounds") self.scroll_speed = self.settings.get("parpg", "ScrollSpeed") xml_file = vfs.VFS.open('gui/settings_menu.xml') self.window = pychan.loadXML(xml_file) self.restart_dialog = RestartDialog(self.settings) self.window.mapEvents({'okButton': self.save, 'cancelButton': self.hide, 'defaultButton': self.reset, 'scroll_speed': self.update}) self.initializeWidgets() self.fillWidgets()
def __init__(self, world, setting): self._world = world self._setting = setting self._widget = pychan.loadXML('gui/mainmenu.xml') self._continue = self._widget.findChild(name="continue") self._newgame = self._widget.findChild(name="new_game") self._credits = self._widget.findChild(name="credits") self._highscores = self._widget.findChild(name="high_scores") self._quit = self._widget.findChild(name="quit") self._widget.position = (0, 0) eventMap = { 'continue': self._world.continueGame, 'new_game': self._world.newGame, 'settings': self._setting.onOptionsPress, 'credits': self._world.showCredits, 'high_scores': self._world.showHighScores, 'quit': self._world.quit, } self._widget.mapEvents(eventMap) self._continueMinWidth = self._continue.min_width self._continueMinHeight = self._continue.min_height self._continueMaxWidth = self._continue.max_width self._continueMaxHeight = self._continue.max_height
def loadXml(self, xml_file): self.logger.debug( 'loading file {0}'.format(getattr(xml_file, 'name', '')) ) top_widget = pychan.loadXML(xml_file) top_widget.deepApply(self._applyActivateEventCapture) top_widget.deepApply(lambda widget: widget.capture(self.selectWidget, 'mousePressed')) widget_preview = self.gui.findChild(name='widgetPreview') widget_preview.content = top_widget top_widget.adaptLayout() # FIXME Technomage 2011-01-23: Containers are not displayed with their # background images when attached to another widget. A workaround # is to call beforeShow after attaching the container. if isinstance(top_widget, pychan.Container): top_widget.beforeShow() xml_editor = self.xml_editor xml_file.seek(0) xml_editor.text = unicode(xml_file.read(), 'utf8') xml_editor.resizeToContent() self.logger.info( 'successfully loaded file {0}'.format( getattr(xml_file, 'name', '') ) )
def load_uh_widget(filename, style=None, center_widget=False): """Loads a pychan widget from an xml file and applies uh-specific modifications """ # load widget try: widget = loadXML(StringIO(get_widget_xml(filename))) except (IOError, ValueError) as error: log = logging.getLogger("gui") log.error(u"PLEASE REPORT: invalid path %s in translation!\n> %s", filename, error) raise # translate widget = translate_widget(widget, filename) if style: widget.stylize(style) # format headline for w in widget.findChildren(): if w.name.startswith("headline") or w.name == "name": w.stylize("headline") elif w.name.startswith("uni_") or w.comment.startswith("uni_"): w.font = "unifont" elif w.name.startswith("transparent_"): w.stylize("transparent") if center_widget: widget.position_technique = "center:center" return widget
def load_uh_widget(filename, style=None, center_widget=False): """Loads a pychan widget from an xml file and applies uh-specific modifications """ # load widget try: widget = loadXML(get_gui_files_map()[filename]) except (IOError, ValueError) as error: print u'PLEASE REPORT: invalid path {path} in translation! {error}'.format(path=filename, error=error) raise # translate widget = translate_widget(widget, filename) if style: widget.stylize(style) # format headline for w in widget.findChildren(): if w.name.startswith("headline") or w.name == "name": w.stylize('headline') elif w.name.startswith("uni_") or w.comment.startswith("uni_"): w.font = '16_black_unifont' if center_widget: widget.position_technique = "automatic" # "center:center" return widget
def onAboutButtonPress(self): if not self.aboutWindow: self.aboutWindow = pychan.loadXML('gui/help.xml') self.aboutWindow.mapEvents({'closeButton': self.aboutWindow.hide}) self.aboutWindow.distributeData( {'helpText': open("misc/infotext.txt").read()}) self.aboutWindow.show()
def __init__(self, world): self._world = world self._widget = pychan.loadXML("gui/credits.xml") eventMap = {"close": self.hide} self._widget.mapEvents(eventMap)
def _show_help(self): """ shows the help dialog """ if self._help_dialog is not None: self._help_dialog.show() return self._help_dialog = pychan.loadXML("gui/help.xml") self._help_dialog.title = u"Help (CellView)" self._help_dialog.mapEvents({ "closeButton": self._help_dialog.hide, }) # gimme some more space _SIZE = (320, 400) scrollarea = self._help_dialog.findChildren( __class__=pychan.widgets.ScrollArea)[0] scrollarea.size = _SIZE scrollarea.min_size = _SIZE scrollarea.max_size = _SIZE f = open('lang/help_cellview.txt', 'r') self._help_dialog.findChild(name="helpText").text = unicode( f.read(), 'utf-8') f.close() self._help_dialog.show()
def standalone_error_popup(headline, msg): """Display an error via gui. Use only for errors that make 'import horizons.main' fail.""" from fife.extensions import pychan from fife import fife e = fife.Engine() e.getSettings().setDefaultFontPath("content/fonts/LinLibertine.ttf") e.init() pychan.init(e) pychan.loadFonts("content/fonts/libertine.fontdef") # hack for accessing this in do_quit (global does't work as the variables here are local) class Quit(object): do = False def do_quit(): Quit.do=True dlg = pychan.loadXML("content/gui/xml/startup_error_popup.xml") # can't translate as translations are only set up later dlg.findChild(name="headline").text = headline dlg.findChild(name="msg").text = msg dlg.mapEvents({'quit_button': do_quit}) dlg.show() e.initializePumping() while not Quit.do: e.pump() e.finalizePumping()
def create(self): """ Create the basic gui container """ self.container = pychan.loadXML('gui/regiontool.xml') self.wrapper = self.container.findChild(name="regions_wrapper") self.remove_region_button = self.container.findChild(name="remove_region_button") self.create_region_button = self.container.findChild(name="add_region_button") self.edit_region_button = self.container.findChild(name="edit_region_button") self.remove_region_button.capture(self.removeSelectedRegion) self.remove_region_button.capture(cbwa(self._editor.getStatusBar().showTooltip, self.remove_region_button.helptext), 'mouseEntered') self.remove_region_button.capture(self._editor.getStatusBar().hideTooltip, 'mouseExited') self.create_region_button.capture(self.showRegionWizard) self.create_region_button.capture(cbwa(self._editor.getStatusBar().showTooltip, self.create_region_button.helptext), 'mouseEntered') self.create_region_button.capture(self._editor.getStatusBar().hideTooltip, 'mouseExited') self.edit_region_button.capture(self.showEditDialog) self.edit_region_button.capture(cbwa(self._editor.getStatusBar().showTooltip, self.edit_region_button.helptext), 'mouseEntered') self.edit_region_button.capture(self._editor.getStatusBar().hideTooltip, 'mouseExited') self.select_layer_drop_down = self.container.findChild(name="layer_select_drop_down") self.select_layer_drop_down.capture(self.update_region_layer) self.onNewMap(None) # overwrite Panel.afterUndock self.container.afterUndock = self.on_undock self.container.afterDock = self.on_dock
def load_uh_widget(filename, style=None, center_widget=False): """Loads a pychan widget from an xml file and applies uh-specific modifications """ # load widget try: widget = loadXML(get_gui_files_map()[filename]) except (IOError, ValueError) as error: print u'PLEASE REPORT: invalid path {path} in translation! {error}'.format(path=filename, error=error) raise # translate widget = translate_widget(widget, filename) if style: widget.stylize(style) # format headline for w in widget.findChildren(): if w.name.startswith("headline") or w.name == "name": w.stylize('headline') elif w.name.startswith("uni_") or w.comment.startswith("uni_"): w.font = 'unifont' if center_widget: widget.position_technique = "center:center" return widget
def __init__(self, world, setting): self._world = world self._setting = setting self._widget = pychan.loadXML("gui/mainmenu.xml") self._continue = self._widget.findChild(name="continue") self._newgame = self._widget.findChild(name="new_game") self._credits = self._widget.findChild(name="credits") self._highscores = self._widget.findChild(name="high_scores") self._quit = self._widget.findChild(name="quit") self._widget.position = (0, 0) eventMap = { "continue": self._world.continueGame, "new_game": self._world.newGame, "settings": self._setting.showSettingsDialog, "credits": self._world.showCredits, "high_scores": self._world.showHighScores, "quit": self._world.quit, } self._widget.mapEvents(eventMap) self._continueMinWidth = self._continue.min_width self._continueMinHeight = self._continue.min_height self._continueMaxWidth = self._continue.max_width self._continueMaxHeight = self._continue.max_height
def __init__(self, acceptedfunction, title, text): self._widget = None # This loads our GUI window and saves a reference to it. We'll need # it to set the text values of the title and text fields. self._widget = pychan.loadXML('gui/query.xml') # This searches for a child widget with the name "queryname" and # then sets that widgets text property. Easy isn't it? # This is the title of our dialog box. self._queryname = self._widget.findChild(name="queryname") self._queryname.text = unicode(title) # This searches for a child widget with the name "querytext" and # then sets that widgets text property. Easy isn't it? self._querytext = self._widget.findChild(name="querytext") self._querytext.text = unicode(text) # Pychan has some handy functions to bind callbacks to certain widget # events. In this case when the the 'accept' and 'decline' child # widgets get clicked the acceptedfunction() or hide() functions get # executed. Remember to not include the ()'s because that will run # the function when Python parses the line... not good! eventMap = { 'accept': acceptedfunction, 'decline': self._widget.hide, } # This function is what actually does the mapping of the function to # widget. There is some magic behind the scenes here. self._widget.mapEvents(eventMap)
def initializeHelpMenu(self): """Initialize the help menu @return: None""" self.help_dialog = pychan.loadXML("gui/help.xml") help_events = {"closeButton":self.help_dialog.hide} self.help_dialog.mapEvents(help_events) main_help_text = u"Welcome to Post-Apocalyptic RPG or PARPG![br][br]"\ "This game is still in development, so please expect for there to be "\ "bugs and[br]feel free to tell us about them at "\ "http://www.forums.parpg.net.[br]This game uses a "\ "\"Point 'N' Click\" interface, which means that to move around,[br]"\ "just click where you would like to go and your character will move "\ "there.[br]PARPG also utilizes a context menu. To access this, just "\ "right click anywhere[br]on the screen and a menu will come up. This "\ "menu will change depending on[br]what you have clicked on, hence "\ "it's name \"context menu\".[br][br]" k_text = u" Keybindings" k_text += "[br] A : Add a test action to the actions display" k_text += "[br] I : Toggle the inventory screen" k_text += "[br] F5 : Take a screenshot" k_text += "[br] (saves to <parpg>/screenshots/)" k_text += "[br] F10 : Toggle console" k_text += "[br] PAUSE : (Un)Pause the game" k_text += "[br] Q : Quit the game" self.help_dialog.distributeInitialData({ "MainHelpText":main_help_text, "KeybindText":k_text })
def start(self): self.widget = pychan.loadXML(self.xmlFile) self.widget.mapEvents({ 'okButton': self.stop, 'addButton': self.addLabel, }) self.labelBox = self.widget.findChild(name="labelBox") self.widget.show()
def showCredits(self): """ Callback handler from the credits link/label. """ # We use PyChan's synchronous execution feature here. if self.creditsWidget is None: self.creditsWidget = pychan.loadXML('gui/credits.xml') self.creditsWidget.execute({ 'okButton' : "Yay!" })
def start(self): self.styledCredits = pychan.loadXML('data/gui/all_widgets.xml') self.styledCredits.distributeInitialData({ 'demoList': [str(x, 'utf8') for x in dir(pychan)], 'demoText': str(pychan.__doc__, 'utf8') }) self.widget = pychan.loadXML(self.xmlFile) self.widget.mapEvents({ 'testStyle': self.testStyle, 'closeButton': self.stop, }) self.widget.distributeInitialData({'styleList': self.styles}) self.widget.position_technique = 'right-20:center' self.styledCredits.position_technique = 'left+20:center' self.widget.show() self.styledCredits.show()
def __init__(self, gamecontroller): super(Credits, self).__init__(gamecontroller) self._widget = pychan.loadXML('gui/credits.xml') eventMap = { 'close': self._guicontroller.hideCredits, } self._widget.mapEvents(eventMap)
def __init__(self, message): self._widget = pychan.loadXML('gui/error.xml') self._widget.mapEvents({'okButton': self._widget.hide}) self._widget.distributeInitialData({'message': message}) self._widget.show() self._widget.adaptLayout( ) # Necessary to make scrollarea work properly
def start(self): self.widget = pychan.loadXML(self.xmlFile) self.widget.mapEvents({ 'wslider': self.update, 'hslider': self.update, 'closeButton': self.stop, }) self.update() self.widget.show()
def start(self): self.widget = pychan.loadXML(self.xmlFile) self.widget.mapEvents({ 'advanceButton': self.advanceBar, 'resetButton': self.resetBar, 'closeButton': self.stop }) self.widget.show()
def start(self): self.widget = pychan.loadXML(self.xmlFile) self.widget.mapEvents({ 'increaseButton': self.increase, 'decreaseButton': self.decrease, 'closeButton': self.stop }) self.widget.show()
def __init__(self, world): self._world = world self._widget = pychan.loadXML('gui/credits.xml') eventMap = { 'close': self.hide, } self._widget.mapEvents(eventMap)
def __init__(self, world): self._world = world self._widget = pychan.loadXML('gui/hud.xml') self._fpstext = self._widget.findChild(name="fps") self._velocitytext = self._widget.findChild(name="velocity") self._positiontext = self._widget.findChild(name="position") self._scoretext = self._widget.findChild(name="score") self._livestext = self._widget.findChild(name="lives") self._widget.position = (0, 0)
def create_gui(self): """ - creates the gui skeleton by loading the xml file - finds some important childs and saves their widget in the object @todo: - move all dynamic widgets to dict """ self.container = pychan.loadXML('gui/objectedit.xml') self.container.position_technique = 'explicit' self.container.position = _POSITION self.container.mapEvents({ 'change_data': self.save, 'show_help': self._show_help, }) self.container.findChild(name="x_offset_up").capture( self.change_offset, "mousePressed") self.container.findChild(name="x_offset_dn").capture( self.change_offset, "mousePressed") self.x_offset = self.container.findChild(name="x_offset") self.x_offset.capture(self.change_offset, "mouseWheelMovedUp") self.x_offset.capture(self.change_offset, "mouseWheelMovedDown") self.container.findChild(name="y_offset_up").capture( self.change_offset, "mousePressed") self.container.findChild(name="y_offset_dn").capture( self.change_offset, "mousePressed") self.y_offset = self.container.findChild(name="y_offset") self.y_offset.capture(self.change_offset, "mouseWheelMovedUp") self.y_offset.capture(self.change_offset, "mouseWheelMovedDown") self.container.findChild(name="object_blocking_toggle").capture( self.object_blocking_toggle, "mousePressed") self.rotations_listbox = self.container.findChild( name="select_rotations") self.rotations_listbox.capture(self.select_rotation, "mouseWheelMovedUp") self.rotations_listbox.capture(self.select_rotation, "mouseWheelMovedDown") self.rotations_listbox.capture(self.select_rotation, "action") self.xoffset_textfield = self.container.findChild(name="x_offset") self.yoffset_textfield = self.container.findChild(name="y_offset") self.actions_wrapper = self.container.findChild(name="actions_wrapper") self.rotations_wrapper = self.container.findChild( name="rotations_wrapper") self.actions_listbox = self.container.findChild(name="select_actions") self.actions_listbox.capture(self.select_action, "mouseWheelMovedUp") self.actions_listbox.capture(self.select_action, "mouseWheelMovedDown") self.actions_listbox.capture(self.select_action, "action")
def load(self): if os.path.exists('gui/highscores.xml'): self._widget = pychan.loadXML('gui/highscores.xml') else: self._widget = pychan.loadXML('gui/hstemplate.xml') self._scores = list() for i in range(1, 11): place = self._widget.findChild(name=str(i)) name = self._widget.findChild(name="%iname" % i) score = self._widget.findChild(name="%iscore" % i) highscore = HighScore(name.text, int(score.text)) self._scores.append(highscore) eventMap = { 'close': self.hide, } self._widget.mapEvents(eventMap)
def __init__(self, settings): # Call our base class's __init__ function and pass it settings. # This is where the FIFE engine instance gets created and configured # (amoungst other things). This includes reading the settings file, # applying the settings to the engine, initializing PyChan (our GUI # manager), creating the default application listener (more info on # this in our later tutorials), and setting up logging. All of # these things you can do on your own but we provide ApplicationBase # to make your life easier. super(Tutorial1Application,self).__init__(settings) # Save a copy of our settings. This could be useful in the future # as the Setting module allows you to store your own settins as # well as FIFE settings. self._settings = settings # Initialize an instance of fife.MapLoader which is a built in map # loader that we provide. We must pass it some internal FIFE objects # that the loader requires to properly load a map. self._loader = fife.MapLoader(self.engine.getModel(), self.engine.getVFS(), self.engine.getImageManager(), self.engine.getRenderBackend()) # True if we have a map loaded. False otherwise. self._mapLoaded = False # Since we want to listen for mouse events lets save a reference to # the event manager and create our event listener and attach it to # the manager. self._eventmanager = self.engine.getEventManager() self._mouselistener = Tutorial1MouseListener(self) # Listeners are executed in the order in which they are added. # Lets ensure this one gets executed first. self._eventmanager.addMouseListenerFront(self._mouselistener) # Add the quit botton to the top left of the screen # First use pychan to load the interface self._rootpanel = pychan.loadXML('gui/rootpanel.xml') # Map functions to the buttons on the root panel self._rootpanel.mapEvents({ 'quitButton' : self.onQuitButtonPress, }) # Finally show the panel so it's visible to the user self._rootpanel.show() # Initialize the dialog box to ask the user if they are sure they want # to quit. The dialog box doesn't get displayed until we call the # show() function. The first parameter is the function to call when # the user clicks the "accept" button on the dialog box. self._quitdialog = QueryDialog(self.quitAccepted, "Attention!", "Are you sure you wan to quit?")
def saveScore(self): self._gamecomplete = False if self._highscores.isHighScore(self._scene.player.score): score = self._scene.player.score dlg = pychan.loadXML('gui/highscoredialog.xml') dlg.execute({'okay': "Yay!"}) name = dlg.findChild(name='name').text self._highscores.addHighScore(HighScore(name, score)) self._highscores.show()
def __init__(self, xml, ok_field=None, cancel_field=None, initial_data={}, data={}): self.gui = loadXML(xml) self.ok_field = ok_field self.cancel_field = cancel_field self.initial_data = initial_data self.data = data self.max_size = None self.min_size = None
def start(self): """ The Example Protocoll: start """ # For simplicity the most basic examples should define # a okButton and/or a closeButton. Those are mapped # to the stop handler. self.widget = pychan.loadXML(self.xmlFile) eventMap = {'closeButton': self.stop, 'okButton': self.stop} # Since the basic example are not required to # supply close and ok button, we 'ignoreMissing' self.widget.mapEvents(eventMap, ignoreMissing=True) self.widget.show()