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 __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)
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() # Get name of sink sink_name = rofi.text_entry("Create sink") if sink_name == None: return sink_description = "(Virtual) " + sink_name sink_name = sink_name.replace(" ", "") # Make it sink_id = pulse.module_load('module-null-sink', 'sink_name=%s ' % sink_name) print("Sink id: %s" % sink_id) # Set props and whatnot to sane values subprocess.run([ "pacmd", "update-sink-proplist", sink_name, 'device.description="%s"' % sink_description ]) subprocess.run([ "pacmd", "update-source-proplist", sink_name + '.monitor', 'device.description="%s"' % sink_description ])
def invoke_dir_man(default_dir): dir_path = default_dir r = Rofi(lines=10, rofi_args=["-font", "Inconsolata Bold 12"]) ls_dir = listdirs_full(dir_path) num, key = display_rofi(ls_dir, r) while key != 0 or (key == 0 and num == 0): if key == -1: return -1 if key == 2 or num == 0: dir_path = os.path.abspath(os.path.join(dir_path, "../")) elif key == 1: curr_name = os.path.basename(ls_dir[num]) dir_path = os.path.join(dir_path, curr_name) ls_dir = listdirs_full(dir_path) num, key = display_rofi(ls_dir, r) if key == 0: if num != 1: curr_name = os.path.basename(ls_dir[num]) dir_path = os.path.join(dir_path, curr_name) return dir_path
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 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() 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 _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 __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 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)
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(): 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 parse_template(template_path): # get the template data from the template file template_data = yaml.load(open(template_path), Loader=Loader) # get the global config info from the top-level global_vars.yml file global_data = yaml.load(open(os.path.join(install_path, 'global_vars.yml')), Loader=Loader) # create a template to parse the template_data and global_data into template = jinja2.Template(template_data['content']) # if there is an "args" object in template data, iterate it. if 'args' in template_data: args = dict() # create a rofi instance r = Rofi() # iterate args, request them, then add to args for templating for listed_arg in template_data['args']: entry = r.text_entry(listed_arg, message=generate_vars_list( template_data['args'], args)) # if we cancelled the entry, return emptry string if entry == None: return "" # if we got a valid entry, continue args[listed_arg] = entry # combine args and global configurations into one object to pass template_fields = dict() template_fields['global'] = global_data template_fields['args'] = args # parse and return finished template return template.render(template_fields)
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/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")
import dmenu import notify2 from notify2 import URGENCY_NORMAL, URGENCY_CRITICAL from pyfzf.pyfzf import FzfPrompt from rofi import Rofi from pystdlib import shell_cmd URGENCY_NORMAL = notify2.URGENCY_NORMAL URGENCY_CRITICAL = notify2.URGENCY_CRITICAL notify2.init(os.path.basename(__file__)) is_interactive = sys.stdin.isatty() in_xsession = os.environ.get("DISPLAY") ro = Rofi() def notify(header, msg, urgency=URGENCY_NORMAL, timeout=3000): n = notify2.Notification(header, msg) n.set_urgency(urgency) n.set_timeout(timeout) n.show() def do_log(msg, header, urgency, timeout): if in_xsession: notify(msg, header, urgency, timeout) else: print(f"{header} {msg}")
def rofi(data): # https://github.com/bcbnz/python-rofi r = Rofi() r.text_entry('What is your name?')
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 jiramenu(): user = None project = None auth = None config = None debug = False r = Rofi() issues = [] rofi_list = [] def __init__(self, config, debug): self.config = config self.r.status("starting jiramenu") try: self.auth = JIRA(config['JIRA']['url'], basic_auth=(config['JIRA']['user'], config['JIRA']['password'])) except Exception as error: self.r.exit_with_error(str(error)) self.debug = debug def log(self, text): if not self.debug: return print(text) def show(self, user): self.user = user self.project = self.config['JIRA']['project'] if user: self.log(f"show issues for: {self.user}") query = self.config['JIRA']['query'] if user: query += f" and assignee = '{user}'" if self.project: query += f" and project = '{self.project}'" self.log(f"Query: {query}") if not self.issues: self.issues = self.auth.search_issues(query) self.boards = self.auth.boards() if not self.rofi_list: if user: self.rofi_list.append("> all") else: self.rofi_list.append("> mine") self.issues.sort(key=lambda x: x.fields.status.id, reverse=False) for issue in self.issues: labels = '' if len(issue.fields.labels): labels = '(' for idx, label in enumerate(issue.fields.labels): labels += label if idx != len(issue.fields.labels) -1: labels += ', ' labels += ')' issuetext = '' issueassignee = '' initials = ' ' if issue.fields.assignee: issueassignee = issue.fields.assignee.displayName initials = ''.join([x[0].upper() for x in issueassignee.split(' ')]) if issue.fields.status.id == str(3): #id:3 = Work in Progress issuetext = '{WIP}' issuekey = issue.key issuekey = "{:<9}".format(issuekey) status = "{:<24}".format(issue.fields.status.name) issueassignee = "{:<20}".format(issueassignee) issuetext += f'{issuekey} {status} {initials} {labels} {issue.fields.summary}' self.rofi_list.append(issuetext) # print active query plus number of results on top index, key = self.r.select(f'{query}[{len(self.rofi_list)}]', self.rofi_list, rofi_args=['-i'], width=100) del key if index < 0: exit(1) if index == 0: self.issues = [] self.rofi_list = [] if user: self.show(None) else: self.show(self.config['JIRA']['user']) return self.show_details(index, user) def addComment(self, ticket_number): comment = self.r.text_entry("Content of the comment:") if comment: # replace @user with [~user] comment = re.sub(r"@(\w+)", r"[~\1]", comment) self.auth.add_comment(ticket_number, comment) def show_details(self, index, user): inputIndex = index # ticket_number = re.match("IMP-([1-9]|[1-9][0-9])+", self.rofi_list[index]).group(0) issue = self.issues[index-1] ticket_number = issue.key summary = '-'.join(issue.fields.summary.split(' ')) branch_name= ticket_number + '-' + summary[:33] self.log("[details]" + ticket_number) issue_description = issue.fields.description output = [] output.append("> show in browser") output.append("") output.append(f"> copy branch ({branch_name})") output.append("") output.append("Status: " + self.issues[index - 1].fields.status.name) # output.append("Description: " + issue_description) description = [] if issue_description: description = issue_description.split('\n') for item in description: output.append(item) if self.auth.comments(ticket_number): comment_ids = self.auth.comments(ticket_number) for comment_id in comment_ids: self.log("comment_id: " + str(comment_id)) commentauthor = self.auth.comment(ticket_number, comment_id).author.displayName + ':' output.append(commentauthor) commenttext = self.auth.comment(ticket_number, comment_id).body commenttext = commenttext.split('\n') for line in commenttext: output.append(line) else: output.append("no comments") output.append("") output.append("> add comment") output.append("") if self.issues[index - 1].fields.assignee: output.append("assigned to: " + self.issues[index - 1].fields.assignee.displayName) else: output.append("> assign to me") # if self.issues[index - 1].fields.status.id == str(3): # WIP # output.append(">>in review") # else: # output.append(">>start progress") output.append("") output.append('< back') index, key = self.r.select(ticket_number, output, width=100) if index in [-1, len(output) - 1]: self.show(user) return # if index == len(output) - 2: # move issue to 'In Review' # self.log("[status]"+self.issues[inputIndex - 1].fields.status.name) # self.log("[transitions]") # self.log(self.auth.transitions(ticket_number)) # if self.issues[inputIndex - 1].fields.status.id == str(3): # WIP # for trans in self.auth.transitions(ticket_number): # if trans['name'] == "in Review": # self.log("move to 'in Review'") # self.auth.transition_issue(ticket_number, trans['id']) # # else: # for trans in self.auth.transitions(ticket_number): # if trans['name'] == "Start Progress": # self.log("move to 'Start Progress'") # self.auth.transition_issue(ticket_number, trans['id']) # self.show_details(inputIndex, user) # return if index == len(output) - 4: # add comment self.log("[addComment]") self.addComment(ticket_number) self.show_details(inputIndex, user) return if index == len(output) - 3: # assign to me self.log("[assign to me]") self.auth.assign_issue(ticket_number, self.config['JIRA']['user']) self.show_details(inputIndex, user) return if index == 2: pyperclip.copy(branch_name) return # if index in [3, 4]: # Popen(['notify-send', issue_description, '-t', '30000']) # self.show_details(inputIndex, user) # return # show in browser self.log("[show in browser]") uri = self.auth.issue(ticket_number).permalink() Popen(['nohup', self.config['JIRA']['browser'], uri], stdout=DEVNULL, stderr=DEVNULL)
from datetime import datetime as dt from rofi import Rofi # import psutil # from subprocess import check_output # ** VARIABLES: i3 i3 = i3ipc.Connection() i3info = i3.get_tree().find_classed("MuPDF") i3ws = i3.get_tree().find_focused().workspace().num # ** VARIABLES: cache_dir cache_dir = "/home/piotr/.cache/mupdf-cache" # ** VARIABLES: rofi theme r = Rofi(rofi_args=["-theme", "/home/piotr/.config/rofi/i3on-window.rasi"]) # ** FUNCTIONS # ** 0. HELPER: NOTIFY def notify(urgency, message): pop(["notify-send", "-u", urgency, "MuPDF cache:", message]) return # ** A. MUPDF CACHE def mupdf_cache(): # ** a0. check if cache_dir exists, create if not, and go there if not os.path.isdir(cache_dir): os.mkdir(cache_dir) os.chdir(cache_dir)
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)
from subprocess import check_output as out from subprocess import Popen as pop import re from rofi import Rofi # >> VARIABLES #r = Rofi(rofi_args=['-theme', '/home/piotr/.config/rofi/mytheme.rasi']) try: theme = '/home/piotr/.config/rofi/' + str(sys.argv[1]) except IndexError: theme = '/home/piotr/.config/rofi/mytheme.rasi' try: monitor = str(sys.argv[2]) except IndexError: monitor = '-2' r = Rofi(rofi_args=['-theme', theme, '-monitor', monitor]) unbashify_re = re.compile(r'\x1b\[(1m|22m|24m|4m)') kill_head_re = re.compile(r'^.*\n.*\n*.*\n*.*\n\[ (.*) -> (.*) \]\n*', re.UNICODE) to_lang_re = re.compile(r' \>([a-z]*)') from_lang_re = re.compile(r' \<([a-z]*)') # >> QUERY def validator(s): return (s, None) if not any(char.isdigit() for char in s) else (None, ' ') query = r.generic_entry(' TRANSLATE: ', validator)
#!/usr/bin/env python3 import os import sys import io import clipboard from rofi import Rofi import requests r = Rofi(lines=12,width=50,location=0,rofi_args=["-columns", "2"]) def show_recieve_dialog(file): options = ["Save", "Save As", "Ignore"] selection,key = r.select("File {} Recieved! Choose an action".format(file["name"]), options) if key != 0: return 0 return options[selection] def path_dialog_loop(file, dir): options = ["Save Here", "Go Up"] local_dirs = filter(lambda x: os.path.isdir(os.path.join(dir, x)), os.listdir(dir)) options.extend(list(local_dirs)) selection,key = r.select("Save file {}".format(file["name"]), options) if key != 0: return dir if selection == 0: return dir if selection == 1: return path_dialog_loop(file, os.path.join(dir,'../')) else: