Exemple #1
0
def loadFrame():
    def open_file_browser(arg):
        d = gui.FileDialog('Load NoteMap file', path='records')
        d.connect(gui.CHANGE, handle_file_browser_closed, d)
        d.open()

    def handle_file_browser_closed(dlg):
        if dlg.value:
            input_file.value = dlg.value
        app.quit()

    app = gui.Desktop()
    main = gui.Container(width=500,
                         height=400)  # , background=(220, 220, 220) )
    # main.add(gui.Label("File Dialog Example", cls="h1"), 20, 20)
    td_style = {'padding_right': 10}
    t = gui.Table()
    t.tr()
    t.td(gui.Label('File Name:'), style=td_style)
    input_file = gui.Input()
    t.td(input_file, style=td_style)
    b = gui.Button("Browse...")
    t.td(b, style=td_style)
    b.connect(gui.CLICK, open_file_browser, None)

    main.add(t, 20, 100)

    app.run(main)
    return input_file.value
Exemple #2
0
    def run(self):
        """Run the item"""

        # Initialize the item
        self.set_item_onset()

        # Create the app
        self.app = gui.Desktop(item=self)
        self.app.connect(gui.QUIT, self.app.quit, None)

        pad = 0  # The maximum line length, used to pad the options

        # Create an HTML document for the content
        doc = html.HTML("")
        for l in self.experiment.unsanitize(self.get("question")).split("\n"):
            doc.add(gui.Label(l))
            pad = max(pad, len(l))
            doc.br(0)

        # Create a 2-column table, start with the HTML on the first row
        c = gui.Table()
        c.tr()
        c.td(doc, align=-1)

        c.tr()
        e = gui.Button(self.get("accept_text"))
        e.connect(gui.CLICK, self.app.quit, None)
        c.td(e, align=-1, height=32, valign=1)

        self.app.run(c)

        # Return success
        return True
Exemple #3
0
    def file_treat():
        global Window, Frame
        #TODO Agregar imagen a botones y estilo a fondo
        third_app = gui.Desktop(screen=Window, area=Frame)
        third_app.connect(gui.QUIT, third_app.quit, None)
        third_app.connect(gui.QUIT, app.quit, None)
        my_container3 = gui.Container(width=670, height=500)
        #Open button
        open_btn = gui.Button("Abrir")
        open_btn.connect(gui.CLICK, open_file_browser, True)
        #Save button
        save_btn = gui.Button("Guardar")
        save_btn.connect(gui.CLICK, open_file_browser, False)
        #Continue button / close file treatment
        ok_btn = gui.Button("Listo!")
        ok_btn.connect(gui.CLICK, third_app.quit, None)
        ok_btn.connect(gui.CLICK, app.quit, None)
        #Cancel button
        cancel_btn = gui.Button("Cancelar")
        cancel_btn.connect(gui.CLICK, third_app.quit, None)
        cancel_btn.connect(gui.CLICK, app.quit, None)

        #Add elements to container
        my_container3.add(
            gui.Image(const.imagespath + "Archivo_Background.png"), 0, 0)
        my_container3.add(open_btn, 155, 330)
        my_container3.add(save_btn, 455, 330)
        my_container3.add(ok_btn, 310, 375)
        my_container3.add(cancel_btn, 580, 10)
        third_app.run(my_container3)
        pygame.display.flip()
Exemple #4
0
def init_gui():
    #themes = cfg['theme'].split(",")
    #gui.theme.load(themes)
    #gui.theme.load(['default','tools'])
    global top
    top = gui.Desktop(theme=gui.Theme([
        os.path.join('data', 'themes', 'default'),
        os.path.join('data', 'themes', 'tools')
    ]))
    def run(self):
        """Run the item"""

        # Initialize the item
        self.set_item_onset()
        self.sri = self.time()
        self.experiment.set("response", None)
        self.experiment.set("response_time", None)

        # Create the app
        self.app = gui.Desktop(item=self)
        self.app.connect(gui.QUIT, self.app.quit, None)

        pad = 0  # The maximum line length, used to pad the options

        # Create an HTML document for the content
        doc = html.HTML("")
        for l in self.experiment.unsanitize(self.get("question")).split("\n"):
            doc.add(gui.Label(l))
            pad = max(pad, len(l))
            doc.br(0)

        # Create a 2-column table, start with the HTML on the first row
        c = gui.Table()
        c.tr()
        c.td(doc, colspan=self.get("maximum_rating") + 1, align=-1)

        c.tr()
        surf = pygame.image.load(
            self.experiment.resource("rating_inactive.png"))
        self.img_list = []
        for i in range(self.get("maximum_rating")):
            img = gui.Image(surf)
            img.connect(gui.CLICK, self.set_response, i)
            c.td(img, align=-1, width=64, height=64)
            self.img_list.append(img)

        c.tr()
        e = gui.Button(self.get("accept_text"))
        e.connect(gui.CLICK, self.app.quit, None)
        c.td(e,
             colspan=self.get("maximum_rating") + 1,
             align=-1,
             height=32,
             valign=1)

        # Keep running the app until a response has been received
        while True:
            self.app.run(c)
            if self.get("response") != "None":
                break

        # Return success
        return True
Exemple #6
0
    def run(self):
        """Run the item"""

        # Initialize the item
        self.set_item_onset()
        self.sri = self.time()
        self.experiment.set("response", None)
        self.experiment.set("response_time", None)

        # Create the app
        self.app = gui.Desktop(item=self)
        self.app.connect(gui.QUIT, self.app.quit, None)

        pad = 0  # The maximum line length, used to pad the options

        # Create an HTML document for the content
        doc = html.HTML("")
        for l in self.experiment.unsanitize(self.get("question")).split("\n"):
            doc.add(gui.Label(l))
            pad = max(pad, len(l))
            doc.br(0)

        # Create a 2-column table, start with the HTML on the first row
        c = gui.Table()
        c.tr()
        c.td(doc, align=-1)

        c.tr()
        t = gui.TextArea(width=self.get("text_area_width"),
                         height=self.get("text_area_height"))
        c.td(t, align=-1)

        c.tr()
        e = gui.Button(self.get("accept_text"))
        e.connect(gui.CLICK, self.app.quit, None)
        c.td(e, align=-1, height=32, valign=1)

        # Keep running the app until a response has been received
        while True:
            self.app.run(c)
            if t.value.strip() != "" or self.get("allow_empty") == "yes":
                break

        # Set the response and response time
        self.experiment.set(
            "response",
            self.experiment.usanitize(unicode(QtCore.QString(
                t.value.strip()))))
        self.experiment.set("response_time", self.time() - self.sri)

        # Return success
        return True
Exemple #7
0
    def __init__(self, config):
        self.config = config
        self.running = True

        self.form = gui.Form()
        self.module = gui.Desktop()

        self.module.connect(gui.QUIT, self.module.quit, None)
        main = gui.Container(width=self.config['width'],
                             height=self.config['height'])
        newdialog = NewKBDDialog(self.config)
        newdialog.connect(gui.CHANGE, self.module.quit, None)
        main.add(newdialog, 0, 0)
Exemple #8
0
def init_gui():
    #themes = cfg['theme'].split(",")
#    themes2 = []
#    for t in themes:
#        if t[0] == "/" or t[0] == ".": themes2.append(t)
#        else: themes2.append(dname+"/"+t)
    #gui.theme.load(themes)
    #gui.theme.load(['default','tools'])
    global top
    top = gui.Desktop(theme=gui.Theme([os.path.join('data','themes','default'),os.path.join('data','themes','tools')]))
    #top.theme.load(['default','tools'])


    pass
Exemple #9
0
 def __init__(self, game_screen, game_engine):
     self._screen = game_screen
     self._engine = game_engine
     self._images = []
     
     self._app = gui.Desktop()
     self._app.connect(gui.QUIT, self._app.quit, None)
     
     self._table = gui.Table()
     #first row
     self._table.tr()
     if self._engine.time_of_day == game.TIME_DAY:
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_day_1_early_bird.png"))
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_day_2_rethink.png"))
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_day_3_mana_steal.png"))
     elif self._engine.time_of_day == game.TIME_NIGHT:
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_night_1_from_the_dusk.png"))
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_night_2_long_night.png"))
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_night_3_mana_search.png"))
     for img in self._images:
         self._table.td(img)
     #second row 
     self._table.tr()
     self._radio = gui.Group()
     self._table.td(gui.Radio(self._radio,value=1))
     self._table.td(gui.Radio(self._radio,value=2))
     self._table.td(gui.Radio(self._radio,value=3))
     #third row      
     self._table.tr()
     if self._engine.time_of_day == game.TIME_DAY:
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_day_4_planning.png"))
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_day_5_great_start.png"))
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_day_6_the_right_moment.png"))
     elif self._engine.time_of_day == game.TIME_NIGHT:
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_night_4_midnight_meditation.png"))
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_night_5_preparation.png"))
         self._images.append(gui.Image("assets/images/cards/tactics/gui_tactics_night_6_sparing_power.png"))
     for i in range(3, 6):
         self._table.td(self._images[i])
     #fourth row
     self._table.tr()       
     self._table.td(gui.Radio(self._radio,value=4))
     self._table.td(gui.Radio(self._radio,value=5))
     self._table.td(gui.Radio(self._radio,value=6))
     #fifth row
     self._table.tr()
     button = gui.Button("Select Tactics")
     self._table.td(button, colspan=3)
     button.connect(gui.CLICK, self._commit_values)
def main():
    #initate pygame just for display window name
    pygame.init()
    #Set Window name
    pygame.display.set_caption(
        (u'Weibo sentiment analysis programme').encode('utf-8'))
    app = gui.Desktop()
    app.connect(gui.QUIT, app.quit, None)
    main_frame = gui.Container(width=800, height=600)
    main_frame.add(gui.Label("Network Sentiment Analysis", cls="h1"), 30, 30)
    td_style = {'padding_right': 10}
    ######################
    m_table = gui.Table(border="32", width=600, height=400)

    m_table.tr()
    m_table.td(gui.Label("Weibo meaning contrast", style=td_style, cls="h2"))
    m_table.td(gui.Label("Dict Analysis", style=td_style, cls="h2"))

    m_table.tr()
    w_m_c_b = gui.Button("Click me")
    w_m_c_dialog = MeaningContrast()
    w_m_c_b.connect(gui.CLICK, w_m_c_dialog.open, None)
    m_table.td(w_m_c_b, style=td_style)

    d_a_b = gui.Button("Click me")
    d_a_dialog = DictAnalysis(weiboid='123223')
    d_a_b.connect(gui.CLICK, d_a_dialog.open, None)
    m_table.td(d_a_b, style=td_style)

    m_table.tr()
    m_table.td(gui.Label("Weibo word contrast", style=td_style, cls="h2"))
    m_table.td(gui.Label("Machine Learning Analysis", style=td_style,
                         cls="h2"))

    m_table.tr()
    w_w_c_b = gui.Button("Click me")
    w_w_c_b_dialog = WeiboWordContrast()
    w_w_c_b.connect(gui.CLICK, w_w_c_b_dialog.open, None)
    m_table.td(w_w_c_b, style=td_style)

    m_l_a_b = gui.Button("Click me")
    m_l_a_b_dialog = MachineLearningAnalysis()
    m_l_a_b.connect(gui.CLICK, m_l_a_b_dialog.open, None)
    m_table.td(m_l_a_b, style=td_style)
    ##################################
    main_frame.add(m_table, 70, 120)
    app.run(main_frame)
Exemple #11
0
    def load(self):
        # Create the top level widget 
        self._app = gui.Desktop(theme = gui.Theme("media/menu/defaultTheme"))
        self._app.connect(gui.QUIT, self._noteWars.quit)

        # Create a table to organise our menu
        highScoreTable = gui.Table()

        spaceLabel = gui.Label(' | ')

        # Add the table header
        highScoreTable.tr()
        highScoreTable.td(gui.Label("Song"))
        highScoreTable.td(spaceLabel)
        highScoreTable.td(gui.Label("Name"))
        highScoreTable.td(spaceLabel)
        highScoreTable.td(gui.Label("Score"))
        highScoreTable.td(spaceLabel)
        highScoreTable.td(gui.Label("Date"))
        
        # Load high scores into table
        highScores = self._loadHighScores()
        for highScore in highScores:
            highScoreTable.tr()
            highScoreTable.td(gui.Label(highScore[0]))
            highScoreTable.td(spaceLabel)
            highScoreTable.td(gui.Label(highScore[1]))
            highScoreTable.td(spaceLabel)
            highScoreTable.td(gui.Label(str(highScore[2])))
            highScoreTable.td(spaceLabel)
            highScoreTable.td(gui.Label(highScore[3]))

        # Add a gap
        highScoreTable.tr()
        highScoreTable.td(gui.Label(), colspan=8)

        # Add a back button
        backButton = gui.Button("Return to main menu")
        backButton.connect(gui.CLICK, self._displayMainMenu)
        highScoreTable.tr() # New table row
        highScoreTable.td(backButton, colspan = 8)

        # Add the menu to the top level widget
        self._app.init(highScoreTable)

        # Signify that the high score menu is visible
        self._isVisible = True
 def __init__(self, game_screen):
     self._screen = game_screen
     
     self._app = gui.Desktop()
     self._app.connect(gui.QUIT, self._app.quit, None)
     
     self._table = gui.Table()
     self._table.tr()
     self._table.td(gui.Label("Select Player"))
     self._select = gui.Select()
     self._select.add("Arythrea", player.ARYTHREA)
     self._table.tr()
     self._table.td(self._select)
     self._table.tr()
     button = gui.Button("Start Solo Game")
     self._table.td(button)
     button.connect(gui.CLICK, self._commit_values)
Exemple #13
0
def main_function():
    # On évite PGU pour Michel
    if len(sys.argv) >= 4 and sys.argv[1] == "--michel":
        ip = sys.argv[2]
        port = int(sys.argv[3])

        jeu(ip, port)

    else:
        app = gui.Desktop(theme=gui.Theme("data/themes/clean"))
        app.connect(gui.QUIT, app.quit, None)

        table = gui.Table()

        # Titre
        table.tr()
        table.td(gui.Label("Connexion au serveur"), colspan=4)

        # IP
        table.tr()
        table.td(gui.Label("IP :"))

        champ_ip = gui.Input(value="127.0.0.1", size=15)
        table.td(champ_ip, colspan=3)

        # Port d'écoute
        table.tr()
        table.td(gui.Label("Port : "))

        champ_port = gui.Input(value="8888", size=5)
        table.td(champ_port, colspan=3)

        # Bouton connexion
        table.tr()
        bouton_conn = gui.Button("Connexion")
        table.td(bouton_conn)

        def lancer_jeu(valeurs):
            (ip, port) = valeurs
            jeu(ip.value, int(port.value))
            sys.exit(0)

        bouton_conn.connect(gui.CLICK, lancer_jeu, (champ_ip, champ_port))

        app.run(table)
Exemple #14
0
 def help():
     global Window, Frame, input_from_user
     #Saves changes on the input
     input_from_user = textarea_code.value
     #App over toolbar
     second_app = gui.Desktop(screen=Window, area=Frame)
     my_container2 = gui.Container(width=670, height=500)
     second_app.connect(gui.QUIT, second_app.quit, None)
     second_app.connect(gui.QUIT, app.quit, None)
     #Exit button
     cancel_btn = gui.Button("Regresar")
     cancel_btn.connect(gui.CLICK, second_app.quit, None)
     cancel_btn.connect(gui.CLICK, app.quit, None)
     #Add items to container
     my_container2.add(
         gui.Image(const.imagespath + "Instrucciones_Background.png"), 0, 0)
     my_container2.add(cancel_btn, 575, 10)
     second_app.run(my_container2)
     pygame.display.flip()
Exemple #15
0
def creationpopup(character):
   
    app = gui.Desktop()
    app.connect(gui.QUIT,app.quit,None)
    c = gui.Table()
    c.tr()
    c.td(gui.Label("Character creation"),colspan=4)
    c.tr()
    c.td(gui.Label("Name :"))
    w = gui.Input(value='noname',size=8)
    c.td(w,colspan=3)
    c.tr()
    def doneit():
	character.name=w.value
    btn = gui.Button("Done")
    btn.connect(gui.CLICK,doneit)
    btn.connect(gui.CLICK,app.quit)
    c.tr()
    c.td(btn,colspan=4)
    app.run(c)
    def levelup(self):
        self.lvl += 1
        self.xp -= 100
        app = gui.Desktop()
        app.connect(gui.QUIT, app.quit, None)
        c = gui.Table()
        c.tr()
        c.td(gui.Label("Character levelup"), colspan=4)
        c.tr()
        c.td(gui.Label("Name :" + self.name))
        c.tr()
        c.td(gui.Label("Level :" + str(self.lvl)))
        c.tr()
        c.td(gui.Label("Strength " + str(self.strength)))
        c.td(gui.Label("Spirit " + str(self.spirit)))
        c.td(gui.Label("Agility " + str(self.agility)))
        c.tr()
        g = gui.Group(value=1)
        c.td(gui.Radio(g, value=1))
        c.td(gui.Radio(g, value=2))
        c.td(gui.Radio(g, value=3))

        def doneit():
            if globalconst.DEBUG:
                print g.value
            if g.value == 1:
                self.strength += 1
                self.healthmax = 5 * self.strength
            if g.value == 2:
                self.spirit += 1
                self.energymax = 5 * (self.strength + self.spirit +
                                      self.agility)
            if g.value == 3:
                self.agility += 1

        btn = gui.Button("Done")
        btn.connect(gui.CLICK, doneit)
        btn.connect(gui.CLICK, app.quit)
        c.tr()
        c.td(btn, colspan=4)
        app.run(c)
    def update(self):

        if self.health < 0:
            self.health = 0
        if self.energy < 0:
            self.energy = 0
        if self.health == 0:
            app = gui.Desktop()
            app.connect(gui.QUIT, app.quit, None)
            e = gui.Button("Game Over")
            e.connect(gui.CLICK, app.quit, None)
            c = gui.Table()
            c.tr()

            c.td(gui.Label(self.name))
            c.td(gui.Label(str(self.lvl)))

            c.tr()
            c.td(e, colspan=2)
            app.run(c)
            self.kill()

        if self.xp >= 100:
            self.levelup()
            if globalconst.DEBUG:
                print self.lvl
        if self.health < self.healthmax:
            t = time.time()
            if globalconst.DEBUG:
                print t - self.restTime
            if (t - self.restTime) > (
                    30 - (30 / 10) * math.log(self.agility, 2)
            ):  #this calcul should be an attribut or such thing ...
                self.health += self.spirit + self.strength
                if self.health > self.healthmax:
                    self.health = self.healthmax
                self.restTime = t

        if self.health == self.healthmax and self.energy < self.energymax:
            t = time.time()
            if globalconst.DEBUG:
                print t - self.restTime
            if (t - self.restTime) > (5 -
                                      (5 / 10) * math.log(self.agility, 2)):
                self.energy += self.spirit
                if self.energy > self.energymax:
                    self.energy = self.energymax
                self.restTime = t

        x, y = self.position
        x += self.action[0] + self.action[1]
        y += self.action[2] + self.action[3]
        self.position = (x, y)
        self.rect = self.image.get_rect()
        self.rect.center = self.position

        image = self.PILimage.copy()

        manavoid = (float)(self.energymax - self.energy) / self.energymax
        healthvoid = (float)(self.healthmax - self.health) / self.healthmax

        beginPixelHealth = healthvoid * image.size[0]
        beginPixelMana = manavoid * image.size[0]

        beginPixelHealth = (int)(beginPixelHealth)
        beginPixelMana = (int)(beginPixelMana)

        boxhealth = (0, 0, image.size[0] - beginPixelHealth, 2)
        boxmana = (0, 2, image.size[0] - beginPixelMana, 4)

        healthbar = Image.new('RGB', (image.size[0] - beginPixelHealth, 2),
                              (0, 255, 0))
        manabar = Image.new('RGB', (image.size[0] - beginPixelMana, 2),
                            (0, 0, 255))

        image.paste(healthbar, boxhealth)
        image.paste(manabar, boxmana)
        #format==PNG
        image = image.convert('RGBA')
        imgstr = image.tostring()

        self.image = pygame.image.fromstring(imgstr, image.size, 'RGBA')

        self.event()
Exemple #18
0
def main():
	whereami = os.path.dirname(os.path.realpath(__file__))
	# Parse arguments
	p = argparse.ArgumentParser(description="A pygame GUI for Home Assistant.")
	p_config = p.add_argument_group('Configuration')
	p_config.add_argument('-c','--config',help="config file to use",required=True,type=argparse.FileType('r'))
	p_config.add_argument('-f','--framebuffer',help="Use this framebuffer as output for the UI (defaults to window mode)",
												default=None,type=str,metavar="/dev/fbX")
	p_config.add_argument('-t','--touchscreen',help="Enable touchscreen integration. Use this as event input",
												default=None,type=str,metavar="/dev/input/eventX")
	p_config.add_argument('-n','--no-display',help="We don't have a display. Sets the SDL_VIDEODRIVER to \"dummy\". Usefull for testing",dest="dummy",action="store_true",
												default=False)
	p_homeassistant = p.add_argument_group('HomeAssistant'," (optional) Parameters to override the config file")
	p_homeassistant.add_argument('-H','--homeassistant',default=None,help="The location of home-assistant",metavar="host.name")
	p_homeassistant.add_argument('-p','--port',default=None,help="the port to use for home-assistant (default: 8123)",type=int)
	p_homeassistant.add_argument('-k','--key',default=None,help="The api password to use (default: None)",type=str)
	p_homeassistant.add_argument('-s','--ssl',help="Use ssl (default false)",default=False,action="store_true")
	p_logging = p.add_argument_group('Logging'," (optional) Logging settings")
	p_logging.add_argument('-v','--verbose',help="Log output",default=False,action="store_true")
	p_logging.add_argument('-L','--logLevel',dest="logLevel",help="Log level to use (default: ERROR)",choices=["INFO","WARNING","ERROR","CRITICAL","DEBUG"],default="ERROR",type=str)
	p_logging.add_argument('-l','--logfile',help="Instead of logging to stdout, log to this file",default=None)
	args = p.parse_args();
	
	
	# Setup logger
	logFormatter = logging.Formatter("%(asctime)s [%(threadName)s:%(name)s] [%(levelname)-5.5s]  %(message)s")
	log = logging.getLogger("HUD")
	log.setLevel(getattr(logging, args.logLevel.upper()))
	if args.verbose:
		if not args.logfile:
			consoleHandler = logging.StreamHandler(sys.stdout)
			consoleHandler.setFormatter(logFormatter)
			log.addHandler(consoleHandler)
		else:
			fileHandler = logging.FileHandler(str(args.logfile))
			fileHandler.setFormatter(logFormatter)
			log.addHandler(fileHandler)
	# Setup Home assistant config
	log.info("Startup: Load config")
	config = configparser.ConfigParser()
	config.read(args.config.name)
	print((config.sections()))
	try:
		haconfig = {
			"host" : (args.homeassistant if args.homeassistant else config["HomeAssistant"]["Host"]),
			"port" : (args.port if args.port else config["HomeAssistant"]["Port"]),
			"ssl" : (args.ssl if args.ssl else config["HomeAssistant"]["SSL"]),
			"key": (args.key if args.key else config["HomeAssistant"]["Password"])
		}
	except KeyError as e:
		log.error("Cannot find section [{}] in config file '{}'!".format(str(e),str(args.config.name)))
		exit(1)
	
	# Setup home assistant connection
	log.info("Startup: Create EventHandler")
	hass = remote.API(haconfig['host'],haconfig['key'],haconfig['port'],haconfig['ssl'])
	HAE = HAEventHandler(hass,settings=haconfig)
	try:
		validation = remote.validate_api(hass)
		if str(validation) != "ok":
			log.info("Startup: Successfully connected to HomeAssistant!")
			raise Exception(validation)
	
	except Exception as e:
		log.error("hass connection verification failed: {}".format(str(validation)))
		exit(1)
	
	log.info("Startup: Setting screen")
	if args.framebuffer:
		log.info("Startup: Setting framebuffer")
		os.putenv('SDL_VIDEODRIVER', 'fbcon')
		os.putenv('SDL_FBDEV'      , args.framebuffer)
	if args.touchscreen:
		log.info("Startup: Setting up touchscreen support")
		os.putenv('SDL_MOUSEDRV'   , 'TSLIB')
		os.putenv('SDL_MOUSEDEV' , args.touchscreen)
	if args.dummy:
		os.putenv('SDL_VIDEODRIVER', 'dummy')
	if args.framebuffer:
		pygame_opts = FULLSCREEN | HWSURFACE | DOUBLEBUF
		#                         ^UNTESTED!^
	else:
		pygame_opts = SWSURFACE
	screen = pygame.display.set_mode((320,480),pygame_opts)
	
	if args.touchscreen:
		## Hide the mouse cursor if we have a touchscreen
		pygame.mouse.set_visible(False)
	
	
	log.info("Startup: Load Theme")
	app = gui.Desktop(theme=gui.Theme(whereami+"/pgu.theme"))
	app.connect(gui.QUIT,app.quit,None)
	
	container=gui.Table(width=230,vpadding=0, hpadding=0)
	
	for section in config.sections():
		if section != "HomeAssistant":
			log.info("Startup: Loading section {}".format(str(section)))
			c = container
			c.tr()
			state = remote.get_state(hass,"group.{}".format(str(config[section]["group"])))
			header = elements.rowHeader(hass,state,table=c)
			HAE.add_listener(state.entity_id,header.set_hass_event)
			c.td(header.draw(),align=-1)
			c.tr()
			if state == None:
				log.warning("Startup: Unable to find group.{}".format(str(config[section]["group"])))
				c.td(gui.Label("Startup: Unable to find group.{}".format(str(config[section]["group"]))))
			else:
				log.info("Startup: Fetching entity statusses")
				# get all states from entities & add to the list if entity is not None (eg. not found)
				entities =  [e for e in [remote.get_state(hass,eid) for eid in state.attributes['entity_id']] if e != None]
				for entity in entities:
					log.info("Startup: Loading entity {}".format(entity.entity_id))
					# Changeable, lights are hmmMMmmm
					if (entity.domain == "light"):
						row = elements.rowLight(hass,entity,last=(True if entity == entities[-1] else False),table=c)
						log.info("Startup: Adding Event listener for {}".format(entity.entity_id))
						HAE.add_listener(entity.entity_id,row.set_hass_event)
						 #row.draw()
						c.td(row.draw(),align=-1)
					elif (entity.domain in ('sensor','device_tracker')):
						# widget = gui.Label("{} : {}".format(str(entity.name),str(entity.state)))
						# c.td(widget)
						row = elements.rowSensor(hass,entity,last=(True if entity == entities[-1] else False))
						log.info("Startup: Adding Event listener for {}".format(entity.entity_id))
						HAE.add_listener(entity.entity_id,row.set_hass_event)
						c.td(row.draw(),align=-1)
					c.tr()
	
			container.td(gui.Spacer(height=4,width=320))
	log.info("Startup: Load elements onto surface")
	main = gui.Container(width=320,height=480)
	header = elements.Header("Home Assistant",width=320,height=40)
	
	
	main.add(header,0,0)
	main.add(container,0,60)
	
	# Start the EventDaemon
	log.info("Startup: start HAEventHandler")
	HAE.start()
	RunPlease = True
	while RunPlease:
		try:
			log.info("Start screen")
			app.run(main,screen=screen )
		except (KeyboardInterrupt, SystemExit):
			log.warning("Got Exit or Ctrl-C. Stopping.")
			RunPlease = False
			pass
		except AttributeError as e:
			log.error("AttributeError, restarting")
			pass
	
	HAE.stop()
	sys.exit(0)
Exemple #19
0
'''
Simple example showing:
- Change to a custom theme.
- Using Table widget to arrange the menu.
'''

from pgu import gui

if __name__ == '__main__':
    # Creating an App
    app = gui.Desktop(theme=gui.Theme('clean'))

    # Creating the widgets
    label1 = gui.Label('Mi super juego')
    #label1.background = gui.Color((255,255,255), width=100,height=100)
    button1 = gui.Button('Testing')
    button2 = gui.Button('Quit')

    # Adding widgets to a container
    container = gui.Table(width=500, height=500)
    container.tr()
    container.td(label1)
    container.tr()
    container.td(button1)
    container.tr()
    container.td(gui.Spacer(10, 50))
    container.tr()
    container.td(button2)

    # Enabling quit, connecting the "quit" button's click event to the app's quit function.
    button2.connect(gui.CLICK, app.quit, None)
Exemple #20
0
            pygame.display.flip()


if __name__ == "__main__":
    # On évite PGU pour Michel
    if len(sys.argv) >= 4 and sys.argv[1] == "--michel":
        ip = sys.argv[2]
        port = int(sys.argv[3])
        if len(sys.argv) == 5:
            nb = int(sys.argv[4])
        else:
            nb = 2
        MyServer(localaddr=(ip, port), nb_joueurs=nb)
    else:
        # Les autres ont le droit à une interface jolie
        app = gui.Desktop(title="coucou", theme=gui.Theme("data/themes/clean"))
        app.connect(gui.QUIT, app.quit, None)

        table = gui.Table()

        # Titre
        table.tr()
        table.td(gui.Label("Config serveur"), colspan=4)

        # IP du serveur
        table.tr()
        table.td(gui.Label("IP : "))

        champ_ip = gui.Input(value="0.0.0.0", size=15)
        table.td(champ_ip, colspan=3)
Exemple #21
0
def init_gui():
    #themes = cfg['theme'].split(",")
    #gui.theme.load(themes)
    #gui.theme.load(['default','tools'])
    global top
    top = gui.Desktop(theme=gui.Theme(['default', 'tools']))
Exemple #22
0
def main():
    whereami = os.path.dirname(os.path.realpath(__file__))
    # Parse arguments
    p = argparse.ArgumentParser(description="A pygame GUI for Home Assistant.")
    p_config = p.add_argument_group('Configuration')
    p_config.add_argument('-c',
                          '--config',
                          help="config file to use",
                          required=True,
                          type=argparse.FileType('r'))
    p_config.add_argument('-f',
                          '--framebuffer',
                          help="Use this framebuffer as output for the UI\
    (defaults to window mode)",
                          default=None,
                          type=str,
                          metavar="/dev/fbX")
    p_config.add_argument('-t',
                          '--touchscreen',
                          help="Enable touchscreen integration.\
     Use this as event input",
                          default=None,
                          type=str,
                          metavar="/dev/input/eventX")
    p_config.add_argument('-n',
                          '--no-display',
                          help="We don't have a display. Sets the\
   SDL_VIDEODRIVER to \"dummy\". Usefull for testing",
                          dest="dummy",
                          action="store_true",
                          default=False)
    p_config.add_argument('--width',
                          help="The width of the display or window",
                          dest="width",
                          type=int,
                          default=False)
    p_config.add_argument('--heigth',
                          help="The height of the display or window",
                          dest="height",
                          type=int,
                          default=False)
    p_homeassistant = p.add_argument_group(
        'HomeAssistant', " (optional) Parameters to override the config file")
    p_homeassistant.add_argument('-H',
                                 '--homeassistant',
                                 default=None,
                                 help="The location of home-assistant",
                                 metavar="host.name")
    p_homeassistant.add_argument('-p',
                                 '--port',
                                 default=None,
                                 help="the port to use for home-assistant\
     (default: 8123)",
                                 type=int)
    p_homeassistant.add_argument(
        '-k',
        '--key',
        default=None,
        help="The api password to use (default: None)",
        type=str)
    p_homeassistant.add_argument('-s',
                                 '--ssl',
                                 help="Use ssl (default false)",
                                 default=False,
                                 action="store_true")
    p_logging = p.add_argument_group('Logging', " (optional) Logging settings")
    p_logging.add_argument('-v',
                           '--verbose',
                           help="Log output",
                           default=False,
                           action="store_true")
    p_logging.add_argument(
        '-L',
        '--logLevel',
        dest="logLevel",
        help="Log level to use (default: ERROR)",
        choices=["INFO", "WARNING", "ERROR", "CRITICAL", "DEBUG"],
        default="ERROR",
        type=str)
    p_logging.add_argument(
        '-l',
        '--logfile',
        help="Instead of logging to stdout, log to this file",
        default=None)
    args = p.parse_args()

    # Setup logger
    logFormat = "%(asctime)s [%(threadName)s:%(name)s]\
 [%(levelname)-5.5s]  %(message)s"

    logFormatter = logging.Formatter(logFormat)
    log = logging.getLogger("HUD")
    log.setLevel(getattr(logging, args.logLevel.upper()))
    if args.verbose:
        if not args.logfile:
            consoleHandler = logging.StreamHandler(sys.stdout)
            consoleHandler.setFormatter(logFormatter)
            log.addHandler(consoleHandler)
        else:
            fileHandler = logging.FileHandler(str(args.logfile))
            fileHandler.setFormatter(logFormatter)
            log.addHandler(fileHandler)
    # Setup Home assistant config
    log.info("Startup: Load config")
    config = configparser.ConfigParser()
    config.read(args.config.name)
    print(config.sections())
    try:
        haconfig = {
            "host": (args.homeassistant if args.homeassistant else
                     config["HomeAssistant"]["Host"]),
            "port":
            (args.port if args.port else config["HomeAssistant"]["Port"]),
            "ssl": (args.ssl if args.ssl else config["HomeAssistant"]["SSL"]),
            "key":
            (args.key if args.key else config["HomeAssistant"]["Password"])
        }
    except KeyError as e:
        log.error("Cannot find section [{}] in config file '{}'!".format(
            str(e), str(args.config.name)))
        exit(1)

    # Setup home assistant connection
    log.info("Startup: Create EventHandler")
    hass = remote.API(haconfig['host'], haconfig['key'], haconfig['port'],
                      haconfig['ssl'])
    HAE = HAWebsocketEventHandler(settings=haconfig)
    try:
        validation = remote.validate_api(hass)
        if str(validation) != "ok":
            log.info("Startup: Successfully connected to HomeAssistant!")
            raise Exception(validation)

    except Exception as e:
        log.error("hass connection verification failed: {}".format(
            str(validation)))
        exit(1)
    # Start the EventDaemon
    log.info("Startup: start HAWebsocketEventHandler")
    HAE.start()
    log.info("Startup: start EventWorker")
    eventWorker.start(1, HAE)
    log.info("Startup: Setting screen")
    width = args.width
    height = args.height
    if args.framebuffer:
        log.info("Startup: Setting framebuffer")
        os.putenv('SDL_VIDEODRIVER', 'fbcon')
        os.putenv('SDL_FBDEV', args.framebuffer)
    if args.touchscreen:
        log.info("Startup: Setting up touchscreen support")
        os.putenv('SDL_MOUSEDRV', 'TSLIB')
        os.putenv('SDL_MOUSEDEV', args.touchscreen)
    if args.dummy:
        os.putenv('SDL_VIDEODRIVER', 'dummy')
    if args.framebuffer:
        pygame_opts = FULLSCREEN | HWSURFACE | DOUBLEBUF
        #                         ^UNTESTED!^
    else:
        pygame_opts = SWSURFACE
    screen = pygame.display.set_mode((width, height), pygame_opts)

    if args.touchscreen:
        # Hide the mouse cursor if we have a touchscreen
        pygame.mouse.set_visible(False)
    pygame.display.set_caption("HUD")
    screen.fill([200, 200, 200])
    pygame.display.update()
    log.info("Startup: Load Theme")
    app = gui.Desktop(theme=gui.Theme(whereami + "/elements/pgu.theme"))
    app.connect(gui.QUIT, app.quit, None)
    timeout = 5
    while timeout != 0:
        if HAE.authenticated:
            pygame_print("Connected. Loading view...", screen, 10, height / 2)
            break
        else:
            timeout -= 1
            log.info("Waiting for connection")
            pygame_print("Connecting to home assistant", screen, 10,
                         height / 2)
            time.sleep(1)
    if not HAE.authenticated:
        log.error("Connection failed")
        pygame_print("Connection failed", screen, 10, height / 2)
        time.sleep(2)
        sys.exit(1)

    view = renderer.renderConfig(remote.get_states(hass), width, height,
                                 config, HAE)

    RunPlease = True
    while RunPlease:
        try:
            app.run(view, screen=screen)
        except (KeyboardInterrupt, SystemExit):
            log.warning("Got Exit or Ctrl-C. Stopping.")
            RunPlease = False
            pass
        except AttributeError as e:
            log.exception(e)
            log.error("AttributeError, restarting")
            sys.exit(1)

    HAE.stop()
    eventWorker.stop()
    sys.exit(0)
def GuiSetup():
    global app
    global MotorMin, MotorMax
    global LSlider, RSlider, FSlider, ASlider
    global speedLbl, depLbl, preLbl, depInput
    global pSwitch, Pbox, Ibox, Dbox

    app = gui.Desktop()
    app.connect(gui.QUIT, app.quit, None)

    Main = gui.Table(width=900)
    Main.tr()

    # c.tr() makes a row
    # c.td(component) creates a cell

    # Top panel for displaying network status and emergancy options
    n = gui.Table()
    n.tr()

    n.td(gui.Label("Network: Status"), height=40)
    n.td(gui.Label("       "))
    emergeButton = gui.Button("In Case of Emergency")
    emergeButton.connect(gui.CLICK, emergeClick)
    n.td(emergeButton)

    #Make sub tabels to be put into c that hold seperate elements.

    #tabel on the "west" side of the frame.
    w = gui.Table()
    w.tr()
    #Radio button group
    w.tr()
    w1 = gui.Table()

    w1.tr()
    w1.td(gui.Label("PID Controls"), colspan=5, height=50)
    w1.tr()
    pidSwitch = gui.Switch(value=False)
    pidSwitch.connect(gui.CLICK, arm_disarm_Component, 0)
    w1.td(pidSwitch)
    w1.td(gui.Label("Arm "))
    w1.td(gui.Label(""), width=95, height=30)
    pidButton1 = gui.Button("Hover")
    pidButton1.connect(gui.CLICK, pidHover)
    w1.td(pidButton1, align=1)

    w.td(w1, align=-1)

    w.tr()
    w2 = gui.Table()

    w2.tr()
    depInput = gui.Input(size=6)
    w2.td(depInput, align=-1)
    w2.td(gui.Label("m "), align=-1, width=30, height=30)
    pidButton2 = gui.Button("Go to depth")
    pidButton2.connect(gui.CLICK, pidGoDepth)
    w2.td(pidButton2, align=1)

    w.td(w2, align=-1)

    #Sliders to control coeficients
    w.tr()
    w3 = gui.Table()

    #P
    w3.tr()
    #w3.td(gui.Label("Stable "))
    Pbox = gui.Input(value="0", height=16, width=120)
    w3.td(Pbox)
    w3.td(gui.Label(" Quick"), align=-1)

    #I
    w3.tr()
    #w3.td(gui.Label("Stable "))
    Ibox = gui.Input(value="0", height=16, width=120)
    w3.td(Ibox)
    w3.td(gui.Label(" Accurate"), align=-1)

    #D
    w3.tr()
    #w3.td(gui.Label("Cautious "))
    Dbox = gui.Input(value="0", height=16, width=120)
    w3.td(Dbox)
    w3.td(gui.Label(" Responsive"), align=-1)

    w.td(w3, align=-1)

    #Restore PID defaults button
    w.tr()
    w4 = gui.Table()

    w4.tr()
    pidButton3 = gui.Button("Restore PID Defaults")
    pidButton3.connect(gui.CLICK, pidDefault)
    w4.td(pidButton3, valign=1)
    w4.td(gui.Label(""), height=30)

    ##    w4.tr()
    ##    pidButton4 = gui.Button("Auto-Calibrate")
    ##    pidButton4.connect(gui.CLICK, pidCalibrate)
    ##    w4.td(pidButton4)
    ##    w4.td(gui.Label(""), height = 30)

    w.td(w4, align=-1)

    #Second panel under top panel for depth, pressure, and subsytems label
    w.tr()
    w5 = gui.Table()

    w5.tr()
    w5.td(gui.Label("Depth "), height=30, align=-1)
    depLbl = gui.Input("0", size=6)
    w5.td(depLbl, align=1)
    w5.td(gui.Label(" m"))
    w5.tr()
    w5.td(gui.Label("Pressure "), align=-1)
    preLbl = gui.Input("0", size=6)
    w5.td(preLbl, align=1)
    w5.td(gui.Label(" kPa"))

    w.td(w5, align=-1)

    #Soleniod controls
    w.tr()
    w.td(gui.Label("Solenoid Controls "), height=30, align=-1)
    w.tr()
    w6 = gui.Table()
    w6.tr()

    sol0 = gui.Switch(false)
    sol0.connect(gui.CLICK, fireSol, 0)
    w6.td(sol0)

    sol1 = gui.Switch(false)
    sol1.connect(gui.CLICK, fireSol, 1)
    w6.td(sol1)

    sol2 = gui.Switch(false)
    sol2.connect(gui.CLICK, fireSol, 2)
    w6.td(sol2)

    sol3 = gui.Switch(false)
    sol3.connect(gui.CLICK, fireSol, 3)
    w6.td(sol3)

    sol4 = gui.Switch(false)
    sol4.connect(gui.CLICK, fireSol, 4)
    w6.td(sol4)

    sol5 = gui.Switch(false)
    sol5.connect(gui.CLICK, fireSol, 5)
    w6.td(sol5)

    sol6 = gui.Switch(false)
    sol6.connect(gui.CLICK, fireSol, 6)
    w6.td(sol6)

    sol7 = gui.Switch(false)
    sol7.connect(gui.CLICK, fireSol, 7)
    w6.td(sol7)

    sol8 = gui.Switch(false)
    sol8.connect(gui.CLICK, fireSol, 8)
    w6.td(sol8)

    sol9 = gui.Switch(false)
    sol9.connect(gui.CLICK, fireSol, 9)
    w6.td(sol9)

    w.td(w6, align=0)

    w.tr()
    w.td(gui.Label("0 1 2 3 4 5 6 7 8 9"), height=30, align=0)

    # Center tabel that holds all the navigation data.
    c = gui.Table()

    #verticle sliders for motor bars and space for surface.
    c.tr()

    c1 = gui.Table()
    c1.tr()
    LSlider = gui.VSlider(value=0,
                          min=Motormin,
                          max=Motormax,
                          size=20,
                          height=120,
                          width=16)
    RSlider = gui.VSlider(value=0,
                          min=Motormin,
                          max=Motormax,
                          size=20,
                          height=120,
                          width=16)
    FSlider = gui.VSlider(value=0,
                          min=Motormin,
                          max=Motormax,
                          size=20,
                          height=120,
                          width=16)
    ASlider = gui.VSlider(value=0,
                          min=Motormin,
                          max=Motormax,
                          size=20,
                          height=120,
                          width=16)
    c1.td(LSlider, width=20, valign=1)
    c1.td(RSlider, width=20, valign=1)
    c1.td(gui.Label("  Surface  "), height=180, width=240)
    c1.td(FSlider, width=20, valign=1)
    c1.td(ASlider, width=20, valign=1)
    c1.tr()
    c1.td(gui.Label("L"))
    c1.td(gui.Label("R"))
    c1.td(gui.Label(""))
    c1.td(gui.Label("F"))
    c1.td(gui.Label("A"))

    c.td(c1)

    # Motor duty cycle bar.
    c.tr()

    c2 = gui.Table()
    c2.tr()
    c2.td(gui.Label(" Motor Duty Cycle "), height=50, colspan=3, valign=1)
    c2.tr()
    c2.td(gui.Label("0 "), height=30)
    MotormaxS = gui.HSlider(value=25,
                            min=0,
                            max=127,
                            size=20,
                            height=16,
                            width=120)
    MotormaxS.connect(gui.CHANGE, setMotorMax, MotormaxS)
    c2.td(MotormaxS)
    c2.td(gui.Label(" 100"))

    c.td(c2)

    #motor configuration graphic
    c.tr()

    c3 = gui.Table()
    c3.tr()
    c3.td(gui.Label(""), height=30)
    c3.tr()
    c3.td(gui.Label(" Motor Configuration "))
    c3.tr()
    c3.td(gui.Label("  Surface  "), height=150, width=150)
    c3.tr()
    c3.td(gui.Label(""), height=30)

    c.td(c3)

    #Radio Buttons for controling pitch and button for speed cycle.
    c.tr()

    c4 = gui.Table()
    c4.tr()
    pSwitch = gui.Switch(value=False)
    pSwitch.connect(gui.CLICK, arm_disarm_Component, 4)
    c4.td(pSwitch)
    c4.td(gui.Label("Pitch on"))
    c4.td(gui.Label("     "))

    spdCycButton = gui.Button("Speed Cycle")
    spdCycButton.connect(gui.CLICK, speedCycle)
    c4.td(spdCycButton)

    c4.tr()
    speedLbl = gui.Input("1/1", size=4, align=1)
    c4.td(speedLbl, colspan=4, align=1)

    c.td(c4)

    # East tabel for hold all the subsystems functions.
    e = gui.Table(width=200)
    e.tr()
    e.td(gui.Label(" Subsystems "), height=50)

    e.tr()

    sysSelectGroup = gui.Group(value=0)

    disarmRadio = gui.Radio(sysSelectGroup, value=0)
    disarmRadio.connect(gui.CLICK, arm_disarm_Component, 5)

    e0 = gui.Table()
    e0.tr()
    e0.td(disarmRadio, width=20)
    e0.td(gui.Label("Disarm All"))

    e.td(e0)

    # Critter Getter functions.
    e.tr()

    e1 = gui.Table()
    e1.tr()

    e1a = gui.Table()
    e1a.tr()
    e1a.td(gui.Label("Critter Getter"), height=29, align=-1)
    e1a.td(gui.Label(), width=30)
    cgRadio = gui.Radio(sysSelectGroup, value=1)
    cgRadio.connect(gui.CLICK, arm_disarm_Component, 1)
    e1a.td(cgRadio)
    e1a.td(gui.Label("Arm "))
    e1a.td(gui.Label(""), height=29, width=20)
    e1.td(e1a, align=-1)

    e1.tr()
    e1b = gui.Table()
    e1b.tr()
    e1b.td(gui.Label("Status: "), height=29, align=-1)
    critLbl = gui.Input(size=15)
    e1b.td(critLbl)
    e1.td(e1b, align=-1)

    e1.tr()

    e1b = gui.Table()
    e1b.tr()
    cgButton1 = gui.Button("Flush")
    cgButton2 = gui.Button("Extend")

    cgButton1.connect(gui.CLICK, operateWC, 1)
    cgButton2.connect(gui.CLICK, operateWC, 2)

    e1b.td(cgButton1)
    e1b.td(gui.Label(""), height=29)
    e1b.td(cgButton2)
    e1.td(e1b, align=-1)

    e.td(e1, height=120, align=-1)

    #Water Collecter functions.
    e.tr()

    e2 = gui.Table()
    e2.tr()

    e2a = gui.Table()
    e2a.tr()
    e2a.td(gui.Label("Water Collecter"), height=29, align=-1)
    e2a.td(gui.Label(), width=30)
    wcRadio = gui.Radio(sysSelectGroup, value=2)
    wcRadio.connect(gui.CLICK, arm_disarm_Component, 2)
    e2a.td(wcRadio)
    e2a.td(gui.Label("Arm "))
    e2a.td(gui.Label(""), height=29, width=20)
    e2.td(e2a, align=-1)

    e2.tr()
    e2b = gui.Table()
    e2b.tr()
    e2b.td(gui.Label("Status: "), height=29, align=-1)
    wcLbl = gui.Input(size=15)
    e2b.td(wcLbl)
    e2.td(e2b, align=-1)

    e2.tr()
    e2c = gui.Table()
    e2c.tr()
    wcButton = gui.Button("Operate")
    e2c.td(wcButton, height=29)
    e2.td(e2c, align=-1)

    e.td(e2, height=120, align=-1)

    #Cap and trade functions.
    e.tr()

    e3 = gui.Table()
    e3.tr()

    #CandTarm_disarm = gui.Group(value = 2)
    e3a = gui.Table()
    e3a.tr()
    e3a.td(gui.Label("Cap and Trade"), height=29, align=-1)
    e3a.td(gui.Label(), width=30)
    ctRadio = gui.Radio(sysSelectGroup, value=3)
    ctRadio.connect(gui.CLICK, arm_disarm_Component, 3)
    e3a.td(ctRadio)
    e3a.td(gui.Label("Arm "))
    e3a.td(gui.Label(""), height=29, width=20)
    e3.td(e3a, align=-1)

    e3.tr()
    e3b = gui.Table()
    e3b.tr()
    e3b.td(gui.Label("Status: "), height=29, align=-1)
    ctLbl = gui.Input(size=15)
    e3b.td(ctLbl)
    e3.td(e3b, align=-1)

    e3.tr()
    ctButton1 = gui.Button("Operate")
    e3.td(ctButton1, height=29, align=-1)

    e.td(e3, height=120, align=-1)

    #put it together.
    Main.tr()
    Main.td(n, colspan=3)
    Main.tr()
    Main.td(gui.Label(""), height=30)
    Main.tr()
    Main.td(w, valign=-1)
    Main.td(c, valign=-1)
    Main.td(e, valign=-1)
    Main.tr()
    Main.td(gui.Label(""), height=30)

    app.init(Main)  #Main is main tabel.
Exemple #24
0
    def start(self, score):
        self.highEnd = 0
        clock = pygame.time.Clock()

        if (score > 0):
            position = self.myScores.check(score)
            if (position != None):
                app = gui.Desktop()
                app.connect(gui.QUIT, app.quit, None)
                main = gui.Container(
                    width=500, height=400)  #, background=(220, 220, 220) )
                positionText = "You are " + PositionText(
                    position) + " on the High Score table!!"
                main.add(gui.Label(positionText, cls="h1"), 20, 20)
                td_style = {'padding_right': 10}
                t = gui.Table()
                t.tr()
                t.td(gui.Label('Type your name:'), style=td_style)
                userName = gui.Input()
                t.tr()
                t.td(userName, style=td_style)
                b = gui.Button("Done")
                b.connect(gui.CLICK, app.quit, None)
                t.td(b, style=td_style)
                main.add(t, 20, 100)
                app.run(main)
                if (userName.value != ""):
                    position = self.myScores.submit(score,
                                                    userName.value[0:15], None)
            else:
                app = gui.Desktop()
                app.connect(gui.QUIT, app.quit, None)
                main = gui.Container(
                    width=500, height=400)  #, background=(220, 220, 220) )
                main.add(
                    gui.Label("Sorry you didn't get a high score", cls="h1"),
                    20, 20)
                td_style = {'padding_right': 10}
                t = gui.Table()
                t.tr()
                b = gui.Button("Done")
                b.connect(gui.CLICK, app.quit, None)
                t.td(b, style=td_style)
                main.add(t, 20, 100)
                app.run(main)

        #Draw background
        pygame.draw.rect(self.screen, (255, 255, 255),
                         pygame.Rect(0, 0, self.SCREEN_W, self.SCREEN_H))

        #Draw Highscore Table
        self.scoretable = ""

        #data contains the html to be parsed on to the screen. This section sets up the table and the table headers
        data = "<table border=1 width=100% align='center' style='border:1px; border-color: #000088; background: #ccccff; margin: 20px; padding: 20px;'>"
        data += "<tr><td width=100%><b>Position</b></td><td width=100%><b>Player</b></td><td width=100%><b>Score</b></td></tr>"

        count = 0
        #Iterate each item in the high score list and add each as a row to the table
        for e in self.myScores:
            data += "<tr>"
            data += "<td>"
            data += PositionText(count)
            data += "</td>"
            data += "<td>"
            data += e.name
            data += "</td>"
            data += "<td>"
            data += str(e.score)
            data += "</td>"
            data += "</tr>"
            count = count + 1

        #Close the table
        data += "</table>"

        #Now that we've finished readin from the highscores, save it back to the .txt file
        self.hiScore.save()

        #Display the table until the user exits
        while (self.highEnd == 0):
            self.__handleUserInteraction()
            html.write(self.screen, self.font, pygame.Rect(300, 25, 700, 700),
                       data)
            pygame.display.flip()
        pygame.event.clear()
        return self.highEnd
Exemple #25
0
    def gen_gui(self):
        from omnitool.shared import theme, lang, exit_prog
        from omnitool.pgu_override import Quitbutton
        pygame.display.init()
        pygame.display.set_caption("Maze World Generator")
        app = gui.Desktop(theme=theme)
        main = gui.Table(width=800)
        app.connect(gui.QUIT, exit_prog, None)

        main.td(gui.Label("Maze Blocks: "))
        tileFrom = gui.List(300, 150)
        for tile in db.tiles:
            if db.tiles.index(tile) not in db.multitiles and db.tiles.index(
                    tile) in clib.data:
                tileFrom.add(gui.Label(tile), value=db.tiles.index(tile))
        main.td(tileFrom)

        #        main.td(gui.Label("Light up maze?"))
        #        polkaDotButton = (gui.Switch(False))
        #        main.td(polkaDotButton)

        main.tr()

        main.td(gui.Label("Maze BackWalls: "))
        tileInto = gui.List(300, 150)
        for wall in db.walls:
            if db.walls.index(wall) in clib.walldata:
                tileInto.add(gui.Label(wall), value=db.walls.index(wall))
        main.td(tileInto)

        #        main.td(gui.Label("View generation?"))
        viewGenButton = (gui.Switch(False))
        #        main.td(viewGenButton)

        main.tr()

        main.td(gui.Label("World Size: "))
        size = gui.List(110, 50)
        size.add("Tiny", value=3)
        size.add("Small", value=0)
        size.add("Medium", value=1)
        size.add("Large", value=2)
        main.td(size)

        main.td(gui.Label("Complexity: "))
        scale = gui.List(110, 50)
        scale.add("Insane", value=3)
        scale.add("Medium", value=6)
        scale.add("Easy", value=9)
        main.td(scale)

        main.tr()
        main.td(Quitbutton(app, lang.pt_start), colspan=4)

        app.run(main)
        pygame.display.quit()

        self.tileFrom = clib.data[tileFrom.value]
        self.tileInto = clib.walldata[tileInto.value]
        self.size2 = size.value
        self.scale2 = scale.value
        self.viewGen = viewGenButton.value
Exemple #26
0
def run(main=None):
    from omnitool.shared import lang, theme, exit_prog, __version__
    from omnitool.pgu_override import Quitbutton

    pygame.display.init()
    pygame.display.set_caption("Planetoids & Terra Generator")
    if main == None:
        app = gui.Desktop(theme=theme)
        main = gui.Table()
        app.connect(gui.QUIT, exit_prog, None)
    else:
        main = gui.Table()
        app = gui.Dialog(gui.Label("Planetoids and Terra Generator"), main)

    main.td(gui.Label(lang.pt_name), align=-1)
    nameinput = gui.Input("Planetoids OT-V" + str(__version__), width=237)
    main.td(nameinput, colspan=2)
    main.tr()

    main.td(gui.Label(lang.pt_mode), align=-1)
    method = gui.Select(width=250)
    method.add(lang.pt_small, (1, 0))
    method.add(lang.pt_medium, (2, 0))
    method.add(lang.pt_large, (3, 0))
    method.add(lang.pt_square, (4, 0))
    method.add(lang.pt_both, (3, 1))
    method.add(lang.pt_square_terra, (4, 2))
    method.value = (3, 0)
    main.td(method, colspan=2)
    main.tr()

    main.td(gui.Label(lang.pt_start_sel), align=-1)
    time = gui.Select(width=250)

    time.add(lang.pt_morning, 2)
    time.add(lang.pt_day, 1)
    time.add(lang.pt_night, 3)
    time.add(lang.pt_bloodmoon, 4)
    time.value = 1
    main.td(time, colspan=2)
    main.tr()
    main.td(gui.Spacer(1, 24))
    main.tr()
    main.td(gui.Label(lang.pt_extras), align=-1, colspan=3)
    main.tr()
    main.td(gui.Label(lang.pt_sun), align=-1)
    darkness = gui.Switch()
    darkness.value = True
    main.td(darkness, colspan=2)
    main.tr()

    main.td(gui.Label(lang.pt_atlantis), align=-1)
    atlantis = gui.Switch()
    atlantis.value = False
    main.td(atlantis, colspan=2)
    main.tr()

    main.td(gui.Label(lang.pt_merchant), align=-1)
    merch = gui.Switch()
    merch.value = True
    main.td(merch, colspan=2)
    main.tr()
    main.td(gui.Label(lang.pt_lloot), align=-1)
    loot = gui.Switch()
    loot.value = False
    main.td(loot, colspan=2)
    main.tr()

    main.td(gui.Label("Hardmode:"), align=-1)
    hard = gui.Switch()
    hard.value = False
    main.td(hard, colspan=2)
    main.tr()
    main.td(gui.Label(lang.pt_mirror), align=-1)
    mirror = gui.Switch()
    mirror.value = False
    main.td(mirror, colspan=2)
    main.tr()
    # main.td(gui.Label(lang.pt_pre), align = -1)
    pre = gui.Switch()
    pre.value = False
    #main.td(pre, colspan = 2)

    #main.tr()
    main.td(gui.Spacer(1, 12))
    main.tr()
    main.td(Quitbutton(app, lang.pt_start), colspan=3)
    main.tr()
    main.td(gui.Spacer(1, 12))

    if app.__class__.__name__ == "Desktop":
        app.run(main)
        pygame.display.quit()
        return (nameinput.value, method.value, time.value, darkness.value,
                atlantis.value, merch.value, loot.value, hard.value,
                mirror.value, pre.value)
    else:
        app.open()
Exemple #27
0
    def genGui(self):
        from omnitool import themename, Theme, lang, exit_prog

        theme = Theme(themename)

        class Quitbutton(gui.Button):
            def __init__(self, value="Finish"):
                gui.Button.__init__(self, value, width=60, height=40)
                try:
                    self.connect(gui.CLICK, app.quit, None)
                except AttributeError:
                    self.connect(gui.CLICK, app.close, None)

        pygame.display.init()

        pygame.display.set_caption("Header Modifier")

        app = gui.Desktop(theme=theme)

        main = gui.Table(width=300)

        app.connect(gui.QUIT, exit_prog, None)

        main.td(gui.Label("Spawn Point: "))
        X = gui.Input(value=self.header["spawn"][0], size=5)
        Y = gui.Input(value=self.header["spawn"][1], size=4)
        main.td(X)
        main.td(Y)
        main.tr()

        main.td(gui.Label("Hardmode: "))
        hardmode = gui.Switch(self.header["hardmode"])
        main.td(hardmode)

        main.td(gui.Label("Day: "))
        daytime = gui.Switch(self.header["is_day"])
        main.td(daytime)
        main.tr()

        main.td(gui.Label("Eye of Cthulhu killed: "))
        eoc = gui.Switch(self.header["bosses_slain"][0])
        main.td(eoc)

        main.td(gui.Label("Eater of Worlds killed: "))
        eow = gui.Switch(self.header["bosses_slain"][1])
        main.td(eow)
        main.tr()

        main.td(gui.Label("Skeletron killed: "))
        skelly = gui.Switch(self.header["bosses_slain"][2])
        main.td(skelly)

        main.td(gui.Label("Saved Goblin Tinkerer: "))
        tinkerbell = gui.Switch(self.header["npcs_saved"][0])
        main.td(tinkerbell)
        main.tr()

        main.td(gui.Label("Saved Mechanic: "))
        mech = gui.Switch(self.header["npcs_saved"][1])
        main.td(mech)

        main.td(gui.Label("Saved Wizard: "))
        wizziewizz = gui.Switch(self.header["npcs_saved"][2])
        main.td(wizziewizz)
        main.tr()

        main.td(gui.Label("Bloodmoon: "))
        bloodz = gui.Switch(self.header["is_bloodmoon"])
        main.td(bloodz)

        main.td(gui.Label("World Name: "))
        worldName = gui.Input(value=self.header["name"], size=8)
        main.td(worldName)
        main.tr()

        main.td(gui.Label("Invasion Type: "))
        # invasion = gui.Select()
        #invasion.add("None",0)
        #invasion.add("Goblin Invasion",1)
        #invasion.add("Frost Legion",2)
        invType = gui.List(110, 50)
        invType.add("None", value=0)
        invType.add("Goblin Invasion", value=1)
        invType.add("Frost Legion", value=2)

        if invType.value == None:
            invType.value = 0

        #main.td(invasion)
        main.td(invType)

        main.td(gui.Label("Invasion Amount (0-1000): "))
        invSize = (gui.Input(value=self.header["gob_inv_size"], size=8))
        main.td(invSize)
        main.tr()

        main.tr()

        main.td(Quitbutton(), colspan=4)

        app.run(main)

        pygame.display.quit()

        bosses = (int(eoc.value), int(eow.value), int(skelly.value))
        npcSaved = (int(tinkerbell.value), int(mech.value),
                    int(wizziewizz.value))

        self.header["spawn"] = (int(X.value), int(Y.value))
        self.header["hardmode"] = int(hardmode.value)
        self.header["is_day"] = int(daytime.value)
        self.header["bosses_slain"] = bosses
        self.header["is_bloodmoon"] = int(bloodz.value)
        self.header["name"] = worldName.value
        self.header["gob_inv_size"] = int(invSize.value)
        self.header["gob_inv_type"] = int(invType.value)
        self.header["npcs_saved"] = npcSaved
Exemple #28
0
import pygame
from pygame.locals import *

# the following line is not needed if pgu is installed
import sys
sys.path.insert(0, "..")

from pgu import gui

# Load an alternate theme to show how it is done. You can also
# specify a path (absolute or relative) to your own custom theme:
#
#   app = gui.Desktop(theme=gui.Theme("path/to/theme"))
#
app = gui.Desktop()
app.connect(gui.QUIT, app.quit, None)

##The table code is entered much like HTML.
##::
c = gui.Table()

c.tr()
c.td(gui.Label("Gui Widgets"), colspan=4)


def cb():
    print("Clicked!")


btn = gui.Button("Click Me!")
Exemple #29
0
    def gen_gui(self):
        #get theme, language and end process function from omnitool API
        from omnitool.shared import lang, theme, exit_prog, exit_prog
        from omnitool.pgu_override import Quitbutton

        #initilize pygame renderer
        pygame.display.init()
        #set window title to Flatworld, from language file
        pygame.display.set_caption(lang.flat)
        #application interface
        app = gui.Desktop(theme=theme)
        #main container, table
        main = gui.Table(width=800)
        #connect the QUIT event with Omnitool API exit_prog
        app.connect(gui.QUIT, exit_prog, None)
        #add label size to table
        main.td(gui.Label(lang.fw_size))
        #size drop down selection
        size = gui.Select(width=300)
        size.add(lang.fw_tiny, 4)
        size.add(lang.fw_small, 0)
        size.add(lang.fw_medium, 1)
        size.add(lang.fw_large, 2)
        size.add(lang.fw_square, 3)
        size.value = 0
        #add it to the table
        main.td(size)
        #surface label
        main.td(gui.Label(lang.fw_surf))

        surf = [
            "Grass Block", "Corrupt Grass Block", "Jungle Grass Block",
            "Mushroom Grass Block", "Hallowed Grass Block"
        ]
        #surface drop down menu
        sur = gui.Select(width=300)
        sur.add("None", None)
        for grass in surf:
            sur.add(grass, tiles.index(grass))
        sur.value = None
        #add surface selection to table
        main.td(sur)

        #go to next line in table
        main.tr()
        #add tile label to table
        main.td(gui.Label(lang.fw_tile))
        #create tile list
        tiles_ = gui.List(300, 150)
        for tile in tiles:
            if tiles.index(tile) not in multitiles:
                tiles_.add(gui.Label(tile), value=tiles.index(tile))
        #add tile list to table
        main.td(tiles_)
        #add wall label to table
        main.td(gui.Label(lang.fw_wall))
        #create wall list
        guiwalls = gui.List(300, 150)
        for wall in walls:
            guiwalls.add(gui.Label(wall), value=walls.index(wall))
        #add wall list to table
        main.td(guiwalls)
        #next row
        main.tr()
        #Generate! button
        main.td(Quitbutton(app, lang.pt_start), colspan=4)
        #run the application and open the window
        app.run(main)
        #when it's done, instruct pygame to clean up
        pygame.display.quit()
        #attach data to plugin, to be used in run()
        self.surface = sur.value
        self.wall = guiwalls.value
        self.tile = tiles_.value
        self.size = size.value
        if self.wall == 0:
            self.wall = None
Exemple #30
0
"""<title>an example of html within gui</title>"""
import pygame
from pygame.locals import *

# the following line is not needed if pgu is installed
import sys
sys.path.insert(0, "..")

from pgu import gui
from pgu import html

app = gui.Desktop(width=780, height=500)

data = """
<h1>header 1</h1>
<h2>header 2</h2>
<h3>header 3</h3>
<p>this is normal <b>this is bold</b> <i>this is italic</i> <u>this is underline</u></p>

<table border=1 bgcolor='yellow' width=200 align=center>
    <tr>
    <th bgcolor='#ffffee'>pgu
    <th bgcolor='red'>red
    <th bgcolor='green'>green
    <th bgcolor='blue'>blue
    
    <tr>
    <td bgcolor='white' border=1><img src='logo.gif'>
    <td border=1 style='padding:4px'>things:<br>apples,<br>fire trucks,<br>crabs,<br>and cherries
    <td border=1 style='padding:4px'>things: <ul>
        <li>grass