def load_all_apps(self): base_menu = Menu([], self.i, self.o, "Main app menu", exitable=False) # Main menu for all applications. base_menu.exit_entry = ["Exit", "exit"] base_menu.process_contents() self.subdir_menus[self.app_directory] = base_menu apps_blocked_in_config = self.config.get("do_not_load", {}) for path, subdirs, modules in app_walk(self.app_directory): for subdir in subdirs: # First, we create subdir menus (not yet linking because they're not created in correct order) and put them in subdir_menus. subdir_path = os.path.join(path, subdir) self.subdir_menus[subdir_path] = Menu([], self.i, self.o, subdir_path) for _module in modules: # Then, we load modules and store them along with their paths try: module_path = os.path.join(path, _module) if module_path in apps_blocked_in_config: logger.warning( "App {} blocked from config; not loading".format( module_path)) continue app = self.load_app(module_path) logger.info("Loaded app {}".format(module_path)) self.app_list[module_path] = app except Exception as e: logger.error("Failed to load app {}".format(module_path)) logger.error(traceback.format_exc()) Printer(["Failed to load", os.path.split(module_path)[1]], self.i, self.o, 2) for subdir_path in self.subdir_menus: # Now it's time to link menus to parent menus if subdir_path == self.app_directory: continue parent_path = os.path.split(subdir_path)[0] ordering = self.get_ordering(parent_path) parent_menu = self.subdir_menus[parent_path] subdir_menu = self.subdir_menus[subdir_path] subdir_menu_name = self.get_subdir_menu_name(subdir_path) # Inserting by the ordering given parent_menu_contents = self.insert_by_ordering( [subdir_menu_name, subdir_menu.activate], os.path.split(subdir_path)[1], parent_menu.contents, ordering) parent_menu.set_contents(parent_menu_contents) for app_path in self.app_list: # Last thing is attaching applications to the menu structure created. app = self.app_list[app_path] subdir_path, app_dirname = os.path.split(app_path) ordering = self.get_ordering(subdir_path) menu_name = app.menu_name if hasattr( app, "menu_name") else app_dirname.capitalize() self.bind_callback(app, app_path, menu_name, ordering, subdir_path) return base_menu
def test_contents_hook(self): """Tests whether menu contents hook is executed""" ev = Event() def gen_contents(): return [["True", ev.clear] if ev.isSet() else ["False", ev.set]] mu = Menu([], get_mock_input(), get_mock_output(), name=mu_name, contents_hook=gen_contents, config={}) def scenario(): assert mu.contents[0][0] == "False" mu.select_entry() assert mu.contents[0][0] == "True" mu.select_entry() assert mu.contents[0][0] == "False" mu.deactivate() assert not mu.in_foreground with patch.object(mu, 'idle_loop', side_effect=scenario) as p: mu.activate()
def show_quick_scan_results_for_network(net_ip, net_results): global current_scan, current_filename current_scan = net_results current_filename = "net_{}_{}".format(net_ip, time.strftime("%Y%m%d-%H%M%S")) net_report = [] ips = net_results.all_hosts() ips = sort_ips(ips) for ip in ips: result = net_results[ip] open_ports_found = "tcp" in result.keys() and result["tcp"] if open_ports_found: open_port_count = len([ port_desc for port_desc in result["tcp"].values() if "state" in port_desc and port_desc["state"] == "open" ]) mac = result["addresses"]["mac"] if "mac" in result[ "addresses"] else "Unknown MAC" if result["vendor"] and mac in result["vendor"].keys(): info_str = result["vendor"][mac] else: info_str = mac if open_ports_found: info_str = "{}P;{}".format(open_port_count, info_str) net_report.append([[ip, info_str], lambda x=result: ip_info_menu(x)]) Menu(net_report, i, o, entry_height=2).activate()
def run_scan(): Printer("Scanning:", i, o, 0) msg = [ 'M-SEARCH * HTTP/1.1', 'Host:{}:1900'.format(config["dst"]), 'ST:{}'.format(config["st"]), 'Man:"ssdp:discover"', 'MX:1', '' ] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.settimeout(config["timeout"]) s.sendto('\r\n'.join(msg), (config["dst"], 1900)) found_devices = OrderedDict() while True: try: data, addr = s.recvfrom(32 * 1024) except socket.timeout: break except: print(format_exc()) else: ip_str = "{}:{}".format(*addr) found_devices[ip_str] = data if not found_devices: Printer("No devices found", i, o, 2) else: data = [[ip, lambda x=ip, y=d: read_info(x, y)] for ip, d in found_devices.iteritems()] Menu(data, i, o).activate()
def all_units(): menu_contents = [] units = systemctl.list_units() for unit in units: menu_contents.append( [unit["basename"], lambda x=unit["name"]: unit_menu(x)]) Menu(menu_contents, i, o, "All unit list menu").activate()
def init_app(input, output): global callback, i, o i = input o = output # Getting references to output and input device objects and saving them as globals main_menu_contents = [["Type URL", main], ["Exit", 'exit']] main_menu = Menu(main_menu_contents, i, o, "Browser Menu") callback = main_menu.activate
def change_interface(): menu_contents = [] interfaces = pyw.winterfaces() for interface in interfaces: menu_contents.append( [interface, lambda x=interface: change_current_interface(x)]) Menu(menu_contents, i, o, "Interface change menu").activate()
def callback(): #A function for main menu to be able to dynamically update def get_contents(): current_interface = wpa_cli.get_current_interface() return [["Status", status_monitor], ["Current: {}".format(current_interface), change_interface], ["Scan", scan], ["Networks", show_scan_results], ["Saved networks", manage_networks]] #Now testing if we actually can connect try: get_contents() except OSError as e: if e.errno == 2: Printer(["Do you have", "wpa_cli?"], i, o, 3, skippable=True) return else: raise e except wpa_cli.WPAException: Printer([ "Do you have", "wireless cards?", "Is wpa_supplicant", "running?" ], i, o, 3, skippable=True) return else: Menu([], i, o, "wpa_cli main menu", contents_hook=get_contents).activate()
def test_enter_on_last_returns_right(self): num_elements = 3 contents = [["A" + str(i), "a" + str(i)] for i in range(num_elements)] mu = Menu(contents, get_mock_input(), get_mock_output(), name=mu_name, config={}) mu.refresh = lambda *args, **kwargs: None # Checking at other elements - shouldn't return def scenario(): mu.select_entry() # KEY_ENTER assert mu.in_foreground # Should still be active mu.deactivate( ) # because is not deactivated yet and would idle loop otherwise with patch.object(mu, 'idle_loop', side_effect=scenario) as p: return_value = mu.activate() assert return_value is None # Scrolling to the end of the list and pressing Enter - should return a correct dict def scenario(): for i in range(num_elements): mu.move_down() # KEY_DOWN x3 mu.select_entry() # KEY_ENTER assert not mu.in_foreground with patch.object(mu, 'idle_loop', side_effect=scenario) as p: return_value = mu.activate() assert isinstance(return_value, dict) assert all( [isinstance(key, basestring) for key in return_value.keys()]) assert all( [isinstance(value, bool) for value in return_value.values()])
def test_left_key_returns_none(self): num_elements = 3 contents = [["A" + str(i), "a" + str(i)] for i in range(num_elements)] mu = Menu(contents, get_mock_input(), get_mock_output(), name=mu_name, config={}) mu.refresh = lambda *args, **kwargs: None # Checking at the start of the list def scenario(): mu.deactivate() # KEY_LEFT assert not mu.in_foreground with patch.object(mu, 'idle_loop', side_effect=scenario) as p: return_value = mu.activate() assert return_value is None # Checking at the end of the list def scenario(): for i in range(num_elements): mu.move_down() # KEY_DOWN x3 mu.deactivate() # KEY_LEFT assert not mu.in_foreground with patch.object(mu, 'idle_loop', side_effect=scenario) as p: return_value = mu.activate() assert return_value is None
def test_graphical_redraw_with_eh_2(self): """ Tests for a bug where a menu with one two-elements-high entry would fail to render """ num_elements = 3 o = get_mock_graphical_output() contents = [[["A" + str(i), "B" + str(i)], "a" + str(i)] for i in range(num_elements)] mu = Menu(contents, get_mock_input(), o, name=mu_name, entry_height=2, append_exit=False, config={}) Canvas.fonts_dir = fonts_dir # Exiting immediately, but we should get at least one redraw def scenario(): mu.deactivate() # KEY_LEFT assert not mu.in_foreground with patch.object(mu, 'idle_loop', side_effect=scenario) as p: return_value = mu.activate() assert o.display_image.called assert o.display_image.call_count == 1 #One in to_foreground
def app_open_entries(): global config 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) 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) mc = [["Add an entry", add_entry_menu], ["Remove an entry", remove_entry_menu]] Menu(mc, i, o, name="Zeromenu app open entry settings menu").activate()
def wireless_status(): w_status = wpa_cli.connection_status() state = w_status['wpa_state'] status_menu_contents = [[["state:", state]]] #State is an element that's always there, let's see possible states if state == 'COMPLETED': #We have bssid, ssid and key_mgmt at least status_menu_contents.append(['SSID: '+w_status['ssid']]) status_menu_contents.append(['BSSID: '+w_status['bssid']]) key_mgmt = w_status['key_mgmt'] status_menu_contents.append([['Security:', key_mgmt]]) #If we have WPA in key_mgmt, we also have pairwise_cipher and group_cipher set to something other than NONE so we can show them if key_mgmt != 'NONE': try: #What if? group = w_status['group_cipher'] pairwise = w_status['pairwise_cipher'] status_menu_contents.append([['Group/Pairwise:', group+"/"+pairwise]]) except: pass elif state in ['AUTHENTICATING', 'SCANNING', 'ASSOCIATING']: pass #These states don't have much information #In any case, we might or might not have IP address info status_menu_contents.append([['IP address:',w_status['ip_address'] if 'ip_address' in w_status else 'None']]) #We also always have WiFi MAC address as 'address' status_menu_contents.append(['MAC: '+w_status['address']]) status_menu = Menu(status_menu_contents, i, o, "Wireless status menu", entry_height=2) status_menu.activate()
def activate(self, activator=None): if CountUpTile.activate(self, activator): xu = self.map.size.x // 4 yu = self.map.size.y // 4 b = Menu(Position(xu, yu), Position(xu * 2, yu * 2), title="Camera Control") b.add('1', "View cameras") b.add( '2', "Switch %s cameras" % (CameraConsole.cameras_on and 'off' or 'on')) b.add('x', "Exit") c = b.get_key() del b cams = self.map.find_all(StaticCamera, Monster) if c == '1': for cam in cams: self.map.prepare_fov(cam.pos, reset=False) self.map.player.handle_keys() elif c == '2': if CameraConsole.cameras_on: for cam in cams: cam.add_effect(StatusEffect.BLIND) else: for cam in cams: cam.remove_effect(StatusEffect.BLIND) CameraConsole.cameras_on = not CameraConsole.cameras_on return True return False
def callback(): main_menu_contents = [["Read from USB", usb_read], ["Prepare USB", usb_prepare], ["Problems and our solutions", problems_menu], ["Privacy policy", privacy_policy], ["Terms and conditions", terms_conditions]] Menu(main_menu_contents, i, o).activate()
def settings_menu(): menu_contents = [ #["Select card", select_card], ["Select channel", select_channel], ["Adjust type", select_adjust_type], ["Adjust amount", change_adjust_amount]] Menu(menu_contents, i, o, "Settings menu").activate()
def pomodoro_options_menu(): menu_contents = [ ["Acknowledge", e_wr(ack_notification)], ["Start", e_wr(start_monitoring)], ["Start break", e_wr(start_break)], ["Stop", e_wr(stop_monitoring)]] Menu(menu_contents, i, o, "Pomodoro options menu").activate()
def init_app(input, output): global main_menu, callback, i, o i = input; o = output i.set_nonmaskable_callback("KEY_PROG1", lambda: mocp_next(silent=True) ) i.set_nonmaskable_callback("KEY_CAMERA", lambda: mocp_prev(silent=True) ) main_menu = Menu(main_menu_contents, i, o, "MOCP menu") callback = main_menu.activate
def wireless_status(): Menu([], i, o, contents_hook=get_wireless_status_mc, name="Wireless status menu", entry_height=2).activate()
def callback(): if not check_modem_connection(): Printer(ffs("Modem connection failed. Try again in 10 seconds.", o.cols), i, o) return contents = [["Status", status_refresher], ["Call", call_view]] Menu(contents, i, o).activate()
def saved_networks(): Menu([], i, o, name="Saved network menu", contents_hook=get_saved_networks_mc, catch_exit=False).activate()
def show_linux_info(): linux_info = sys_info.linux_info() menu_contents = [[["Hostname:", linux_info["hostname"]]], [["Kernel version:", linux_info["k_release"]]], [["Architecture:", linux_info["machine"]]], [["Distribution:", " ".join(linux_info["distribution"])]]] Menu(menu_contents, i, o, entry_height=2).activate()
def write_menu(self): def verify_and_run(): """ If file that we need to write to the chip does not exist, we should warn the user and abort. """ if not (os.path.exists(self.write_file) and os.path.isfile(self.write_file)): PrettyPrinter("File does not exist/invalid!", self.i, self.o, 2) return self.create_process() if self.write_checklist(): self.detect_and_run() # Needs to be autogenerated so that filename updates after changing them def get_contents(): if self.write_file: dir, filename = os.path.split(self.write_file) else: dir, filename = '/', 'None' contents = [[ "File: {}".format(filename), lambda x=dir: self.set_write_file(x) ], ["Use bootloader", self.pick_bootloader], ["Use last read file", self.set_write_as_last_read], ["Continue", verify_and_run]] return contents Menu([], self.i, self.o, contents_hook=get_contents, name="Avrdude write parameter menu", append_exit=False).activate()
def init_app(input, output): global main_menu, callback, i, o i = input o = output i.set_nonmaskable_callback("KEY_PROG1", mocp_next) main_menu = Menu(main_menu_contents, i, o, "MOCP menu") callback = main_menu.activate
def callback(): script_menu_contents = [["Script by path", call_by_path], ["Custom command", call_command]] scripts_in_config = [] for script_def in config: script_path = script_def["path"] if script_path.startswith('./'): script_path = script_path.lstrip('.').lstrip('/') script_path = local_path(script_path) scripts_in_config.append(script_path) args = script_def["args"] if "args" in script_def else [] script_name = script_def[ "name"] if "name" in script_def else os.path.split(script_path)[1] script_list = [script_path] + args script_menu_contents.append( [script_name, lambda x=script_list: call_external(x)]) other_scripts = os.listdir(local_path(scripts_dir)) for script in other_scripts: relpath = local_path(scripts_dir, script) if relpath not in scripts_in_config: script_menu_contents.append([ os.path.join(scripts_dir, script), lambda x=relpath: call_external([x]) ]) Menu(script_menu_contents, i, o, "Script menu").activate()
def test_fo_graphical_icon_disappears(self): o = get_mock_graphical_output() overlay = FunctionOverlay([lambda: True, lambda: False]) mu = Menu([], get_mock_input(), o, name=ui_name, config={}) mu.idle_loop = lambda *a, **k: True Canvas.fonts_dir = fonts_dir overlay.apply_to(mu) def activate(): mu.before_activate() mu.to_foreground() mu.idle_loop() img_1 = o.display_image.call_args[0] mu.idle_loop() mu.refresh() img_2 = o.display_image.call_args[0] assert(img_1 == img_2) for i in range(overlay.duration): mu.idle_loop() mu.refresh() img_2 = o.display_image.call_args[0] assert(img_1 != img_2) mu.deactivate() # KEY_LEFT with patch.object(mu, 'activate', side_effect=activate) as p: mu.activate()
def show_menu(): script_menu_contents = [] scripts_in_config = [] try: config = read_config(config_path) except ValueError: Printer("Invalid config!", i, o) else: for script_def in config: script_path = script_def["path"] if script_path.startswith('./'): script_path = script_path.lstrip('.').lstrip('/') script_path = os.path.join(base_dir, script_path) scripts_in_config.append(script_path) args = script_def["args"] if "args" in script_def else [] script_name = script_def[ "name"] if "name" in script_def else os.path.split( script_path)[1] script_list = [script_path] + args script_menu_contents.append( [script_name, lambda x=script_list: call_external(x)]) other_scripts = os.listdir(os.path.join(base_dir, scripts_dir)) for script in other_scripts: relpath = os.path.join(base_dir, scripts_dir, script) if relpath not in scripts_in_config: script_menu_contents.append([ os.path.join(scripts_dir, script), lambda x=relpath: call_external([x]) ]) Menu(script_menu_contents, i, o, "Script menu").activate()
def test_ho_keymap(self): overlay = HelpOverlay(lambda: True) mu = Menu([], get_mock_input(), get_mock_output(), name=ui_name, config={}) overlay.apply_to(mu) self.assertIsNotNone(mu.keymap) assert("KEY_F5" in mu.keymap) assert(all([callable(v) for v in mu.keymap.values()]))
def list_mounts(): menu_contents = [] mounts = device_info.get_mounted_partitions() for device in mounts: mountpoint = mounts[device] menu_contents.append([mountpoint, lambda x=mountpoint, y=device: view_mount(x, y)]) Menu(menu_contents, i, o).activate()
def filtered_units(): menu_contents = [] units = systemctl.list_units() for unit in units: if unit["type"] in config["allowed_types"]: menu_contents.append([unit["basename"], lambda x=unit: unit_menu(x)]) Menu(menu_contents, i, o, "All unit list menu").activate()