Exemple #1
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 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)
Exemple #3
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()
Exemple #4
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)
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]) 
Exemple #6
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)
Exemple #7
0
def rofi(data):
    # https://github.com/bcbnz/python-rofi
    r = Rofi()
    r.text_entry('What is your name?')
Exemple #8
0
import subprocess
import argparse
import shlex
import os

from notify import Notification
from rofi import Rofi

# initialize argument parser
parser = argparse.ArgumentParser(description='Rofi frontend for keepassxc interaction')
parser.add_argument('--database', help='Path to your keepass database', required=True)
args = parser.parse_args()

# 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
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)
Exemple #10
0
            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)

        elif key == 2:
            title = r.text_entry("Enter task title", rofi_args=["-l", "0"])

            if title:
                categories = r.text_entry(
                    "Enter categories separated by comma",
                    rofi_args=["-l", "0"])
                categories_list = categories.replace(" ", "").split(",")
                create_task(title, categories_list)

        else:
            break

except KeyError:
    print("KeyError")
Exemple #11
0
    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)

    print(artists[selected_artist_idx].artist_name)

    artist_albums = get_artist_albums(artists[selected_artist_idx].spotify_uri)

    selected_album_idx, selected_album_key = r.select(
        "Choose the album", [c.album_name for c in artist_albums])

    if selected_album_key == -1:
Exemple #12
0
import os
import pyperclip

from rofi import Rofi

r = Rofi()

is_open = True
results = []

try:
    while is_open:
      word_to_translate = r.text_entry("Word:",  rofi_args=["-p"])
      word_result = os.popen('~/.dotfiles/rofi/scripts/translate/trans -b :fr {}'.format(word_to_translate)).read()

      if len(word_result.rstrip()) == 0:
        word_result = os.popen('~/.dotfiles/rofi/scripts/translate/trans -e bing -b :fr {}'.format(word_to_translate)).read()

      results.append(word_result.rstrip().replace('\n', ' '))
      
      index, key = r.select(
          prompt="Results",
          options=results,
          key1=("Alt+d", "delete task"),
          key2=("Alt+a", "add task"),
          rofi_args=["-i", "-no-custom"],
      )

      if key == 0:
        word_select = results[index]
        pyperclip.copy(word_select)
Exemple #13
0
        rofi_args=["-i", "-no-custom", "-l", "15"],
    )

    if key == 0:
        r.error(notes["notes"][index]["description"])

    elif key == 1:
        del notes["notes"][index]

        with open(args.file, "w") as f:
            json.dump(notes, f, indent=2)

        r.error("Note deleted.")

    elif key == 2:
        name = r.text_entry("Enter note name", rofi_args=["-l", "0"])

        if name:
            desc = r.text_entry("Enter node description",
                                rofi_args=["-l", "0"])
            new_note = {"name": name, "description": desc}
            notes["notes"].append(new_note)

            with open(args.file, "w") as f:
                json.dump(notes, f, indent=2)

            r.error("Note added.")

    else:
        break
Exemple #14
0
class Spotlight:
    def __init__(self):
        self.rofi = Rofi()

    def multifuncitonal(self, argument):
        def reformat_whitespaces(self, search):
            search = search.split(" ")
            while "" in search:
                search.remove("")
            del search[0]
            return search

        try:
            argument
        except:
            search = self.rofi.text_entry("function")
        else:
            search = argument + " " + self.rofi.text_entry("function")

        selector = search[0]
        if selector == "w":
            search = reformat_whitespaces(self, search)
            search = " ".join(search)
            self.websearch(search)
        elif selector == "s":
            search = reformat_whitespaces(self, search)
            search = " ".join(search)
            print(search)
            self.search(search)
        elif selector == "e":
            self.exit()
        elif selector == "x":
            search = reformat_whitespaces(self, search)
            self.execute(search)
        else:
            self.rofi.error(
                'Not a valid command. Type "s" for search, "!" for websearch, "e" for exit or "x" for executing a command.'
            )

    def websearch(self, search):
        subprocess.Popen(["firefox", "-search", search],
                         stdout=subprocess.PIPE)

    def search(self, search):
        def find(self, pattern, path):
            result = []
            for root, dirs, files in os.walk(path):
                for name in files:
                    if fnmatch.fnmatch(name, pattern):
                        result.append(os.path.join(root, name))
            return result

        output = find(self, search, os.path.expanduser("~"))
        index, key = self.rofi.select("out", output)
        self.open(output[index])

    def open(self, file):
        subprocess.Popen(["xdg-open", file], stdout=subprocess.PIPE)

    def exit(self):
        options = [
            "lock", "exit", "suspend", "hibernate", "reboot", "shutdown"
        ]
        index, key = self.rofi.select("exit", options)
        command = ""
        if index == 0:
            command = "sh i3exit.sh lock"
        elif index == 1:
            command = "sh i3exit.sh logout"
        elif index == 2:
            command = "sh i3exit.sh suspend"
        elif index == 3:
            command = "sh i3exit.sh hibernate"
        elif index == 4:
            command = "sh i3exit.sh reboot"
        elif index == 5:
            command = "sh i3exit.sh poweroff"
        subprocess.Popen(command.split(" "), stdout=subprocess.PIPE)

    def execute(self, command):
        proc = subprocess.Popen(command, stdout=subprocess.PIPE)
        output, errors = proc.communicate()
        output = output.decode("utf-8").split("\n")
        self.rofi.select("out", output)
Exemple #15
0
if __name__ == "__main__":
    r = Rofi()
    option = r.select(prompt="action: ", options=options).selection

    if option == "work":
        cards = client.get_list(ACTION_LIST).list_cards()
        random.shuffle(cards)
        selected_card = r.select(options=cards).selection
        if selected_card is not None:
            choice = r.select(options=('show', 'open', "select")).selection
            if choice is not None:
                if choice == "show":
                    info = more_info(selected_card)
                    r.show(info)
                    choice, key = r.select(options=('open', "select"))
                if choice == "open":
                    webbrowser.open(selected_card.url, new=1, autoraise=True)
                if choice == "select":
                    selected_card.change_list(PROCESS_LIST)
                    r.show("card has moved to PROCESS_LIST")

    if option == "inbox":
        text = r.text_entry(prompt="short description: ")
        client.get_list(INBOX_LIST).add_card(text)
        r.show("card added")

    if option == "notes":
        text = r.text_entry(prompt="text: ")
        client.get_list(NOTES_LIST).add_card(text)
        r.show("card added")
Exemple #16
0
def search_menu():
    from spotify_search import play_search
    r = Rofi()

    play_search(r.text_entry("Play Song"))