Ejemplo n.º 1
0
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"])
Ejemplo n.º 2
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
    ])
Ejemplo n.º 3
0
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]()
Ejemplo n.º 4
0
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])
Ejemplo n.º 5
0
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])
Ejemplo n.º 6
0
def main():
  rofi = Rofi()
  #if not os.path.exists(DATA_LOCATION):
  #  try:
  #    os.makedirs(os.path.dirname(DATA_LOCATION))
  #  except OSError:
  #    pass
#
  #  with open(DATA_LOCATION, "w+") as f:
  #    yaml.dump({}, stream=f)
#
  #with open(DATA_LOCATION) as f:
  #  data = yaml.load(f)
#
  ##validate data and whatnot
  #if "current_project" not in data:
  #  data["current_project"] = "Inbox"

  # Ask user what to add
  task_text = rofi.text_entry("Create new task")
  if task_text == None:
    return

  # Login to todoist
  with open(os.path.join(os.environ["HOME"],'.todoist.config.json')) as f:
    todoist_creds = json.load(f)
  #user = todoist.login_with_api_token(todoist_creds["token"])

  #project = user.get_project(data["current_project"])
  #if project == None:
  #  project = user.add_project(data["current_project"])

  api = todoist.TodoistAPI(todoist_creds["token"])
  api.quick.add(task_text)
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
def read_history_file(hist_file='/home/jack/.dotfiles/clipster/history'):
    try:
        with open(hist_file) as hist_f:
            data = (json.load(hist_f))
        return data
    except FileNotFoundError as exc:
        Rofi.error("[!] Missing History File [!]")
        raise SystemExit(1)
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
 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)
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
    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)
Ejemplo n.º 14
0
 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)
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
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]])
Ejemplo n.º 19
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()))
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
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()
Ejemplo n.º 22
0
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()
Ejemplo n.º 23
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 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]) 
Ejemplo n.º 25
0
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])
Ejemplo n.º 27
0
    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)
Ejemplo n.º 28
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()
Ejemplo n.º 29
0
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())
Ejemplo n.º 30
0
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)
Ejemplo n.º 31
0
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])
Ejemplo n.º 32
0
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")
Ejemplo n.º 33
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)
Ejemplo n.º 34
0
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}")
Ejemplo n.º 35
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")
Ejemplo n.º 36
0
#!/usr/bin/env python3

import subprocess
from os import linesep
import json
from rofi import Rofi
r = Rofi()
subprocess.run("whoami > /tmp/whoami", shell=True)
with open("/tmp/whoami", "r") as whoami:
    user = whoami.read().replace(linesep, "")
subprocess.run("rm /tmp/whoami".split(" "))
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=")):
Ejemplo n.º 37
0
def rofi(data):
    # https://github.com/bcbnz/python-rofi
    r = Rofi()
    r.text_entry('What is your name?')
Ejemplo n.º 38
0
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
Ejemplo n.º 39
0
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'])