Beispiel #1
0
    def test_returns_right_values(self):
        """Checking that going to different options returns the right values"""
        # Checking first option - Yes
        db = DialogBox("ync", get_mock_input(), get_mock_output(), name=db_name)
        def scenario():
            db.accept_value()  # KEY_ENTER
            assert not db.in_foreground  # Should exit

        with patch.object(db, 'idle_loop', side_effect=scenario) as p:
            return_value = db.activate()
        assert return_value is True #First element - Yes, means True

        # Checking second option - No
        db = DialogBox("ync", get_mock_input(), get_mock_output(), name=db_name)
        def scenario():
            db.move_right()
            db.accept_value()  # KEY_ENTER
            assert not db.in_foreground  # Should exit

        with patch.object(db, 'idle_loop', side_effect=scenario) as p:
            return_value = db.activate()
        assert return_value is False #Second element - No, means False

        # Checking second option - Cancel
        db = DialogBox("ync", get_mock_input(), get_mock_output(), name=db_name)
        def scenario():
            db.move_right()
            db.move_right()
            db.accept_value()  # KEY_ENTER
            assert not db.in_foreground  # Should exit

        with patch.object(db, 'idle_loop', side_effect=scenario) as p:
            return_value = db.activate()
        assert return_value is None #Last element - Cancel, means None
Beispiel #2
0
def callback():
    print(DialogBox('ync', i, o, message="It's working?").activate())
    print(DialogBox('yyy', i, o, message="Isn't it beautiful?").activate())
    print(
        DialogBox([["Yes", True], ["Absolutely", True]],
                  i,
                  o,
                  message="Do you like it").activate())
Beispiel #3
0
 def test_values_leakage(self):
     """tests whether the exit label of one DialogBox leaks into another"""
     i = get_mock_input()
     o = get_mock_output()
     d1 = DialogBox("ync", i, o, name=db_name + "1")
     d2 = DialogBox(["y", ["Hell no", False]], i, o, name=db_name + "2")
     d3 = DialogBox([["Hell yeah", True], ["Sod off", None]], i, o, name=db_name + "3")
     assert (d1.values != d2.values)
     assert (d2.values != d3.values)
     assert (d1.values != d3.values)
Beispiel #4
0
 def test_init_options(self):
     """tests different ways of passing "values" - as string, as list of lists and as a list of both characters and lists."""
     i = get_mock_input()
     o = get_mock_output()
     d1 = DialogBox("ync", i, o, name=db_name + "1")
     assert (d1.values == [["Yes", True], ["No", False], ["Cancel", None]])
     d2 = DialogBox(["y", ["Hell no", False]], i, o, name=db_name + "2")
     assert (d2.values == [["Yes", True], ["Hell no", False]])
     d3 = DialogBox([["Hell yeah", True], ["Sod off", None]], i, o, name=db_name + "3")
     assert (d3.values == [["Hell yeah", True], ["Sod off", None]])
Beispiel #5
0
def flash_image_ui():
    if not MTKDownloadProcess(None, None, path=config["mtkdownload_path"]).mtkdownload_is_available():
        Printer("mtkdownload not found!", i, o, 5)
        choice = DialogBox("yn", i, o, name="Hardware setup app mtkdownload path confirmation", message="Set mtkdownload path?").activate()
        if choice:
            if set_mtkdownload_path():
                # Running again, now the path should be valid
                flash_image_ui()
            return # No need to continue whether we've recursed or not, exiting
    files = collect_fw_folders(config["gsm_fw_path"])
    lbc = [[os.path.basename(file), file] for file in files]
    if not lbc:
        Printer("No firmware images found!", i, o, 5)
        choice = DialogBox("yn", i, o, name="Hardware setup app mtkdownload path confirmation", message="Alternative FW path?").activate()
        if choice:
            if set_sim_firmware_path():
                # Running again, now there should be some firmware
                flash_image_ui()
            return
    choice = Listbox(lbc, i, o, name="Hardware setup app GSM FW picker").activate()
    # A ProgressBar for the flashing specifically
    pb = ProgressBar(i, o, message="Flashing the modem")
    # A LoadingIndicator for everything else
    li = LoadingIndicator(i, o, message="Waiting for modem")
    if choice:
        cb = lambda state: process_state(pb, li, state)
        p = MTKDownloadProcess("/dev/ttyAMA0", choice, callback=cb, path=config["mtkdownload_path"])
        gp = get_gsm_reset_gpio()
        if not gp:
            return
        def reset():
            gpio.setup(gp, gpio.OUT)
            gpio.set(gp, False)
            sleep(0.1)
            gpio.set(gp, True)
        e = None
        try:
            p.write_image(reset_cb=reset)
        except Exception as e:
            e = traceback.format_exc()
        state = p.get_state()
        if state["state"] == "failed" or e:
            choice = DialogBox("yn", i, o, message="Send bugreport?").activate()
            if choice:
                br = BugReport("mtkdownload_flash_fail.zip")
                if e:
                    br.add_text(json.dumps(e), "mtkdownload_exception.json")
                br.add_text(json.dumps(p.dump_info()), "mtkdownload_psinfo.json")
                result = br.send_or_store("/boot/", logger=logger)
                if result[0]:
                    logger.info("Report sent to {}".format(result[1]))
                else:
                    logger.info("Report stored in {}".format(result[1]))
Beispiel #6
0
 def verify_and_run():
     """
     If either directory that we need to read into does not exist,
     the filename is invalid or there is already an invalid file in that
     location (character device or something like that), we should warn
     the user and abort.
     If there's already a file in that location, we should make the
     user confirm the overwrite.
     """
     full_path = os.path.join(self.read_dir,
                              self.read_filename) + ".hex"
     if not os.path.isdir(self.read_dir):
         PrettyPrinter("Wrong directory!", self.i, self.o, 3)
         return
     if '/' in self.read_filename:
         PrettyPrinter("Filename can't contain a slash!", self.i,
                       self.o, 3)
         return
     if os.path.exists(full_path):
         if os.path.isdir(full_path) or not os.path.isfile(full_path):
             PrettyPrinter(
                 "Trying to overwrite something that is not a file!",
                 self.i, self.o, 5)
             return
         choice = DialogBox(
             'ync',
             self.i,
             self.o,
             message="Overwrite?",
             name="Avrdude write overwrite confirmation").activate()
         if not choice:
             return
     self.create_process()
     if self.read_checklist():
         self.detect_and_run()
Beispiel #7
0
def set_default_sim_firmware_path():
    choice = DialogBox("yn", i, o, name="Hardware setup app default SIM firmware path confirmation", message="Set default FW path?").activate()
    if choice:
        config["gsm_fw_path"] = default_gsm_fw_path
        save_config(config)
        return True
    return False
Beispiel #8
0
def call_external(script_list, shell=False):
    if shell == True:
        script_path = script_list.split(' ')[0]
    else:
        script_path = os.path.split(script_list[0])[1]
    Printer("Calling {}".format(script_path), i, o, 1)
    try:
        output = check_output(script_list, stderr=STDOUT, shell=shell)
    except OSError as e:
        if e.errno == 2:
            Printer("File not found!", i, o, 1)
        elif e.errno == 13:
            Printer(["Permission", "denied!"], i, o, 1)
        elif e.errno == 8:
            Printer(["Unknown format,", "forgot header?"], i, o, 1)
        else:
            error_data = ["Unknown error", ""]
            error_data += ffs(repr(e), o.cols)
            Printer(error_data, i, o, 1)
        output = ""
    except CalledProcessError as e:
        Printer(["Failed with", "code {}".format(e.returncode)], i, o, 1)
        output = e.output
    else:
        Printer("Success!", i, o, 1)
    finally:
        if not output:
            return
        answer = DialogBox("yn", i, o, message="Show output?").activate()
        if answer == True:
            Printer(ffs(output, o.cols, False), i, o, 5, True)
Beispiel #9
0
def call_external(script_list, shell=False):
    if shell:
        script_path = script_list.split(' ')[0]
    else:
        script_path = os.path.split(script_list[0])[1]
    Printer("Calling {}".format(script_path), i, o, 1)

    output = None
    try:
        output = check_output(script_list, stderr=STDOUT, shell=shell)
    except OSError as e:
        if e.errno == 2:
            Printer("File not found!", i, o, 1)
        elif e.errno == 13:
            Printer(["Permission", "denied!"], i, o, 1)
        elif e.errno == 8:
            Printer(["Unknown format,", "forgot header?"], i, o, 1)
        else:
            error_message = "Unknown error! \n \n {}".format(e)
            PrettyPrinter(error_message, i, o, 3)
        output = ""
    except CalledProcessError as e:
        Printer(["Failed with", "code {}".format(e.returncode)], i, o, 1)
        output = e.output
    else:
        Printer("Success!", i, o, 1)
    finally:
        if not output:
            return
        answer = DialogBox("yn", i, o, message="Show output?").activate()
        if answer:
            TextReader(output, i, o, autohide_scrollbars=True,
                       h_scroll=True).activate()
Beispiel #10
0
    def create_dialog(self):

        self.text = dice(len(self.dialogs) - 1)

        name = self.dialogs[self.text[0]]['npc']
        text = self.dialogs[self.text[0]]['text']
        message = {0: "{0}:".format(name)}

        max_chars = 24
        i = 1
        for j in range(0, len(text), max_chars):
            message[i] = text[j:j + max_chars]
            i += 1

        self.dialog_box = DialogBox(self.factory,
                                    font_size=32,
                                    fg_color=Colors.WHITE,
                                    bg_color=Colors.BLACK,
                                    font_name="04B_20__.TTF",
                                    text=message,
                                    position=self.position,
                                    renderer=self.renderer)

        sprites = self.dialog_box.get_sprites()
        for sprite in sprites:
            self.dialog_sprites.append(sprite)
Beispiel #11
0
    def test_left_key_returns_none(self):
        db = DialogBox("ync",
                       get_mock_input(),
                       get_mock_output(),
                       name=db_name)
        db.refresh = lambda *args, **kwargs: None

        # Checking at the start of the options
        def scenario():
            db.move_left()
            assert not db.in_foreground

        with patch.object(db, 'idle_loop', side_effect=scenario) as p:
            return_value = db.activate()
        assert return_value is None

        # Going to the right and then going to the left again
        def scenario():
            db.move_right()
            db.move_left()  #At this point, shouldn't exit
            assert db.in_foreground
            db.move_left()
            assert not db.in_foreground

        with patch.object(db, 'idle_loop', side_effect=scenario) as p:
            return_value = db.activate()
        assert return_value is None
Beispiel #12
0
 def test_constructor(self):
     """tests constructor"""
     db = DialogBox([["Option", "option"]],
                    get_mock_input(),
                    get_mock_output(),
                    name=db_name)
     self.assertIsNotNone(db)
Beispiel #13
0
def option_switch_dialog(option):
    answer = DialogBox(
        [["On", 'o'], ["Off", 'u'], ["Toggle", "t"]],
        i,
        o,
        message=option.capitalize() + ":",
        name="MOCP {} option control dialog".format(option)).activate()
    if answer: mocp_switch_option(answer, option)
Beispiel #14
0
def setup_ssh():
    regenerate_ssh_keys()
    choice = DialogBox("ync", i, o, message="Enable SSH server?").activate()
    if choice is not None:
        if choice:
            enable_ssh()
        else:
            disable_ssh()
Beispiel #15
0
def reboot_after_firstboot():
    choice = DialogBox("ync", i, o, message="Reboot to apply changes?", name="Reboot app firstboot reboot dialog").activate()
    if not choice:
        return True
    o.clear()
    o.display_data("Rebooting")
    call(['reboot'])
    return True
Beispiel #16
0
def offer_retry(counter):
    do_reactivate = DialogBox("ync", i, o, message="Retry?").activate()
    if do_reactivate:
        PrettyPrinter("Connecting, try {}...".format(counter), i, o, 0)
        init.reset()
        init.run()
        wait_for_connection()
        callback(counter)
Beispiel #17
0
def control_autosend():
    is_autosent = config.get("autosend", False)
    d = DialogBox("yn", i, o, message="Automatically send bugreports?", name="Autosend control dialog box")
    d.set_start_option(0 if is_autosent else 1)
    choice = d.activate()
    if choice is not None:
        config["autosend"] = True if choice else False
        save_config(config)
Beispiel #18
0
 def update_on_firstboot(self):
     choice = DialogBox("yn",
                        i,
                        o,
                        message="Update ZPUI?",
                        name="ZPUI update app firstboot dialog").activate()
     if not choice:
         return None
     return self.update(suggest_restart=False)
Beispiel #19
0
def confirm_exit():
	global choice_ongoing, lose
	choice_ongoing = True
	#TODO : Maybe a clearer message ?
	choice = DialogBox(["n", ["Restart", None], "y"], i, o, message="Exit the game?").activate()
	if choice is True:	#Exit
		lose = True
	elif choice is None:	#Restart
		restart_game()
	choice_ongoing = False
	set_keymap()
Beispiel #20
0
    def test_start_option(self):
        db = DialogBox("ync", get_mock_input(), get_mock_output(), name=db_name)
        db.refresh = lambda *args, **kwargs: None
        db.set_start_option(1) #So, "No" option would be selected

        def scenario():
            db.accept_value()  # KEY_ENTER
            assert not db.in_foreground  # Should exit

        with patch.object(db, 'idle_loop', side_effect=scenario) as p:
            return_value = db.activate()
        assert return_value is False #Second element - No, means False
Beispiel #21
0
def remove_network(id):
    want_to_remove = DialogBox("yn", i, o, message="Remove network?").activate()
    if not want_to_remove:
        return 
    try:
        wpa_cli.remove_network(id)
    except wpa_cli.WPAException:
        Printer(['Failed to', 'remove network'], i, o, skippable=True)
    else:
        wpa_cli.save_config()
        Printer(['Removed network', str(id)], i, o, skippable=True)
        raise MenuExitException
Beispiel #22
0
    def test_graphical_display_redraw(self):
        o = get_mock_graphical_output()
        db = DialogBox("ync", get_mock_input(), o, name=db_name)
        Canvas.fonts_dir = fonts_dir
        # Exiting immediately, but we should get at least one redraw
        def scenario():
            db.deactivate()  # KEY_LEFT
            assert not db.in_foreground

        with patch.object(db, 'idle_loop', side_effect=scenario) as p:
            return_value = db.activate()
        assert o.display_image.called
        assert o.display_image.call_count == 1 #One in to_foreground
Beispiel #23
0
 def erase_checklist(self):
     """
     Asks user if they really want to erase the chip.
     """
     answer = DialogBox(
         'yn',
         self.i,
         self.o,
         message="Are you sure?",
         name="Avrdude app erase verify dialogbox").activate()
     if answer:
         self.p.setup_erase()
     return answer
Beispiel #24
0
def delete_config_entry(name, secret, r):
    global config
    # Need to match both name and secret to find the right entry that needs to be deleted
    do_delete = DialogBox("yn", i, o,
                          message="Delete \"{}\"?".format(name)).activate()
    if not do_delete:
        return
    try:
        config["secrets"].remove([name, secret])
    except:
        Printer("Could not delete!", i, o)
        raise
    else:
        save_config(config)
        r.deactivate()
Beispiel #25
0
def change_range():
    global config
    dialogbox_options = [["Safe", "conservative"], ["Full", "full"], "c"]
    dialogbox = DialogBox(dialogbox_options,
                          i,
                          o,
                          message="Scan range",
                          name="I2C tools app range setting dialogbox")
    if config.get("scan_range", "conservative") == "full":
        # setting dialogbox position to the "full" option as it's currently selected
        dialogbox.set_start_option(1)
    new_range = dialogbox.activate()
    if new_range is not None:
        config["scan_range"] = new_range
        save_config(config)
Beispiel #26
0
def exit():
    index = values.get_index()
    if index < 0:  # operation
        values.page = oper1
        do_update.set()
        return
    waiting.set()
    blink.clear()
    choice = DialogBox("yn", i, o, message="Exit?").activate()
    waiting.clear()
    if choice:
        exit_app.set()
    else:
        do_update.set()
        set_keymap()
Beispiel #27
0
def callback():
    problem_found = False
    problem_fixed = False
    logger.debug("App launched")
    li = LoadingBar(i, o, message="Detecting hardware")
    li.run_in_background()
    sleep(1)  # Showing the message a little bit
    hw_version = get_hw_version(li)
    if not hw_version:
        return False  # User pressed LEFT in Listbox
    # DKMS check
    # if hardware is undetected, do we need to check it?
    # ask the user.
    hw_wrong_but_check_esp = False
    if hw_version == "other":
        hw_wrong_but_check_esp = DialogBox(
            "yn", i, o, message="Using ESP8266?").activate()
    # This deals with ESP8266 problems
    if hw_version == "zero" or hw_wrong_but_check_esp:
        #check dkms module
        problem_found = check_esp8089_dkms(li)
        #check esp8089 module
        if not problem_found:
            if kmodpy:
                problem_found, problem_fixed = check_esp8089_module(li)
            else:
                logger.debug(
                    "kmodpy not available, not checking the esp8089 module")
        # Check dmesg
        if not problem_found:
            problem_found = check_dmesg(li)
        # Check config.txt
        if not problem_found:
            problem_found = problem_fixed = check_zero_config_txt(li)
    elif hw_version == "zerow":
        # Check brcmfmac module
        problem_found, problem_fixed = check_brcmfmac_module(li)
        # Check config.txt
        if not problem_found:
            problem_found = problem_fixed = check_zerow_config_txt(li)
    li.stop()
    if problem_found:
        if problem_fixed:
            Printer("Fixed some problems!", i, o)
        else:
            Printer("Couldn't fix problems!", i, o)
    else:
        Printer("No problems found!", i, o)
Beispiel #28
0
def firstboot_log_autosend_opt_in():
    more = True
    while more: # Need to restart the DialogBox every time "learn more" option is picked
        choice = DialogBox(["y", "n", ["Learn more", "more"]], i, o, message="Automatically send ZPUI error logs for analysis & fixing?").activate()
        if choice is None:
            return False
        elif choice != "more":
            more = False
            if choice:
                logger.info("Automatic sending of bugreports enabled")
                config["autosend"] = True
                save_config(config)
            return True
        else:
            TextReader(bugreport_optin_text, i, o, "Bugreport app UUID reader", h_scroll=False).activate()
    return False
Beispiel #29
0
def set_hw_version(offer_zpui_restart=True):
    lbc = sorted([list(reversed(x)) for x in versions.items()])
    choice = Listbox(lbc, i, o, name="ZP hardware version choose listbox").activate()
    if choice:
        try:
            result = hw_version.set_version(choice)
        except:
            logger.exception("Exception while setting hardware version")
            result = False
        if result:
            Printer("Success!", i, o)
            if offer_zpui_restart:
                needs_restart = DialogBox('yn', i, o, message="Restart ZPUI?").activate()
                if needs_restart:
                    os.kill(os.getpid(), signal.SIGTERM)
        else:
            Printer("Failed to set the version =( Please send a bugreport", i, o, 7)
        return result
Beispiel #30
0
    def __init__(self, renderer):

        self.db = DataBase()

        self.renderer = renderer

        self.inventory = self.db.get_player_inventory()
        self.equipped = json.loads(self.inventory["equipped"])
        self.left_hand_id = self.equipped["left_hand"]
        self.left_hand = self.db.get_item_by_id(self.left_hand_id)

        self.inv_text = {
            0: self.left_hand["name"],
            1: self.left_hand["description"]
        }
        self.inv_dialog = DialogBox(self.renderer, Colors.WHITE, 16,
                                    (300, 200), Colors.BLACK,
                                    "GlametrixBold.otf")