Source

scripts / i3-workspace-menu.py

Full commit
#!/usr/bin/env python
# coding: utf-8
"""
i3wm workspace menu
~~~~~~~~~~~~~~~~~~~

:author: Andrey Mikhaylenko, 2013
:license: GPL3

Displays a menu with workspace names; switches to given name.

Requirements:

* *i3* (incl. `i3-msg`)
* *dmenu*

"""
import json
import subprocess


def get_active_workspaces():
    "Returns a list of currently active workspaces"
    result = subprocess.check_output(['i3-msg', '-t', 'get_workspaces'])
    workspaces = json.loads(result.decode())
    names = [w['name'] for w in workspaces]
    return names


def show_menu(options):
    "Displays dmenu with given options, returns selected item"
    data = '\n'.join(options)
    p = subprocess.Popen(['dmenu', '-b', '-f'],
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    out, err = p.communicate(input=data.encode())
    name = out.strip()
    return name


def switch_workspace(name):
    "Switches i3 to given workspace (it is expected to be prefixed with a number)"
    print('switching to "{0}"'.format(name.decode()))
    subprocess.call(['i3-msg', 'workspace', 'number', name], stdout=subprocess.PIPE)


def main():
    names = get_active_workspaces()
    name = show_menu(names)
    switch_workspace(name)


if __name__ == '__main__':
    main()