コード例 #1
0
    def returns_on_enter_runner(self, contents, num_elements, exp_return1,
                                exp_return2):
        lb = Listbox(contents,
                     get_mock_input(),
                     get_mock_output(),
                     name=lb_name,
                     config={})
        lb.refresh = lambda *args, **kwargs: None

        # Checking at the start of the list
        def scenario():
            lb.select_entry()  # KEY_ENTER
            assert not lb.in_foreground

        with patch.object(lb, 'idle_loop', side_effect=scenario) as p:
            return_value = lb.activate()
        assert return_value == exp_return1

        # Checking at the end of the list
        def scenario():
            for i in range(num_elements - 1):
                lb.move_down()  # KEY_DOWN x2
            lb.select_entry()  # KEY_ENTER
            assert not lb.in_foreground

        with patch.object(lb, 'idle_loop', side_effect=scenario) as p:
            return_value = lb.activate()
        assert return_value == exp_return2
コード例 #2
0
    def __init__(self, i, o):
        super(LoadingBarExampleApp, self).__init__(i, o)
        self.menu_name = "Loading bar test app"

        self.default_progress_bar = ProgressBar(self.i, self.o)
        self.text_progress_bar = TextProgressBar(self.i,
                                                 self.o,
                                                 refresh_interval=.1,
                                                 show_percentage=True,
                                                 percentage_offset=0)
        self.circular_progress = CircularProgressBar(self.i,
                                                     self.o,
                                                     show_percentage=True)
        self.dotted_progress_bar = IdleDottedMessage(self.i, self.o)
        self.throbber = Throbber(self.i, self.o, message="Test message")
        self.graphical_progress_bar = GraphicalProgressBar(self.i, self.o)
        self.default_progress_bar = ProgressBar(self.i, self.o)
        lb_contents = [
            ["Default progress bar", self.default_progress_bar],
            ["Text progress bar", self.text_progress_bar],
            ["Dotted idle ", self.dotted_progress_bar],
            ["Circular progress ", self.circular_progress],
            ["Idle Throbber", self.throbber],
            ["Graphical Loading bar", self.graphical_progress_bar],
        ]
        self.bar_choice_listbox = Listbox(lb_contents, self.i, self.o)
コード例 #3
0
    def test_left_key_returns_none(self):
        """ A Listbox shouldn't return anything when LEFT is pressed"""
        num_elements = 3
        contents = [["A" + str(i), "a" + str(i)] for i in range(num_elements)]
        lb = Listbox(contents,
                     get_mock_input(),
                     get_mock_output(),
                     name=lb_name,
                     config={})
        lb.refresh = lambda *args, **kwargs: None

        # Checking at the start of the list
        def scenario():
            lb.deactivate()  # KEY_LEFT
            assert not lb.in_foreground

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

        # Checking at the end of the list
        def scenario():
            for i in range(num_elements):
                lb.move_down()  # KEY_DOWN x3
            lb.deactivate()  # KEY_LEFT
            assert not lb.in_foreground

        with patch.object(lb, 'idle_loop', side_effect=scenario) as p:
            return_value = lb.activate()
        assert return_value is None
コード例 #4
0
ファイル: main.py プロジェクト: hpagseddy/ZPUI
def callback():
    listbox_contents = [
    ["NumberAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 101],
    ["String", "stringstring"],
    ["Tuple", (1, 2, 3)]]
    lb = Listbox(listbox_contents, i, o)
    HelpOverlay(lambda: print("Halp plz")).apply_to(lb)
    lb.activate()
コード例 #5
0
    def graphical_display_redraw_runner(self, contents):
        o = get_mock_graphical_output()
        lb = Listbox(contents, get_mock_input(), o, name=lb_name, config={})
        Canvas.fonts_dir = fonts_dir

        # Exiting immediately, but we should get at least one redraw
        def scenario():
            lb.deactivate()  # KEY_LEFT
            assert not lb.in_foreground

        with patch.object(lb, 'idle_loop', side_effect=scenario) as p:
            return_value = lb.activate()
        assert o.display_image.called
        assert o.display_image.call_count == 1  #One in to_foreground
コード例 #6
0
ファイル: main.py プロジェクト: hpagseddy/ZPUI
    def set_timezone(self):

        try:
            with open('/etc/timezone', "r") as f:
                current_timezone = f.readline().strip()
        except:
            logger.exception("Can't get current timezone!")
            current_timezone = None
        else:
            logger.info("Current timezone: {}".format(repr(current_timezone)))

        lc = []
        with LoadingBar(self.i, self.o, message="Getting timezones"):
            for k in ZoneInfoFile(getzoneinfofile_stream()).zones.keys():
                lc.append([k])
        lc = sorted(lc)
        choice = Listbox(lc,
                         self.i,
                         self.o,
                         "Timezone selection listbox",
                         selected=current_timezone).activate()
        if choice:
            # Setting timezone using timedatectl
            try:
                check_output(["timedatectl", "set-timezone", choice])
            except CalledProcessError as e:
                logger.exception(
                    "Can't set timezone using timedatectl! Return code: {}, output: {}"
                    .format(e.returncode, repr(e.output)))
                return False
            else:
                logger.info("Set timezone successfully")
                return True
        else:
            return None
コード例 #7
0
    def change_wifi_country(self):
        with open('/usr/share/zoneinfo/iso3166.tab') as f:
            content = f.readlines()

        lc = []
        current_country = self.get_current_wifi_country()

        for l in content:
            # Replace tabs with spaces and strip newlines
            l = l.replace('\t', ' ').strip()
            # Filter commented-out lines
            if l.startswith("#"):
                continue
            country_code, description = l.split(' ', 1)
            lc.append([rfa(l), country_code])

        choice = Listbox(lc,
                         self.i,
                         self.o,
                         name="WiFi country selection listbox",
                         selected=current_country).activate()
        if choice:
            with LoadingBar(self.i,
                            self.o,
                            message="Changing WiFi country",
                            name="WiFi country change LoadingBar"):
                result = self.set_wifi_country(choice)
            if result:
                Printer("Changed the country successfully!", self.i, self.o)
                return True
            else:
                Printer("Failed to change the country!", self.i, self.o)
                return False
        return None
コード例 #8
0
 def pick_bootloader(self):
     """
     A menu to pick the bootloader from bootloaders.json.
     Also records fuse information in self.write_fuse_params,
     where it stays until user selects another bootloader
     or manually selects a file by path.
     """
     bootloader_dir = local_path("bootloaders/")
     config = read_config(
         os.path.join(bootloader_dir, self.bootloader_config_filename))
     bootloader_choices = [[bootloader["name"], bootloader]
                           for bootloader in config["bootloaders"]]
     if not bootloader_choices:
         PrettyPrinter("No bootloaders found!", self.i, self.o, 3)
         return
     choice = Listbox(bootloader_choices,
                      self.i,
                      self.o,
                      name="Avrdude bootloader picker").activate()
     if choice:
         self.write_file = os.path.join(bootloader_dir, choice["file"])
         self.write_fuse_params = []
         for type in self.fuse_types:
             if type in choice:
                 self.write_fuse_params.append(
                     [type, choice[type], config["fuse_format"]])
         self.config["last_write_file"] = self.write_file
         self.config["last_write_fuse_params"] = self.write_fuse_params
         self.save_config()
コード例 #9
0
    def selected_single_el_entry_runner(self, contents, selected):
        lb = Listbox(contents,
                     get_mock_input(),
                     get_mock_output(),
                     selected=selected,
                     name=lb_name,
                     config={})
        lb.refresh = lambda *args, **kwargs: None

        # Checking at the start of the list
        def scenario():
            lb.select_entry()  # KEY_ENTER
            assert not lb.in_foreground

        with patch.object(lb, 'idle_loop', side_effect=scenario) as p:
            return_value = lb.activate()
        assert return_value == selected
コード例 #10
0
 def test_constructor(self):
     """tests constructor"""
     lb = Listbox([["Option", "option"]],
                  get_mock_input(),
                  get_mock_output(),
                  name=lb_name,
                  config={})
     self.assertIsNotNone(lb)
コード例 #11
0
ファイル: main.py プロジェクト: hpagseddy/ZPUI
def change_difficulty():
	global speed, level
	lc = [["Too young to die", 1], ["Hurt me plenty", 2], ["Nightmare !", 3]]
	selected_level = Listbox(lc, i, o, name="Level").activate()
	# If user presses Left, Listbox returns None
	if selected_level:
		level = selected_level
		if level == 3:
			speed = 0.05
コード例 #12
0
def select_adjust_type():
    global config
    contents = [["Percent", '%'], ["Decibels", 'dB'], ["HW value", '']]
    adjust_type = Listbox(contents, i, o,
                          "Adjust selection listbox").activate()
    if adjust_type is None:
        return False
    config["adjust_type"] = adjust_type
    write_config(config, config_path)
コード例 #13
0
    def test_left_key_works_when_not_exitable(self):
        """Listbox should still exit on KEY_LEFT when exitable is set to False"""
        num_elements = 3
        contents = [["A" + str(i), "a" + str(i)] for i in range(num_elements)]
        lb = Listbox(contents,
                     get_mock_input(),
                     get_mock_output(),
                     name=lb_name,
                     config={})
        lb.refresh = lambda *args, **kwargs: None

        def scenario():
            assert "KEY_LEFT" in lb.keymap
            lb.deactivate()
            assert not lb.in_foreground

        with patch.object(lb, 'idle_loop', side_effect=scenario) as p:
            lb.activate()
コード例 #14
0
    def shows_data_on_screen_runner(self, contents):
        i = get_mock_input()
        o = get_mock_output()
        lb = Listbox(contents, i, o, name=lb_name, config={})

        def scenario():
            lb.deactivate()

        with patch.object(lb, 'idle_loop', side_effect=scenario) as p:
            lb.activate()
            #The scenario should only be called once
            assert lb.idle_loop.called
            assert lb.idle_loop.call_count == 1

        assert o.display_data.called
        assert o.display_data.call_count == 1  #One in to_foreground
        assert o.display_data.call_args[0] == ('A0', 'A1', 'A2',
                                               lb.exit_entry[0])
コード例 #15
0
 def test_contents(self):
     """tests contents str-to-list replacement"""
     lb = Listbox([["Option", "option1"], "option2"],
                  get_mock_input(),
                  get_mock_output(),
                  name=lb_name,
                  config={})
     self.assertIsNotNone(lb.contents)
     for entry in lb.contents:
         assert (isinstance(entry, list))
コード例 #16
0
 def test_keymap(self):
     """tests keymap"""
     lb = Listbox([["Option", "option"]],
                  get_mock_input(),
                  get_mock_output(),
                  name=lb_name,
                  config={})
     self.assertIsNotNone(lb.keymap)
     for key_name, callback in lb.keymap.iteritems():
         self.assertIsNotNone(callback)
コード例 #17
0
    def __init__(self, i, o):
        super(LoadingBarExampleApp, self).__init__(i, o)
        self.menu_name = "Loading bar test app"

        self.progress_bar = ProgressBar(
            self.i,
            self.o,
            refresh_interval=.1,
            show_percentage=True,
            percentage_offset=0,
            keymap={"KEY_RIGHT": self.increase_progress})

        self.dotted_progress_bar = DottedProgressIndicator(self.i,
                                                           self.o,
                                                           refresh_interval=.1)

        lb_contents = [["Progress bar", self.progress_bar],
                       ["Dotted bar", self.dotted_progress_bar]]
        self.bar_choice_listbox = Listbox(lb_contents, self.i, self.o)
コード例 #18
0
 def test_exit_label_leakage(self):
     """tests whether the exit label of one Listbox leaks into another"""
     i = get_mock_input()
     o = get_mock_output()
     c1 = Listbox([["a", "1"]],
                  i,
                  o,
                  name=lb_name + "1",
                  final_button_name="Name1",
                  config={})
     c2 = Listbox([["b", "2"]],
                  i,
                  o,
                  name=lb_name + "2",
                  final_button_name="Name2",
                  config={})
     c3 = Listbox([["c", "3"]], i, o, name=lb_name + "3", config={})
     assert (c1.exit_entry != c2.exit_entry)
     assert (c2.exit_entry != c3.exit_entry)
     assert (c1.exit_entry != c3.exit_entry)
コード例 #19
0
def select_channel():
    global config
    contents = []
    channels = amixer_get_channels()
    for channel in channels:
        contents.append([ellipsize(channel, o.cols), channel])
    channel = Listbox(contents, i, o, "Channel selection listbox").activate()
    if channel is None:
        return False
    config["channel"] = channel
    write_config(config, config_path)
コード例 #20
0
def select_card():
    #TODO get a list of all cards
    global config
    contents = []
    cards = []
    for card in cards:
        contents.append([ellipsize(card["name"], o.cols), card["id"]])
    card_id = Listbox(contents, i, o, "Card selection listbox").activate()
    if card_id is None:
        return False
    config["card"] = card_id
    write_config(config, config_path)
コード例 #21
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]))
コード例 #22
0
def get_gsm_reset_gpio():
    hw_revs = [["Gamma", "gamma"], ["Delta/Delta-B", "delta"]]
    gpios = {"gamma":502, "delta":496}
    assert(all([hwr[1] in gpios.keys() for hwr in hw_revs])) # check after editing
    hwr = Listbox(hw_revs, i, o, name="Hardware setup app GSM FW picker").activate()
    if not hwr:
        return None
    if hwr == "delta":
        # Enable UARTs
        gpio.setup(500, gpio.OUT)
        gpio.set(500, False)
    gp = gpios[hwr]
    return gp
コード例 #23
0
def init_app(input, output):
    global callback, i, o
    i = input
    o = output
    lb_contents = [["Very long listbox option name", 1],
                   ["Even longer option name", 2]]
    lb = Listbox(lb_contents, i, o, "Scrolling test listbox")
    pp = PathPicker('/', i, o)
    main_menu_contents = [["Command with very long name", lb.activate],
                          ["Command with an even longer name", pp.activate],
                          ["Exit", 'exit']]
    main_menu = Menu(main_menu_contents, i, o, "Scrolling test menu")
    callback = main_menu.activate
コード例 #24
0
 def remove_entry_menu():  # Kinda misleading, since it's a Listbox
     cl = context.list_contexts()
     gmnfa = get_menu_name_for_alias
     lc = [[gmnfa(cl, entry), entry] for entry in config["app_open_entries"]
           if gmnfa(cl, entry)]
     if not lc:
         PrettyPrinter("No app open entries found!", i, o, 3)
         return
     choice = Listbox(
         lc, i, o, name="Zeromenu app open entry removal menu").activate()
     if choice:
         config["app_open_entries"].remove(choice)
         save_config(config)
コード例 #25
0
 def add_entry_menu():
     cl = context.list_contexts()
     app_context_list = [entry for entry in cl if entry["menu_name"]]
     lc = [[e["menu_name"], e["name"]] for e in app_context_list]
     lc = list(sorted(lc))
     if not lc:
         PrettyPrinter("No suitable app contexts found!", i, o, 3)
         return
     choice = Listbox(
         lc, i, o, name="Zeromenu app open entry addition menu").activate()
     if choice:
         config["app_open_entries"].append(choice)
         save_config(config)
コード例 #26
0
 def pick_chip(self):
     """ A menu to pick the chip from a list of available chips provided by
     avrdude. """
     chips = pyavrdude.get_parts()
     lc = [[name, alias] for alias, name in chips.items()]
     choice = Listbox(lc,
                      self.i,
                      self.o,
                      "Avrdude part picker listbox",
                      selected=self.current_chip).activate()
     if choice:
         self.current_chip = choice
         self.config["default_part"] = self.current_chip
         self.save_config()
コード例 #27
0
 def pick_programmer(self):
     """ A menu to pick the programmer from a list of available programmers
     provided by avrdude. """
     programmers = pyavrdude.get_programmers()
     if self.filter_programmers:
         programmers = self.get_filtered_programmers(programmers)
     lc = [[name, alias] for alias, name in programmers.items()]
     choice = Listbox(lc,
                      self.i,
                      self.o,
                      "Avrdude programmer picker listbox",
                      selected=self.current_programmer).activate()
     if choice:
         self.current_programmer = choice
         self.config["default_programmer"] = self.current_programmer
         self.save_config()
コード例 #28
0
def get_hw_version(li):
    if rpiinfo.is_pi_zero():
        if rpiinfo.is_pi_zero_w():
            return "zerow"
        else:
            return "zero"
    else:
        with li.paused:
            if vcgencmd.otp_problem_detected(vcgencmd.otp_dump()):
                TextReader(otp_fail_text, i, o, h_scroll=False).activate()
            else:
                Printer("Hardware detect failed! Pick your hardware:", i, o, 5)
            lc = [["Pi Zero", "zero"], ["Pi Zero W", "zerow"],
                  ["Other", "other"]]
            choice = Listbox(
                lc, i, o, name="WiFi repair - hw revision picker").activate()
        return choice
コード例 #29
0
 def pick_branch(self):
     #TODO: allow adding branches dynamically instead of having a whitelist
     lc = [[branch_name] for branch_name in self.config["branches"]]
     branch = Listbox(
         lc, i, o, name="Git updater branch selection listbox").activate()
     if branch:
         try:
             GitInterface.checkout(branch)
             self.check_revisions = False
             updated = self.update()
             self.check_revisions = True
         except:
             PrettyPrinter(
                 "Couldn't check out the {} branch! Try resolving the conflict through the command-line."
                 .format(branch), i, o, 3)
         else:
             PrettyPrinter("Now on {} branch!".format(branch), i, o, 2)
             self.suggest_restart()
コード例 #30
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