def main(): pulse = pulsectl.Pulse() rofi = Rofi() # Ask user for a source-output to move source_outputs = pulse.source_output_list() selections = ['All'] for so in source_outputs: try: selections.append(so.proplist['application.name'] + ': ' + so.proplist['media.name']) except KeyError: selections.append(so.proplist['media.name']) source_output_index, _ = rofi.select("Select source-output to move", selections) if source_output_index == -1: # They hit escape return # convert to pulse source-output index or -1 if all was selected source_output_index = -1 if source_output_index == 0 else source_outputs[ source_output_index - 1].index # Ask user which source to move it to sources = pulse.source_list() current_default_name = pulse.server_info().default_source_name for i, s in enumerate(sources): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default sink?") return source_index, _ = rofi.select("Select destination source", [ s.description if s.description not in SOURCE_ALIASES else SOURCE_ALIASES[s.description] for s in sources ], select=current_default) if source_index == -1: # They hit escape return # Move the source-output to the source if source_output_index == -1: # Move all for si in source_outputs: pulse.source_output_move(si.index, sources[source_index].index) else: pulse.source_output_move(source_output_index, sources[source_index].index)
def main(): pulse = pulsectl.Pulse() rofi = Rofi(rofi_args=['-theme', 'themes/onedark', '-i']) # Ask user for a sink-input to move sink_inputs = pulse.sink_input_list() selections = ['All'] for si in sink_inputs: try: selections.append(si.proplist['application.name'] + ': ' + si.proplist['media.name']) except KeyError: selections.append(si.proplist['media.name']) sink_input_index, _ = rofi.select("Select sink-input to move", selections) if sink_input_index == -1: # They hit escape return # convert to pulse sink-input index or -1 if all was selected sink_input_index = -1 if sink_input_index == 0 else sink_inputs[ sink_input_index - 1].index # Ask user which sink to move it to sinks = pulse.sink_list() current_default_name = pulse.server_info().default_sink_name for i, s in enumerate(sinks): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default sink?") return sink_index, _ = rofi.select("Select destination sink", [ s.description if s.description not in SINK_ALIASES else SINK_ALIASES[s.description] for s in sinks ], select=current_default) if sink_index == -1: # They hit escape return # Move the sink-input to the sink if sink_input_index == -1: # Move all for si in sink_inputs: pulse.sink_input_move(si.index, sinks[sink_index].index) else: pulse.sink_input_move(sink_input_index, sinks[sink_index].index)
def main(): pulse = pulsectl.Pulse() rofi = Rofi() # Get all loopback modules raw_loopbacks = list(filter(lambda m: m.name == 'module-loopback', pulse.module_list())) # Parse out the source and sink names of each loopback sink_re = re.compile('sink="?([^ "]+)"?') source_re = re.compile('source="?([^ "]+)"?') loopbacks = [] for lb in raw_loopbacks: sink_name = sink_re.search(lb.argument).group(1) source_name = source_re.search(lb.argument).group(1) sink_name = SINK_ALIASES[sink_name] if sink_name in SINK_ALIASES else sink_name source_name = SOURCE_ALIASES[source_name] if source_name in SOURCE_ALIASES else source_name loopbacks.append((lb.index, source_name, sink_name)) # Have the user select a loopback loopback_index, _ = rofi.select("Delete loopback", [l[1] + " -> " + l[2] for l in loopbacks]) if loopback_index == -1: # The user hit escape return # Remove it pulse.module_unload(loopbacks[loopback_index][0])
def rofi_list_lectures(): lectures = CURRENT_PROJECT.course_info if not lectures: return lectures = lectures.get_lectures() lectures_str = [str(l) for l in lectures] rofi = Rofi(rofi_args=["-i"]) index, key = rofi.select("Choose a lecture", lectures_str, key4=('Super+o', "Open lecture in Zathura"), key5=('Super+e', "Open tex file in vim"), key6=("Super+n", "Create a new Lecture")) if index == -1: return if key == 4: lectures[index].view().execute() elif key == 5: lectures[index].edit().execute() else: rofi = Rofi(rofi_args=["-i"]) title = rofi.text_entry("Title for lecture: ") lecture = Lecture.create_new(CURRENT_PROJECT_PATH, title) lecture.edit().execute()
def rofi_handler(music, sources, use_icons=False, row=0): """ Handle rofi using passed music list and display options """ r = Rofi() # keys that can be used in rofi for different operations to be handled keys = { 'key0': ('Return', 'Add'), 'key1': ('Ctrl+i', 'Insert'), 'key2': ('Alt+Return', 'Add...'), 'key3': ('Alt+Ctrl+i', 'Insert...') } # If only one source is in use, set source name as prompt if len(sources) == 1: prompt = sources[0].capitalize() else: prompt = 'Music' # if the row arg is passed, set the initial current row args = '-i -selected-row {}'.format(row).split() # use nerdfont icons in rofi listings to show album/song source if use_icons: icons = {'file': '', 'spotify': ''} rows = [ '{} {} - {}'.format(icons[i['type']], i['artist'], i['title']) for i in music ] else: rows = ['{} - {}'.format(i['artist'], i['title']) for i in music] index, key = r.select(prompt, rows, rofi_args=args, **keys) return index, key
def save_menu(): from collections import OrderedDict from spotify_item import SpotifyItem from util import my_playlists_file, notify_context rofi = Rofi(rofi_args=["-no-sort", "-i"]) track: Track = get_current_track() options = OrderedDict() options[add_icon_to_str("Save Song", "emblem-favorite")] = track.save options[add_icon_to_str( "Add song to playlist", "list-add")] = lambda: add_to_playlist_menu(my_playlists_file, track) options[add_icon_to_str( "Play track album", "media-playback-start" )] = lambda: SpotifyItem.from_uri(track.uri).album.play() options[add_icon_to_str("Query context", "dialog-question")] = lambda: notify_context() options[add_icon_to_str("Remove song", "user-trash")] = track.unsave index, key = rofi.select("Music", list(options.keys()), message=rofi.escape(str(track))) # user escape/quit if index == -1: return # call the lambda at the chosen index list(options.values())[index]()
def main(): pulse = pulsectl.Pulse() rofi = Rofi() sinks = pulse.sink_list() current_default_name = pulse.server_info().default_sink_name for i, s in enumerate(sinks): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default sink?") return sink_index, _ = rofi.select("Select default sink", [ s.description if s.description not in SINK_ALIASES else SINK_ALIASES[s.description] for s in sinks ], select=current_default) if sink_index == -1: return pulse.default_set(sinks[sink_index]) # for i3 bar only subprocess.run(["py3-cmd", "refresh", "volume_status"])
def add_to_playlist_menu(playlist_path: Path, track: Track): from spotify_item import Playlist pls = Favorites.from_file(playlist_path) pls.save_all_images() rofi = Rofi(rofi_args=["-no-sort", "-i"]) index, key = rofi.select(f"Add \"{track}\" to playlist", pls.get_display_list(detail=0), key9=("Alt-X", "Remove Playlist")) # escape key/exit was pressed if index == -1: return playlist = pls.items[index] # remove playlist if key == 9: remove = prompt_menu(f"Remove {playlist} from playlists?", no_first=True) if remove: pls.remove_item(playlist) pls.write(playlist_path) return if isinstance(playlist, Playlist): if prompt_menu(f"Add {track} to {playlist.name}?", no_first=False): playlist.add_item(track)
def main(): pulse = pulsectl.Pulse() rofi = Rofi() # Get all loopback modules raw_loopbacks = list( filter(lambda m: m.name == 'module-loopback', pulse.module_list())) # Parse out the source and sink names of each loopback sink_re = re.compile('sink="?([^ "]+)"?') source_re = re.compile('source="?([^ "]+)"?') loopbacks = [] for lb in raw_loopbacks: sink_name = sink_re.search(lb.argument).group(1) source_name = source_re.search(lb.argument).group(1) sink_name = SINK_ALIASES[ sink_name] if sink_name in SINK_ALIASES else sink_name source_name = SOURCE_ALIASES[ source_name] if source_name in SOURCE_ALIASES else source_name loopbacks.append((lb.index, source_name, sink_name)) # Have the user select a loopback loopback_index, _ = rofi.select("Delete loopback", [l[1] + " -> " + l[2] for l in loopbacks]) if loopback_index == -1: # The user hit escape return # Remove it pulse.module_unload(loopbacks[loopback_index][0])
def main(): pulse = pulsectl.Pulse() rofi = Rofi() # Ask user for a sink-input to move sink_inputs = pulse.sink_input_list() selections = ['All'] for si in sink_inputs: try: selections.append(si.proplist['application.name'] + ': ' + si.proplist['media.name']) except KeyError: selections.append(si.proplist['media.name']) sink_input_index, _ = rofi.select("Select sink-input to move", selections) if sink_input_index == -1: # They hit escape return # convert to pulse sink-input index or -1 if all was selected sink_input_index = -1 if sink_input_index == 0 else sink_inputs[sink_input_index-1].index # Ask user which sink to move it to sinks = pulse.sink_list() current_default_name = pulse.server_info().default_sink_name for i, s in enumerate(sinks): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default sink?") return sink_index, _ = rofi.select("Select destination sink", [s.description if s.description not in SINK_ALIASES else SINK_ALIASES[s.description] for s in sinks], select=current_default) if sink_index == -1: # They hit escape return # Move the sink-input to the sink if sink_input_index == -1: # Move all for si in sink_inputs: pulse.sink_input_move(si.index, sinks[sink_index].index) else: pulse.sink_input_move(sink_input_index, sinks[sink_index].index)
def _input(msg, options): r = Rofi(rofi_args=["-theme", "base16-default-dark"]) if options: key = -1 while key != 0: index, key = r.select(msg, options) return options[index] else: return r.text_entry(msg)
def prompt_menu(question: str, no_first=True, str_yes="Yes", str_no="No"): r = Rofi(rofi_args=["-i"]) str_yes = add_icon_to_str(str_yes, "object-select") str_no = add_icon_to_str(str_no, "window-close") options = [str_no, str_yes] if no_first else [str_yes, str_no] index, _ = r.select(question, options) if index == -1: return False return options[index] == str_yes
def open_resources_rofi(self): """ Generates a comman that opens a rofi window which contains all the resources this project provides """ rofi = Rofi(rofi_args=["-i"]) resources = list(self.other_resources.keys()) index, _ = rofi.select("Select a resource", resources) if index == -1: return command, *args = self.other_resources.get(resources[index]) return Command(command, args)
class RofiTunes: def __init__(self): self.rofi = Rofi() self.songs = [] self.mpd_dir = f"""{os.environ.get('HOME')}/.mpd""" def update_library(self): pass def build_library(self): # TODO: extract artist/genre/track ect from audio file proc = subprocess.Popen(['mpc', 'listall'], stdout=subprocess.PIPE) for song in proc.stdout.readlines(): try: mp3 = eyed3.load("{}/{}".format('/home/jack/Music', song.decode('utf-8').strip())) #TODO: Now you can extract all the relevant metadata title = mp3.tag.title album = mp3.tag.album artist = mp3.tag.artist self.songs.append("{} - {} - {}".format(title, album, artist)) except AttributeError: pass except UnicodeDecodeError: pass #print("{} - Invalid or No attribute tag".format(song.decode('utf-8').strip())) def build_menu(self): choice = self.rofi.select(">", self.songs, key1=("Alt+1", "Description")) print(choice) if choice[1] >= 1: # NOTE: A hotkey was pushed pass elif choice[0] != -1: return self.play_song(choice[0]) def play_song(self, choice): proc = subprocess.Popen(['mpc', 'play', str(choice)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(self.songs[choice].strip()) try: outs, errs = proc.communicate(timeout=15) print(outs.decode()) print(errs.decode()) except TimeoutError: proc.kill() outs, errs = proc.communicate() print(outs.decode()) print(errs.decode())
def main(): r = Rofi() r.lines = 3 r.width = 300 options = ['sleeping now', 'know time going to sleep', 'know time waking up'] index, key = r.select('> ', options) if index == 0: now = datetime.datetime.now() + datetime.timedelta(minutes=90*2) + datetime.timedelta(minutes=15) possibilities = [] for i in range(5): now += datetime.timedelta(minutes=90) possibilities.append('%d:%02d' % (now.hour, now.minute)) possibilities = '\n'.join(possibilities) notify('Wake up times', possibilities)
def main(): history = read_history_file() history['PRIMARY'].reverse() history['CLIPBOARD'].reverse() history = history['PRIMARY'] + history['CLIPBOARD'] history = sorted(set(history), key=history.index) r = Rofi() prompt = r.select('>', history, message='Select an item to copy to your clipboard') if prompt == (-1, -1): # Bad Exit for rofi raise SystemExit(1) print("Copying {}".format(history[prompt[0]])) pyperclip.copy(history[prompt[0]])
def exportToRofi(aliases): selection = [] for alias in aliases.values(): name = alias['name'].strip() if name == '': name = alias['alias'] # print("%s | %s" % (name, alias['email'])) selection.append("%s | %s" % (name, alias['email'])) r = Rofi(rofi_args=[ '-i', '-disable-history', '-levenshtein-sort', '-matching', 'normal', '-e' ]) index, key = r.select("what", selection) selected = selection[index].split('|') print("%s <%s>" % (selected[0], selected[1].strip()))
def play_menu(path: Path = favorites_file): favs = Favorites.from_file(path) favs.save_all_images() rofi = Rofi(rofi_args=["-no-sort", "-i", "-matching", "fuzzy"]) index, key = rofi.select("Play", favs.get_display_list(detail=2), key1=("Alt+Shift+Return", "Play without shuffle\n"), key2=("Alt+Return", "Play with shuffle\n"), key8=("Alt+p", "Search Spotify\n"), key9=("Alt+X", "Remove from menu")) # escape key/exit was pressed if index == -1: return # search button pressed if key == 8: search_menu() return item = favs.items[index] # remove from menu if key == 9: remove = prompt_menu(f"Remove {repr(item)} from favorites?", no_first=True) if remove: favs.remove_item(item) favs.write() return # play without shuffle if key == 1: from util import set_shuffle set_shuffle(False) # play with shuffle elif key == 2: from util import set_shuffle set_shuffle(True) favs.bring_to_top(item) favs.write(path) item.play()
def choose_project(): projects = list(PROJECTS.keys()) rofi = Rofi(rofi_args=["-i"]) index, _ = rofi.select("Project to work on", projects) if index == -1: return try: set_current_from_link() global CURRENT_PROJECT CURRENT_PROJECT.unlink_soft_link().execute() except: pass CURRENT_PROJECT_PATH = PROJECTS.get(projects[index]) CURRENT_PROJECT = Project(CURRENT_PROJECT_PATH) CURRENT_PROJECT.create_soft_link().execute()
def main(): pulse = pulsectl.Pulse() rofi = Rofi() sinks = pulse.sink_list() current_default_name = pulse.server_info().default_sink_name for i, s in enumerate(sinks): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default sink?") return sink_index, _ = rofi.select("Select default sink", [s.description if s.description not in SINK_ALIASES else SINK_ALIASES[s.description] for s in sinks], select=current_default) if sink_index == -1: return pulse.default_set(sinks[sink_index])
def main(): pulse = pulsectl.Pulse() rofi = Rofi() sources = pulse.source_list() current_default_name = pulse.server_info().default_source_name current_default = None for i, s in enumerate(sources): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default source?") return source_index, _ = rofi.select("Select default source", [s.description if s.description not in SOURCE_ALIASES else SOURCE_ALIASES[s.description] for s in sources], select=current_default) if source_index == -1: return pulse.default_set(sources[source_index])
class FuzzySelect: def __init__(self, buffers, opts): self.buffers = buffers self.opts = opts if not opts.rofi: self.rofi = Rofi(rofi_args=[ '-matching', 'fuzzy', '-levenshtein-sort', '-i', '-no-case-sensitive' ]) else: self.rofi = Rofi(self.opts.ROFI) # Accepts a predicate which returs list of buffers def select(self, bufs, name): buf_names = list(map(lambda x: x.short_name, bufs)) logging.debug("Buf Names: {}".format(buf_names)) index, key = self.rofi.select(name, buf_names, rofi_args=['-i']) if index == -1: return logging.debug("Index: {}, Key: {}".format(index, key)) selected_buffer = self.buffers.get_buffer( lambda b: b.short_name == buf_names[index]) selected_buffer.show() self.buffers.set_to_hide(selected_buffer) weechat.command("", "/buffer {}".format(selected_buffer.full_name)) # TODO This code can be made much cleaner # Alt + t def select_any_buffer(self): self.select(self.buffers.get_buffers(), "Buffers") def select_channels(self): self.select(self.buffers.get_channels(), "Channels") def select_pms(self): self.select(self.buffers.get_pm_buffers(), "PM") def select_matrix(self): self.select(self.buffers.get_matrix_buffers(), "Matrix")
def main(): pulse = pulsectl.Pulse() rofi = Rofi() sources = pulse.source_list() current_default_name = pulse.server_info().default_source_name current_default = None for i, s in enumerate(sources): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default source?") return source_index, _ = rofi.select("Select default source", [ s.description if s.description not in SOURCE_ALIASES else SOURCE_ALIASES[s.description] for s in sources ], select=current_default) if source_index == -1: return pulse.default_set(sources[source_index])
#!/usr/bin/env python # Script to choose between the current scratchpads using rofi ########### REQUIRED ############# # Rofi (obviously) # # sudo pip install i3ipc-python # # sudo pip install python-rofi # ################################## import sys from i3ipc import Connection, Event from rofi import Rofi i3 = Connection() r = Rofi() scratchpads = [] for node in i3.get_tree().scratchpad().floating_nodes: scratchpads.append((node.nodes[0].name, node.nodes[0].window)) selected_index, selected_key = r.select("Choose a scratchpad", [x[0] for x in scratchpads]) if selected_index == -1: sys.exit(1) i3.command('[id='"%s"'] scratchpad show' % scratchpads[selected_index][1])
#!/bin/python import os from rofi import Rofi r = Rofi() script = "/home/suphal/.scripts/" ls = os.listdir(script) result = r.select("Which script would you like to run?", ls) j = 0 dist = {} for i in ls: dist[(j, 0)] = i j += 1 for i in dist: if str(i) == str(result): path = "/bin/python " + script + dist[i] os.system(path)
r = Rofi() options = [ # 'Shutdown ⏻', # 'Reboot ', # 'Sleep ', # 'Quit i3 ', # 'Lock ' 'Shutdown', 'Reboot', 'Sleep', 'Hibernate', 'Quit Desktop', 'Lock' ] commands = [ '~/bin/util/shutdown.sh', 'reboot', '~/bin/util/sleep.sh', '~/bin/util/hibernate.sh', '~/bin/util/quit.sh', '~/bin/util/lock.sh' ] index, key = r.select('Exit', options, lines=len(options) + 1, width=30) if key == 0: confirm = r.select('Are you sure?', ['Yes', 'No'], lines=3, width=20)[0] print(confirm) if confirm == [0]: os.system(commands[int(index[0])])
#!/usr/bin/python import i3ipc from rofi import Rofi scr_windows = list() i3 = i3ipc.Connection() tree = i3.get_tree() for leaf in tree.scratchpad().leaves(): scr_windows.append(leaf.window_class) r = Rofi() index, key = r.select('window', scr_windows) if key != 0: exit(0) selected = scr_windows[index] window = tree.find_classed(selected)[0] window.command("focus") window.command("move position center")
home = str(f"/home/{user}") multimc_folder = f"{home}/.local/share/multimc/instances" # replace with wherever multimc folder is, if this isn't it try: with open(f"{multimc_folder}/instgroups.json", "r") as raw_inst_groups: instgroups = json.loads(raw_inst_groups.read()) except: r.exit_with_error("MultiMC folder not found. Please add it to the code.") instances = [] instances_shown = [] instance_name = "" for group in instgroups["groups"]: for instance in instgroups["groups"][group]["instances"]: instances.append(instance) with open(f"{multimc_folder}/{instance}/instance.cfg", "r") as instancecfg: configs = instancecfg.read().split("\n") for cfg in configs: if (cfg.startswith("name=")): instance_name = cfg.replace("name=", "") break instances_shown.append(f"{instance_name} ({group})") index, key = r.select('instance', instances_shown) if (key == -1): exit() launched_instance = str(instances[index]) print(f"launching {launched_instance}") subprocess.run(["multimc", "-l", launched_instance])
def main(): pulse = pulsectl.Pulse() rofi = Rofi() # Ask user which source to link sources = pulse.source_list() current_default_name = pulse.server_info().default_source_name for i, s in enumerate(sources): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default sink?") return source_index, _ = rofi.select("Select receiving source", [s.description if s.description not in SOURCE_ALIASES else SOURCE_ALIASES[s.description] for s in sources], select=current_default) if source_index == -1: # They hit escape return # Ask user which sink to link sinks = pulse.sink_list() current_default_name = pulse.server_info().default_sink_name for i, s in enumerate(sinks): if s.name == current_default_name: current_default = i if current_default == None: print("Couldn't find the default sink?") return sink_index, _ = rofi.select("Select destination sink", [s.description if s.description not in SINK_ALIASES else SINK_ALIASES[s.description] for s in sinks], select=current_default) if sink_index == -1: # They hit escape return # Link them! print("Linking: %s to %s" % (sources[source_index].name, sinks[sink_index].name)) loop_id = pulse.module_load('module-loopback', 'source="%s" sink="%s" latency_msec=1' % (sources[source_index].name, sinks[sink_index].name)) print("Loop id: %s" % loop_id) if loop_id > 100000: print("Invalid loop id") return # Find the newly created sink-input loop_sink_input = None for si in pulse.sink_input_list(): if si.owner_module == loop_id: print("Sink-input: %s" % si.index) loop_sink_input = si if loop_sink_input == None: print("Could not find newly created sink-input") return # Find the newly created source-output loop_source_output = None for so in pulse.source_output_list(): if so.owner_module == loop_id: print("Source-output: %s" % so.index) loop_source_output = so if loop_source_output == None: print("Could not find newly created source-output") return
class RofiSkyss: def __init__(self): self.rofi = Rofi() cache_dir = os.path.expanduser('~/.cache/rofi-skyss') self.stop_groups_cache = os.path.join(cache_dir, 'stop_groups.json') self.api_url = 'https://api.skyss.no/ws/mobile' self.api_auth = ('mobile', 'g7pEtkRF@') # ensure that the cache dir exists os.makedirs(cache_dir, exist_ok=True) def call_api(self, endpoint): url = '{}/{}'.format(self.api_url, endpoint) response = requests.get(url, auth=self.api_auth) if response.status_code == 200: return response.json() else: return False def get_stop_groups(self): if os.path.exists(self.stop_groups_cache): with open(self.stop_groups_cache) as f: return json.load(f) else: self.rofi.status('Downloading list of stop groups ...') stop_groups = self.call_api('stopgroups') if not stop_groups: self.rofi.error('Failed to download stop groups, sorry :(') sys.exit(1) with open(self.stop_groups_cache, 'w') as f: json.dump(stop_groups, f) self.rofi.close() return stop_groups def get_stops(self, identifier): self.rofi.status('Getting stops and passing times') stop_group = self.call_api('stopgroups/' + identifier) if not stop_group: self.rofi.error('Failed to get stops and passing times, sorry :(') sys.exit(1) routes = [] for group in stop_group['StopGroups']: for stop in group['Stops']: if 'RouteDirections' not in stop: self.rofi.error( 'The stop group is missing routes, sorry :(') sys.exit(1) for route in stop['RouteDirections']: routes.append(route) if not routes: self.rofi.error('The stop group is missing routes, sorry :(') sys.exit(1) route_names = [ '{} - {}'.format(route['PublicIdentifier'], route['DirectionName']) for route in routes ] index, status = self.rofi.select('Route: ', route_names) if status == 0: route = routes[index] times = [time['DisplayTime'] for time in route['PassingTimes']] self.rofi.select('Time: ', times, '<b>{}</b>'.format(route_names[index]), width=len(route_names[index]) * -1) def run(self): stop_groups = self.get_stop_groups()['StopGroups'] stop_group_names = [group['Description'] for group in stop_groups] index, status = self.rofi.select('Stop group: ', stop_group_names) if status == 0: stop_group = stop_groups[index] self.get_stops(stop_group['Identifier'])
def mupdf_open(): pdf_folder = "/home/piotr/pdf" os.chdir(pdf_folder) pdfs = os.listdir() index_o, key_o = r.select("choose a file to open:", pdfs) if key_o == -1: quit() else: pop(["mupdf", f"{pdfs[index_o]}"]) # ** D. EXECUTE if i3info == []: opts0 = ["[1] load", "[2] open pdf"] index0, key0 = r.select("MuPDF cache action:", opts0) if key0 == -1: quit() elif index0 == 0: mupdf_load() else: mupdf_open() else: opts_a = ["[1] load", "[2] open pdf", "[3] cache"] index_a, key_a = r.select("MuPDF cache action:", opts_a) if key_a == -1: quit() elif index_a == 0: mupdf_load() elif index_a == 1: mupdf_open()
# initialize rofi r = Rofi() password = r.text_entry('Master Password', rofi_args=['-password', '-lines', '0']) try: # load database kp = PyKeePass(args.database, password=password) except CredentialsIntegrityError as e: r.exit_with_error('Could not open database') options = [] for entry in kp.entries: options.append(entry.title) index, key = r.select('Name', options, key1=('Alt+1', "Type all"), key2=('Alt+2', "Type user"), key3=('Alt+3', "Type pass"), rofi_args=['-i', '-no-custom']) if(key == 0): # copy password cmd = "echo -n " + shlex.quote(kp.entries[index].password) + " | xclip -selection clipboard" subprocess.Popen(cmd,shell=True).communicate() Notification("Will be cleared in 15 seconds", kp.entries[index].title + " copied") subprocess.Popen("sleep 15 && echo -n "" | xclip -selection clipboard", shell=True).communicate() elif(key == 1): # type all subprocess.call(["sleep", "0.5"]) subprocess.call(["xdotool", "type", kp.entries[index].username]) subprocess.call(["xdotool", "key", "Tab"]) subprocess.call(["xdotool", "type", kp.entries[index].password]) elif(key == 2): # type user
class RofiSkyss: def __init__(self): self.rofi = Rofi() cache_dir = os.path.expanduser('~/.cache/rofi-skyss') self.stop_groups_cache = os.path.join(cache_dir, 'stop_groups.json') self.api_url = 'https://api.skyss.no/ws/mobile' self.api_auth = ('mobile', 'g7pEtkRF@') # ensure that the cache dir exists os.makedirs(cache_dir, exist_ok=True) def call_api(self, endpoint): url = '{}/{}'.format(self.api_url, endpoint) response = requests.get(url, auth=self.api_auth) if response.status_code == 200: return response.json() else: return False def get_stop_groups(self): if os.path.exists(self.stop_groups_cache): with open(self.stop_groups_cache) as f: return json.load(f) else: self.rofi.status('Downloading list of stop groups ...') stop_groups = self.call_api('stopgroups') if not stop_groups: self.rofi.error('Failed to download stop groups, sorry :(') sys.exit(1) with open(self.stop_groups_cache, 'w') as f: json.dump(stop_groups, f) self.rofi.close() return stop_groups def get_stops(self, identifier): self.rofi.status('Getting stops and passing times') stop_group = self.call_api('stopgroups/' + identifier) if not stop_group: self.rofi.error('Failed to get stops and passing times, sorry :(') sys.exit(1) routes = [] for group in stop_group['StopGroups']: for stop in group['Stops']: if 'RouteDirections' not in stop: self.rofi.error('The stop group is missing routes, sorry :(') sys.exit(1) for route in stop['RouteDirections']: routes.append(route) if not routes: self.rofi.error('The stop group is missing routes, sorry :(') sys.exit(1) route_names = ['{} - {}'.format(route['PublicIdentifier'], route['DirectionName']) for route in routes] index, status = self.rofi.select('Route: ', route_names) if status == 0: route = routes[index] times = [time['DisplayTime'] for time in route['PassingTimes']] self.rofi.select('Time: ', times, '<b>{}</b>'.format(route_names[index]), width=len(route_names[index]) * -1) def run(self): stop_groups = self.get_stop_groups()['StopGroups'] stop_group_names = [group['Description'] for group in stop_groups] index, status = self.rofi.select('Stop group: ', stop_group_names) if status == 0: stop_group = stop_groups[index] self.get_stops(stop_group['Identifier'])
def run(): config, config_dir = load_config() parser = argparse.ArgumentParser() parser.add_argument("-a", "--add-to-playlist", action="store_true", help="Add current track to a playlist") parser.add_argument("-l", "--like-current", action="store_true", help="Like current track") parser.add_argument("-st", "--search-track", action="store_true", help="Search for a track") parser.add_argument('-i', '--case-sensitive', action='store_true', help='Enable case sensitivity') parser.add_argument('-r', '--args', nargs=argparse.REMAINDER, help='Command line arguments for rofi. ' 'Separate each argument with a space.') args = parser.parse_args() rofi_args = args.args or [] if not args.case_sensitive: rofi_args.append('-i') rofi = Rofi() scope = "user-library-read user-read-currently-playing user-read-playback-state user-library-modify " \ "user-modify-playback-state playlist-modify-private playlist-read-private playlist-modify-public" sp = spotipy.Spotify(auth_manager=spotipy.oauth2.SpotifyOAuth(client_id=config['spotipy']['client_id'], client_secret=config['spotipy']['client_secret'], redirect_uri=config['spotipy']['redirect_uri'], scope=scope, cache_path=(config_dir + "/token"))) if args.add_to_playlist: track_id, track_meta = getCurrentTrack(sp) playlists = getPlaylists(sp, onlyEditable=True, username=config['spotify']['spotify_username']) playlists_names = [d['name'] for d in playlists['items']] index, key = rofi.select("To which playlist do you want to add " + track_meta + "? ", playlists_names, rofi_args=rofi_args) if key == -1: sys.exit(0) target_playlist_id = playlists['items'][index]['id'] result = addTrackToPlaylist(rofi, rofi_args, sp, config['spotify']['spotify_username'], target_playlist_id, playlists_names[index], track_id, track_meta) if not result == 0: if config['settings'].getboolean('show_add_to_playlist_popups'): rofi.status(track_meta + " added to " + playlists_names[index] + ".", rofi_args=rofi_args) time.sleep(2) rofi.close() sys.exit(0) if args.like_current: track_id, track_meta = getCurrentTrack(sp) sp.current_user_saved_tracks_add({track_id}) rofi.status(track_meta + " liked.", rofi_args=rofi_args) time.sleep(2) rofi.close() if args.search_track: trackquery = rofi.text_entry('Search for a track: ', rofi_args=rofi_args) results = sp.search(trackquery, limit=config['settings']['track_search_max_entries'], type="track") if not results['tracks']['items']: rofi.status("No tracks found.", rofi_args=rofi_args) time.sleep(2) rofi.close() else: tracks = [] for index, track in enumerate(results['tracks']['items']): tracks.append({'id': track['id'], 'artists': getArtistsTitleForID(sp, track['id'])[0], 'title': track['name'], 'uri': track['uri']}) rofi_tracks = [d['artists'] + " - " + d['title'] for d in tracks] index_track, key_track = rofi.select("Select a track: ", rofi_tracks, rofi_args=rofi_args) if key_track == -1: sys.exit(0) index_todo, key_todo = rofi.select(rofi_tracks[index_track] + ": ", ["Add to queue", "Add to playlist", "Play"], rofi_args=rofi_args) if key_todo == -1: sys.exit(0) if index_todo == 0: sp.add_to_queue(tracks[index_track]['id']) if config['settings'].getboolean('show_playback_popups'): rofi.status(rofi_tracks[index_track] + " added to queue.", rofi_args=rofi_args) time.sleep(2) rofi.close() if index_todo == 1: playlists = getPlaylists(sp, onlyEditable=True, username=config['spotify']['spotify_username']) playlists_names = [d['name'] for d in playlists['items']] index_playlist, key_playlist = rofi.select("To which playlist do you want to add " + rofi_tracks[index_track] + "? ", playlists_names, rofi_args=rofi_args) if key_playlist == -1: sys.exit(0) target_playlist_id = playlists['items'][index_playlist]['id'] result = addTrackToPlaylist(rofi, rofi_args, sp, config['spotify']['spotify_username'], target_playlist_id, playlists_names[index_playlist], tracks[index_track]['id'], rofi_tracks[index_track]) if not result == 0: if config['settings'].getboolean('show_add_to_playlist_popups'): rofi.status(rofi_tracks[index_track] + " added to " + playlists_names[index_playlist] + ".", rofi_args=rofi_args) time.sleep(2) rofi.close() if index_todo == 2: sp.start_playback(uris=[tracks[index_track]['uri']]) if config['settings'].getboolean('show_playback_popups'): rofi.status("Playing " + rofi_tracks[index_track] + ".", rofi_args=rofi_args) time.sleep(2) rofi.close() sys.exit(0) curr_track_id, curr_track_meta = getCurrentTrack(sp) index, key = rofi.select("Currently playing: " + curr_track_meta + " ", ["Add current song to playlist", "Like current track", "Search track"], rofi_args=rofi_args) if index == 0: rofi_args = args.args or [] rofi_args.append("-a") subprocess.run(["rofi-spotify", ", ".join(rofi_args)]) if index == 1: rofi_args = args.args or [] rofi_args.append("-l") subprocess.run(["rofi-spotify", ", ".join(rofi_args)]) if index == 2: rofi_args = args.args or [] rofi_args.append("-st") subprocess.run(["rofi-spotify", ", ".join(rofi_args)]) sys.exit(0)
if __name__ == "__main__": opt = get_options() spotify_auth_args = { "username": opt.username, "client_id": opt.client_id, "client_secret": opt.client_secret, } sp = get_spotify_client(**spotify_auth_args) r = Rofi() options = ["search", "clear queue"] index, key = r.select("select an option", options) if key == -1: sys.exit(1) if index == 1: clear_queue() sys.exit(1) name = r.text_entry("Enter the search term") artists = get_artists_name(name) selected_artist_idx, selected_artist_key = r.select( "Search results", [b.artist_name for b in artists]) if selected_artist_key == -1: sys.exit(1)
def delete_task(task_id): task_response = requests.post(url=url, json=generate_query_delete_todo(task_id), headers=headers).json() try: while True: all_tasks = [] get_tasks() index, key = r.select( prompt="Tasks", options=all_tasks, key1=("Alt+d", "delete task"), key2=("Alt+a", "add task"), rofi_args=["-i", "-no-custom", "-l", "15"], ) if key == 0: break elif key == 1: task_for_delete = all_tasks[index] pattern = '(^|\s)#([0-9]*)' task_id = re.search(pattern, task_for_delete).group(0).replace('#', '') del all_tasks[index] delete_task(task_id)