예제 #1
0
def resolution_requester(open_gui=True):
    if open_gui:
        window_mode = pymsgbox.confirm(text='Select your screen mode',
                                       title='AMOS DEMO',
                                       buttons=['Windowed', 'Fullscreen'])

        if window_mode == 'Windowed':
            demo_screen_size[2] = gs.Window.Windowed
            screen_resolutions = ['640x480', '720x568', '800x600', '1280x800']
        elif window_mode == 'Fullscreen':
            demo_screen_size[2] = gs.Window.Fullscreen
            screen_resolutions = [
                '640x480', '800x600', '1280x720', '1280x800', '1920x1080'
            ]
        else:
            return False

        screen_res = pymsgbox.confirm(text='Select your screen resolution',
                                      title='AMOS DEMO',
                                      buttons=screen_resolutions)

        if screen_res is not None:
            demo_screen_size[0] = int(screen_res.split('x')[0])
            demo_screen_size[1] = int(screen_res.split('x')[1])
        else:
            return False

    return True
예제 #2
0
def gamewin():
    for i in range(0, 8):
        if circlepositionList[i] == []:
            mb.confirm("Circle win the game", "Win game")
            quit()
    for i in range(0, 8):
        if crosepositionList[i] == []:
            mb.confirm("Crose win the game", "Win game")
            quit()
예제 #3
0
def test(Prix):

    #génération d'un prix aléatoire
    boisson = generation_nom_boisson(Prix)
    #Msg Box popup pour poser la question sur cettte boisson
    proposition_de_demarage_du_jeu = pymsgbox.alert(
        'Quel est le prix de:' + " " + boisson, 'La devinette',
        "Allez je me le tente!")

    response = pymsgbox.prompt('Vas-y propose ton prix !!?')
    #si la réponse est la bonne
    if response == str(Prix[boisson]):
        resultat = pymsgbox.confirm(
            'Bien ouej! Tu veux rejouer tout de suite ou reprendre plus tard?',
            'Fin du game?', ["Je rejoue!", 'La flemme!'])

        #si le user veut rejouer --> boucle sur la génération aléatoire d'un nom de boisson
        if resultat == "Je rejoue!":
            test(Prix)
        elif resultat == "La flemme!":
            pymsgbox.alert('A plus tard !', 'Fin du Game !!!', "A + !")
    #sinon, si la réponse est fausse
    elif response == None:
        pymsgbox.alert('A plus tard !', 'Fin du Game !!!', "A + !")
    else:
        resultat = pymsgbox.confirm(
            'Et non t es pas encore au point sur ta carte, Tu veux une deuxième chance ou tu veux la réponse desuite?',
            'Fin du game?',
            ["Deuxième chance!", 'La flemme balance la réponse!'])
        #si il y a 2e essaie alors le résultat de pymsgbox.confirm nous permet de boucler sur response
        if resultat == "Deuxième chance!":
            #boucle sur response
            response = pymsgbox.prompt(
                'Attention, deuxième chance pour le prix de/du ' + " " +
                boisson, 'La devinette')
            if response == str(Prix[boisson]):
                resultat = pymsgbox.confirm('Top! 2e round concluant!',
                                            'Fin du game?',
                                            ["Je rejoue!", 'La flemme!'])
                #si le user veut rejouer --> boucle sur la génération aléatoire d'un nom de boisson
                if resultat == "Je rejoue!":
                    test(Prix)
                elif resultat == "La flemme!":
                    pymsgbox.alert('A plus tard !', 'Fin du Game !!!', "A + !")
            elif response == None:
                pymsgbox.alert('A plus tard !', 'Fin du Game !!!', "A + !")
            else:
                pymsgbox.alert(
                    "La réponse est .... :" + "\n" + str(Prix[boisson]) +
                    " ma gueule :) ! ", 'Fin du Game !!!',
                    "OK maintenant c dans ma ptite tête !!")
        else:
            pymsgbox.alert(
                "La réponse est .... :" + "\n" + str(Prix[boisson]) +
                " ma gueule :) ! ", 'Fin du Game !!!',
                "OK maintenant c dans ma ptite tête !!")
예제 #4
0
    def check_found_elements(self, element_identifiers, element_type, parent_element_xpath, training_stage):

        with open("/tmp/no_js_dump.html") as oldfile, open("/tmp/highlighted_dump.html", 'w') as newfile:
            for line in oldfile:
                # Pre-editing for correct\ing body tag
                if "<body " in line or "<BODY " in line or "<body>" in line or "<BODY>" in line:
                    index = line.find('>')
                    output_line = line[:index] + " onload=\"highlightElements()\"" + line[index:]
                    line = output_line
                newfile.write(line)
                if "<head " in line or "<HEAD " in line or "<head>" in line or "<HEAD>" in line:
                    injected_content = ""
                    # Beautified snippets below
                    if element_type == ElementType.CLASS:
                        injected_content = "<script>function highlightElements(){var nodeList=document." \
                                           "querySelectorAll(\""
                        for element in element_identifiers:
                            element = element.replace(" ", ".")
                            injected_content += "." + element + ", "
                        injected_content = injected_content[:-2]
                        injected_content += "\");for(var i=0,length=nodeList.length;i<length;i+=1){nodeList[i].style." \
                                            "backgroundColor=\"yellow\";}}</script>"
                    else:
                        if element_type == ElementType.XPATH:
                            injected_content = "<script>function highlightElements(){var element_identifiers=["
                            for element in element_identifiers:
                                if (training_stage == TrainingStage.POST_COUNT) or (training_stage == TrainingStage.
                                        POST_AUTHOR) or (training_stage == TrainingStage.POST_CONTENT) or (
                                        training_stage == TrainingStage.POST_DATE):
                                    injected_content += "\"" + parent_element_xpath + "/" + element + "\","
                                else:
                                    injected_content += "\"" + element + "\","
                            injected_content += "];for(var j=0;j<element_identifiers.length;j+=1){result=document." \
                                                "evaluate(element_identifiers[j],document,null,XPathResult." \
                                                "ORDERED_NODE_SNAPSHOT_TYPE,null);for(var i=0;i<result.snapshotLength" \
                                                ";i+=1){result.snapshotItem(i).style.backgroundColor=\"yellow\"}}}" \
                                                "</script>"
                    newfile.write(injected_content)

        Popen(["sudo", "-u", "user", "/usr/lib/firefox/firefox", "-new-window", "-url",
               "file:///tmp/highlighted_dump.html", "-foreground"])

        sleep(5)

        if training_stage == TrainingStage.THREAD_NEXT_PAGE2:
            if pymsgbox.confirm('Is the content marked correctly?', 'Check', ['Yes', 'No']) == 'No':
                if pymsgbox.confirm('The buttons for going back are highlighted as well?', 'Check', ['Yes', 'No']) == 'No':
                    return 'No'
                else:
                    return 'Duplicate'
            else:
                return 'Yes'

        return pymsgbox.confirm('Is the content marked correctly?', 'Check', ['Yes', 'No'])
예제 #5
0
    def kill(self):
        self.root.withdraw()
        ans = pymsgbox.confirm(text="Kill Process",
                               title="Confirm Action",
                               buttons=["OK", "CANCEL"])
        if (ans != "OK"):
            return
        pid = int(self.str1.get())
        q = psutil.Process(pid)
        d_t = str(datetime.today())
        try:
            conn = MySQLdb.connect(host='localhost',
                                   user='******',
                                   password='******',
                                   database='process_manager')
            cursor = conn.cursor()
            cursor.execute(
                "insert into process(pid,name,username,status,time) values(%s,%s,%s,%s,%s)",
                (int(q.pid), q.name(), q.username(), q.status(), d_t[:-7]))
            conn.commit()
        except:
            conn.rollback()
            print("Error in updating database!")
        cursor.close()
        conn.close()

        try:
            s = "taskkill /pid '%d' /t /f"
            sc = subprocess.Popen(["powershell", s % pid],
                                  stdout=subprocess.PIPE)
            print(sc.communicate)
        except:
            print(" Taskkill Error")
        finally:
            self.root.deiconify()
예제 #6
0
def cb_button(n):
    global Buttons, msgBox, msgBoxWait
    if msgBoxWait is not None: return
    item = Buttons[n]
    w = item["button"]
    f = True
    if item["confirm"]:
        msgBox = tk.Toplevel()
        msgBox.geometry("250x100+" + str(w.winfo_rootx()) + "+" +
                        str(w.winfo_rooty()))
        msgBoxWait = msgBox.after(500, cb_lift)
        msg = item["message"]
        f = pymsgbox.confirm(root=msgBox,
                             text=msg,
                             buttons=['OK', 'NO', 'CANCEL'])
        msgBox.after_cancel(msgBoxWait)
        msgBoxWait = None
        msgBox.destroy()

        pub_msg = Bool()
        if f.startswith('C'):  #Cancel
            print "Button cancel:", item["label"]
        else:
            if f.startswith('O'):  #OK
                pub_msg.data = True
            rospy.loginfo("Button='%s' topic=%d", item["label"], pub_msg.data)
            item["pub"].publish(pub_msg)
    else:
        rospy.loginfo("Button='%s' topic=1", item["label"])
        item["pub"].publish(mTrue)
예제 #7
0
def confirmXcode():
    buttons_xcode_confirm = ['Ok', 'No-Way']
    xcode_confirm_output = pymsgbox.confirm(text=('Run Auto-Xcode?'), title='Pokemon H@ck', buttons=buttons_xcode_confirm)
    if (xcode_confirm_output == buttons_xcode_confirm[0]):
        run_app(projectDirectory)
    elif (buttons_xcode_confirm == buttons_xcode_confirm[1]):
        print("Skipping Default Xcode Config")
예제 #8
0
def check_request_status(req):
    # Check if response of request is good
    if req.status_code != 200:
        if req.status_code == 207:
            user_answer = pymsgbox.confirm(
                f"The request was only partially successful. Status code: {req.status_code}."
                f"To continue press 'OK'",
                title="Alert")
            if user_answer == 'Cancel':
                exit()

        elif req.status_code == 401:
            pymsgbox.alert(
                f"The request requires an authentication. Please check the API key Status code: {req.status_code}.",
                title="Error")
            exit()

        elif req.status_code == 403:
            pymsgbox.alert(
                f"The request was denied. Access is restricted. Status code: {req.status_code}",
                title="Error")
            exit()

        elif req.status_code == 413:
            pymsgbox.alert(
                f"Request is too large. Please consider reducing it. Status code: {req.status_code}",
                title="Error")
            exit()

        elif req.status_code == 429:
            pymsgbox.alert(
                f"Maximum limit of requests is exceeded. Please continue tomorrow. Status code: {req.status_code}",
                title="Error")
            exit()
예제 #9
0
def run(ticker, bool_batch=False):
    # Let user choose the solution for getting the data: Either scraping or using API
    if not bool_batch:
        scraping_method = pymsgbox.confirm(
            f'What method do you want to use to get the financial data from {ticker}?',
            'Select Option',
            buttons=['API', 'Web Scraping'])
    else:
        scraping_method = 'API'

    # Output folders
    work_directory = pathlib.Path(__file__).parent.absolute()
    excel_output_folder = os.path.join(work_directory, '../financial_files',
                                       'excel')
    json_output_folder = os.path.join(work_directory, '../financial_files',
                                      'json')
    excel_output_path = os.path.join(excel_output_folder, ticker + '.xlsx')
    json_output_path = os.path.join(json_output_folder, ticker + '.json')

    if scraping_method == 'Web Scraping':
        pymsgbox.alert(
            "Be aware that this option my not work due to possible scraping restrictions from website."
        )

        if not check_validity_output_file(excel_output_path) \
                or not excel_sheet_exists(excel_output_path, source=scraping_method):
            links = links_constructor(ticker)
            df_fs = scrape_tables(links)
        else:
            df_fs = excel_to_dataframe(excel_output_path,
                                       source=scraping_method)

    else:
        if not check_validity_output_file(json_output_path) \
                or not excel_sheet_exists(excel_output_path, source=scraping_method):
            json_file = get_api_request(ticker, bool_batch=bool_batch)
            save_json_request_to_file(json_file, json_output_path)
        else:
            with open(json_output_path, 'r') as file:
                json_file = json.load(file)

        df_fs = create_dataframe_from_api(json_file)

    # Get all the calculated ratios and relevant stock data
    results_df = get_rule_number1_ratios(df_fs, ticker)

    # Output all the financial data into an excel file
    dataframe_to_excel(excel_output_path,
                       df_fs,
                       ticker,
                       source=scraping_method,
                       bool_batch=True)

    # Output all the Rule #1 results into the excel file
    dataframe_to_excel(excel_output_path,
                       results_df,
                       ticker,
                       source='filter_fs_data',
                       bool_batch=bool_batch)
예제 #10
0
def confirmMirror():
    buttons_mirror_config = ['Ok', 'No-Way']
    mirror_config = pymsgbox.confirm(text=('Run Screen Mirror?'), title='Pokemon H@ck', buttons=buttons_mirror_config)

    if (mirror_config == buttons_mirror_config[0]):
        mirror()
    elif (mirror_config == buttons_mirror_config[1]):
        print("Skipping Default Xcode Config")
예제 #11
0
def ask_dpi():
    choice = pymsgbox.confirm(text="To apply changes, the GWSL XServer needs to be restarted. Be sure to save any work open in GWSL programs. This will force close windows running in GWSL. Restart now?",
                              title=f"Restart XServer to Apply Changes?",
                              buttons=["Yes", "No"])
    if choice == "Yes":
        return True
    else:
        return False
예제 #12
0
def ask_clip(phrase):
    choice = pymsgbox.confirm(text="Toggle the shared clipboard? Be sure to save any work open in GWSL programs. This might force-close some windows.",
                              title=f"{phrase} Clipboard",
                              buttons=["Yes", "No"])
    if choice == "Yes":
        return True
    else:
        return False
예제 #13
0
def ask():
    choice = pymsgbox.confirm(text="Switch XServer profiles? Be sure to save any work open in GWSL programs. This might force-close some windows.",
                              title="Switch Profile",
                              buttons=["Yes", "No"])
    if choice == "Yes":
        return True
    else:
        return False
def show_confirm_box(box_title, box_content, displayed_buttons = ['Yes', 'No']):
    result = confirm(text=box_content, title=box_title, buttons=displayed_buttons)
  
    if result == 'OK':
        return True
    else:
        return False
        
예제 #15
0
class UI:
    returnOpt1 = confirm(
        text='Thank you for using Clash of Clans Auto Player! \n'
        'You are about to ace this game! \n'
        'Click OK to continue \n'
        'Click Cancel to exit',
        title='ClashOfClans',
        buttons=['OK', 'Cancel'])

    #Intentional Failure to break the execution
    if returnOpt1 == 'OK':
        returnOpt2 = confirm(text='Click on one of the Options',
                             title='Action',
                             buttons=[
                                 'Collect Coin', 'Collect Elixir',
                                 'Collect All Resources', 'Upgrade Buildings'
                             ])
예제 #16
0
def messageTest():
    if msg.confirm(text='CONFIRM_TEXT',
                   title='CONFIRM_TITLE',
                   buttons=['OK', 'Cancel']) == 'OK':
        msg.alert(text='u r pressed OK', title='ALERT_TITLE', button='OK')
    else:
        msg.alert(text='u r pressed CANCEL', title='ALERT_TITLE', button='OK')
    msg.password(text='', title='', default='', mask='*')
예제 #17
0
 def show():
     import pymsgbox
     while True:
         chosen = pymsgbox.confirm(text=msg,title='triggers',buttons=texts)
         for i,t in enumerate(texts):
             if t==chosen:
                 print(i,t,'chosen...')
                 callbacks[i]()
예제 #18
0
def makeDecision(text, title):
    mkd = "I'm not sure"
    while (mkd == "I'm not sure"):
        mkd = msg.confirm(text, title, ["Yes", "No", "I'm not sure"])
        if (mkd == "I'm not sure"):
            msg.alert("Please make a decision !",
                      "Tapisserie - Human interface error")
        else:
            return (mkd)
예제 #19
0
def message_box(text, title='', style=1):
    # if is_windows():
    #     import ctypes
    #     return ctypes.windll.user32.MessageBoxW(0, text, title, style)
    # else:
    import pymsgbox
    buttons = {0: ['Ok'], 1: ['Ok', 'Cancel'], 2: ['Abort', 'No', 'Cancel'], 3: ['Yes', 'No', 'Cancel'],
               4: ['Yes', 'No'], 5: ['Retry', 'No'], 6: ['Cancel', 'Try Again', 'Continue']}
    return pymsgbox.confirm(text=text, title=title, buttons=buttons[style])
예제 #20
0
파일: iss.py 프로젝트: DiegoHeer/iss
def remove_non_approved_tickers():
    user_answer = pymsgbox.confirm(
        "Remove also tickers were the MOAT needs to be checked?",
        "Ticker Removal", (pymsgbox.YES_TEXT, pymsgbox.NO_TEXT))
    remover = FSHandler('screener')
    if user_answer == pymsgbox.YES_TEXT:
        remover.dump_non_approved_tickers(True)
    else:
        remover.dump_non_approved_tickers(False)
예제 #21
0
def ask_restart():
    answer = pymsgbox.confirm(
        text="Hmm... The GWSL service just crashed or was closed. Do you want to restart the service?",
        title="XServer Has Stopped",
        buttons=['Yes', 'No'])
    if answer == "Yes":
        return True
    else:
        return False
예제 #22
0
def ask():
    choice = pymsgbox.confirm(
        text="Switch XServer profiles? This might force-close some windows.",
        title="Switch Profile",
        buttons=["Yes", "No"])
    if choice == "Yes":
        return True
    else:
        return False
예제 #23
0
    def gesture_details_data(self):
        """
        Capturing the details of the gesture, gesture ID and Gesture details and inserting it into the database
        :return: None
        """
        # self.gesture_id = input('Gesture Number')
        conn = sqlite3.connect(self.gesture_db)
        query = "SELECT max(gesture_id) FROM isl_gesture "
        cursor = conn.execute(query)
        for row in cursor:
            gesture_id = row[0]
        conn.close()
        try:

            id_value = pymsgbox.prompt('Gesture Number',
                                       default=int(gesture_id) + 1,
                                       title='Gesture Information')
            self.gesture_id = int(-1 if id_value is None else id_value)
        except (ValueError, TypeError) as e:
            pymsgbox.alert('Please enter a valid integer ID', 'Alert!')
            self.gesture_details_data()
            return

        if self.gesture_id is -1:
            exit(0)
        else:
            self.gesture_id = str(self.gesture_id)

        # self.gesture_detail = input('Gesture Details')
        self.gesture_detail = pymsgbox.prompt('Gesture Details',
                                              default='',
                                              title='Gesture Information')
        if self.gesture_detail is None:
            exit(0)

        conn = sqlite3.connect(self.gesture_db)
        query = "INSERT INTO isl_gesture (gesture_id, gesture_detail) VALUES (%s, \'%s\')" % \
                (self.gesture_id, self.gesture_detail)

        try:
            conn.execute(query)
        except sqlite3.IntegrityError:
            # choice = input("Gesture with this ID already exists. Want to change the record? (y/n): ")
            choice = pymsgbox.confirm(
                'Gesture with this ID already exists. Want to change the record?',
                'Confirm', ["Yes", 'No'])
            if choice.lower() == 'yes':
                cmd = "UPDATE isl_gesture SET gesture_detail" \
                      " = \'%s\' WHERE gesture_id = %s" % (self.gesture_detail, self.gesture_id)
                conn.execute(cmd)
            else:
                conn.close()
                self.gesture_details_data()
                return

        conn.commit()
예제 #24
0
def ask_dpi():
    """Prompts user to confirm changing DPI"""
    choice = pymsgbox.confirm(text="To apply changes, the GWSL will close. Be sure to save any work open in GWSL "
                                   "programs. This will force close windows running in GWSL. Restart now?",
                              title=f"Restart XServer to Apply Changes?",
                              buttons=["Yes", "No"])
    if choice == "Yes":
        return True
    else:
        return False
예제 #25
0
def marine():

    yesno = pymsgbox.confirm(
        'Are you interested in both fluid (air and water)?', '', 'YN')
    if yesno == 'Y':
        pymsgbox.alert('You have to use the multyphase simulation')
        pymsgbox.alert('You have to use the interFoam solver')
    else:
        pymsgbox.alert('You have to use the monophase simulation')
        pymsgbox.alert('Choose the automotive button')
예제 #26
0
 def test_timeout(self):
     # Note: If these test's fail, the unit tests will hang.
     self.assertEqual(pymsgbox.alert('timeout test', timeout=1000),
                      pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.confirm('timeout test', timeout=1000),
                      pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.prompt('timeout test', timeout=1000),
                      pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.password('timeout test', timeout=1000),
                      pymsgbox.TIMEOUT_TEXT)
예제 #27
0
파일: reminder.py 프로젝트: PyDL/reminder
def showmsg(text='Reminder',title='Reminder'):
    '''
    Show Message
    '''
    ans = pymsgbox.confirm(text, title, ['Got it', 'Stop Reminder'])
    if ans == 'Stop Reminder':
        ans = 'n'
    else:
        ans = 'y'
    return(ans)
예제 #28
0
def show_msg(message):
    """
    Show dialog, get an answer. Could be tweaked to drop requirement on pymsgbox
    """
    import pymsgbox
    response = pymsgbox.confirm(message)
    if response == 'OK':
        return True
    else:
        return False
예제 #29
0
def ask_restart():
    """Prompts user to confirm restarting the GWSL service"""
    answer = pymsgbox.confirm(
        text="Hmm... The main GWSL service just crashed or was closed. Do you want to restart the service? If any GWSL windows are still open, they will be closed. Please save your work in those windows before clicking yes.",
        title="XServer Has Stopped",
        buttons=['Yes', 'No'])
    if answer == "Yes":
        return True
    else:
        return False
예제 #30
0
def show_msg(message):
    """
    Show dialog, get an answer. Could be tweaked to drop requirement on pymsgbox
    """
    import pymsgbox
    response = pymsgbox.confirm(message)
    if response == 'OK':
        return True
    else:
        return False
예제 #31
0
def ask_reset():
    """Prompts user to confirm clearing logs and resetting config"""
    choice = pymsgbox.confirm(text="Delete GWSL logs and reset configuration? This will not delete shortcuts. "
                                   "The GWSL XServer will need to be restarted. Be sure to save any work open in GWSL "
                                   "programs. This will force close windows running in GWSL.",
                              title=f"Clear GWSL Data?",
                              buttons=["Yes", "No"])
    if choice == "Yes":
        return True
    else:
        return False
def mittagessen_um(message, uhrzeit):
    getUserName = getpass.getuser()
    kommtMit = pymsgbox.confirm(
        'Kommst Du mit zum Mittagessen um %s' %
        uhrzeit, 'Teilnahme Mittagessen', [
            "Ja", "Vielleicht", 'Nein'])
    if kommtMit == "Ja":
        message.send(
            'Ja, %s kommt mit zum Mittagessen' %
            getUserName,
            '7iqsqeqaefdmdcy4nj7ccnwfnw')
    elif kommtMit == "Vielleicht":
        message.send('Vielleicht kommt %s mit zum Mittagessen' %
                     getUserName, '7iqsqeqaefdmdcy4nj7ccnwfnw')
    else:
        message.send(
            '%s Kommt nicht mit zum Mittagessen' %
            getUserName,
            '7iqsqeqaefdmdcy4nj7ccnwfnw')
def mittagessen_aufruf(message):
    os.system('xdg-open "http://www.aserv.kit.edu/downloads/Speiseplan_deutsch.pdf"')
    time.sleep(3)
    getUserName = getpass.getuser()
    kommtMit = pymsgbox.confirm(
        'Kommst Du mit zum Mittagessen', 'Teilnahme Mittagessen', [
            "Ja", "Vielleicht", 'Nein'])
    if kommtMit == "Ja":
        message.send(
            'Ja, %s kommt mit zum Mittagessen' %
            getUserName,
            '7iqsqeqaefdmdcy4nj7ccnwfnw')
    elif kommtMit == "Vielleicht":
        message.send('Vielleicht kommt %s mit zum Mittagessen' %
                     getUserName, '7iqsqeqaefdmdcy4nj7ccnwfnw')
    else:
        message.send(
            '%s Kommt nicht mit zum Mittagessen' %
            getUserName,
            '7iqsqeqaefdmdcy4nj7ccnwfnw')
예제 #34
0
def main():
	pc_screen_windowed = True
	pc_screen_width = 1280
	pc_screen_height = 720

	plus = gs.GetPlus()
	plus.CreateWorkers()
	DemoSimulation.print_ascii_intro(None)

	if getattr(sys, 'frozen', False):
	    # frozen
	    dir_ = dirname(sys.executable)
	else:
	    # unfrozen
	    dir_ = dirname(realpath(__file__))

	window_mode = pymsgbox.confirm(text='Select your screen mode', title='System Zoetrope', buttons=['Windowed', 'Fullscreen'])

	if window_mode == 'Windowed':
		pc_screen_windowed = True
		screen_resolutions = ['640x480', '720x568', '800x600', '1280x800']
	elif window_mode == 'Fullscreen':
		pc_screen_windowed = False
		screen_resolutions = ['640x480', '800x600', '1280x720', '1280x800', '1920x1080']
	else:
		return False

	screen_res = pymsgbox.confirm(text='Select your screen resolution', title='System Zoetrope',
								   buttons=screen_resolutions)

	if screen_res is not None:
		pc_screen_width = int(screen_res.split('x')[0])
		pc_screen_height = int(screen_res.split('x')[1])
	else:
		return False

	demo_screen_width = 720//2
	demo_screen_height = 568//2
	amiga_screen_ratio = demo_screen_height / demo_screen_width
	overscan_factor = gs.Vector4(16 / demo_screen_width, 4 / demo_screen_height,
								 (demo_screen_width - 16) / demo_screen_width, (demo_screen_height - 28) / demo_screen_height) # in pixels


	if pc_screen_windowed:
		pc_screen_width = int(pc_screen_height * (demo_screen_width / demo_screen_height))

	# mount the system file driver
	# gs.GetFilesystem().Mount(gs.StdFileDriver("pkg.core"), "@core")
	gs.MountFileDriver(gs.StdFileDriver())
	gs.LoadPlugins(gs.get_default_plugins_path())

	# create the renderer and render system
	if pc_screen_windowed:
		w_mode = gs.Window.Windowed
	else:
		w_mode = gs.Window.Fullscreen
	plus.RenderInit(pc_screen_width, pc_screen_height, 1, w_mode)

	egl = plus.GetRendererAsync()

	# create the font object
	font = gs.RasterFont("@core/fonts/default.ttf", 48, 512)

	# Init demo simulation
	demo = DemoSimulation(demo_screen_width, demo_screen_height)

	# # load a simple 2d shader outputting a single color
	# shader = egl.LoadShader("res/shader_2d_single_texture.isl")
	#
	# # Create index buffer
	# data = gs.BinaryBlob()
	# data.WriteShorts([0, 1, 2, 0, 2, 3])
	#
	# idx = egl.NewBuffer()
	# egl.CreateBuffer(idx, data, gs.GpuBuffer.Index)
	#
	# # Create vertex buffer
	# # Create vertex buffer
	# vtx_layout = gs.VertexLayout()
	# vtx_layout.AddAttribute(gs.VertexAttribute.Position, 3, gs.VertexFloat)
	# vtx_layout.AddAttribute(gs.VertexAttribute.UV0, 2, gs.VertexUByte, True)  # UVs are sent as normalized 8 bit unsigned integer (range [0;255])
	#
	# def custom_uv(u, v):
	# 	return [int(Clamp(u, 0, 1) * 255), int(Clamp(v, 0, 1) * 255)]
	#
	# data = gs.BinaryBlob()
	# x, y = 1, 1
	# data.WriteFloats([-x, -y, 0.5])
	# data.WriteUnsignedBytes(custom_uv(overscan_factor.x, overscan_factor.w))
	# data.WriteFloats([-x, y, 0.5])
	# data.WriteUnsignedBytes(custom_uv(overscan_factor.x, overscan_factor.y))
	# data.WriteFloats([x, y, 0.5])
	# data.WriteUnsignedBytes(custom_uv(overscan_factor.z, overscan_factor.y))
	# data.WriteFloats([x, -y, 0.5])
	# data.WriteUnsignedBytes(custom_uv(overscan_factor.z, overscan_factor.w))
	#
	# vtx = egl.NewBuffer()
	# egl.CreateBuffer(vtx, data, gs.GpuBuffer.Vertex)

	# demo bitmaps
	demo.load_textures()
	demo_screen_tex = egl.NewTexture("demo_screen_texture")

	res = egl.CreateTexture(demo_screen_tex, demo.screen_pic)
	print("CreateTexture() returned ", res)

	# play music
	al = gs.MixerAsync(gs.ALMixer())
	al.Open()
	channel_state = gs.MixerChannelState(0, 1, gs.MixerRepeat)
	al.Stream("res/music_loop.ogg", channel_state)

	mode_switch = "DMODE_SW_UBOB"

	while not plus.IsAppEnded(plus.EndOnDefaultWindowClosed) and not plus.KeyPress(gs.InputDevice.KeyEscape):
		dt = plus.UpdateClock()
		plus.Clear()

		# Demo simulation (re-creation)
		demo.update_dt(dt.to_sec())
		demo.clear_screen()
		demo.draw_pixel_art_logo()
		demo.draw_checkerboard()

		if mode_switch == "DMODE_SW_UBOB":
			if not demo.draw_unlimited_bobs():
				if demo.figure_mode % 2 == 0:
					mode_switch = "DMODE_SW_CLEAR_FROM_TOP"
				else:
					mode_switch = "DMODE_SW_CLEAR_FROM_BOTTOM"
		elif mode_switch == "DMODE_SW_CLEAR_FROM_TOP":
			if demo.clear_playfield(True):
				mode_switch = "DMODE_SW_NEXT_UBOB"
		elif mode_switch == "DMODE_SW_CLEAR_FROM_BOTTOM":
			if demo.clear_playfield(False):
				mode_switch = "DMODE_SW_NEXT_UBOB"
		elif mode_switch == "DMODE_SW_NEXT_UBOB":
			demo.set_next_unlimited_bobs()
			mode_switch = "DMODE_SW_UBOB"

		demo.render_demo_text()

		egl.BlitTexture(demo_screen_tex, gs.BinaryBlobFromByteArray(demo.screen_pic.GetData()), demo_screen_width, demo_screen_height)

		if pc_screen_windowed:
			# egl.SetShader(shader)
			# egl.SetShaderTexture("u_tex", demo_screen_tex)
			# egl.DrawBuffers(6, idx, vtx, vtx_layout)
			plus.Quad2D(0, 0, 0, pc_screen_height, pc_screen_width, pc_screen_height,
						pc_screen_width, 0, gs.Color.White, gs.Color.White, gs.Color.White, gs.Color.White,
						demo_screen_tex, overscan_factor.x, overscan_factor.y,
						overscan_factor.z, overscan_factor.w)
		else:
			_x_offset = (pc_screen_width - pc_screen_width * amiga_screen_ratio) * 0.5
			plus.Quad2D(_x_offset, 0, _x_offset, pc_screen_height, _x_offset + (pc_screen_width * amiga_screen_ratio),
						pc_screen_height, _x_offset + (pc_screen_width * amiga_screen_ratio), 0,
						gs.Color.White, gs.Color.White, gs.Color.White, gs.Color.White, demo_screen_tex,
						overscan_factor.x, overscan_factor.y,
						overscan_factor.z, overscan_factor.w)

		plus.Flip()
예제 #35
0
 def test_timeout(self):
     # Note: If these test's fail, the unit tests will hang.
     self.assertEqual(pymsgbox.alert('timeout test', timeout=1000), pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.confirm('timeout test', timeout=1000), pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.prompt('timeout test', timeout=1000), pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.password('timeout test', timeout=1000), pymsgbox.TIMEOUT_TEXT)
예제 #36
0
    def test_confirm(self):
        # press enter on OK
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm(), 'OK')

        # press right, enter on Cancel
        t = KeyPresses(['right', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm(), 'Cancel')

        # press right, left, right, enter on Cancel
        t = KeyPresses(['right', 'left', 'right', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm(), 'Cancel')

        # press tab, enter on Cancel
        t = KeyPresses(['tab', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm(), 'Cancel')

        # press tab, tab, enter on OK
        t = KeyPresses(['tab', 'tab', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm(), 'OK')

        # with text
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello'), 'OK')

        # with text, title
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title'), 'OK')

        # with text, title, and one custom button
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A']), 'A')

        # with text, title, and one custom blank button
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['']), '')

        # with text, title, and two custom buttons
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A', 'B']), 'A')

        t = KeyPresses(['right', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A', 'B']), 'B')

        t = KeyPresses(['right', 'left', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A', 'B']), 'A')

        t = KeyPresses(['tab', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A', 'B']), 'B')

        t = KeyPresses(['tab', 'tab', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A', 'B']), 'A')

        # with text, title, and three custom buttons
        t = KeyPresses(['tab', 'tab', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A', 'B', 'C']), 'C')

        # with text, title, and four custom buttons
        t = KeyPresses(['tab', 'tab', 'tab', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A', 'B', 'C', 'D']), 'D')

        # with text, title, and five custom buttons
        t = KeyPresses(['tab', 'tab', 'tab', 'tab', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm('Hello', 'Title', ['A', 'B', 'C', 'D', 'E']), 'E')

        # with text, title, and three custom buttons specified with keyword arguments
        t = KeyPresses(['tab', 'tab', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm(text='Hello', title='Title', buttons=['A', 'B', 'C']), 'C')

        # test that pressing Esc is the same as clicking Cancel (but only when there is a cancel button)
        t = KeyPresses(['escape'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm(text='Escape button press test'), 'Cancel')

        # Make sure that Esc keypress does nothing if there is no Cancel button.
        t = KeyPresses(['escape', 'enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.confirm(text='Escape button press test', buttons=['OK', 'Not OK']), 'OK')