summaryrefslogtreecommitdiff
path: root/monitor-menu.py
blob: 5c4ee3a733da8345e67b39e2bf771474772cbfe7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3

'''
monitor-menu.py
Usage:
    monitor-menu.py [options]
    monitor-menu.py [options] <profile>

Options:
    --loglevel=LOGLEVEL  Set the log level [default: info]
'''

from os.path import expanduser

import dialog
import docopt
import json
import logging
import subprocess

d = dialog.Dialog()

class MonitorMenu():
    def __init__(self, config_file='~/.config/monitor-profiles.json'):
        with open(expanduser(config_file)) as fd:
            self.profiles = json.load(fd)

    def run(self, profile_idx=None):
        choices = []

        if profile_idx is None:
            i = 0
            for p in self.profiles:
                choices.append((str(i), p['name']))
                i += 1

            code, profile_idx = d.menu('Select the profile you want to use.', choices=choices)

            if code == d.ESC or code == d.CANCEL:
                return

        profile = self.profiles[int(profile_idx)]

        # We build the command line starting from just "xrandr" and adding arguments.
        xrandr_cmd = ['xrandr']
        feh_cmd = ['feh', '--bg-fill']

        try:
            xrandr_cmd += profile['xrandr-opts']
        except KeyError:
            pass

        for monitor in profile['monitors']:
            xrandr_cmd.extend(monitor['xrandr-opts'])

            if monitor.get('background') is not None:
                feh_cmd.append(monitor['background']);

        logging.debug("Executing: %s", xrandr_cmd)
        subprocess.run(xrandr_cmd)
        logging.debug("Executing: %s", feh_cmd)
        subprocess.run(feh_cmd)


def main(argv=None):
    args = docopt.docopt(__doc__, version='1', argv=argv)

    menu = MonitorMenu()

    numeric_level = getattr(logging, args["--loglevel"].upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError(f"invalid log level: {args['--loglevel']}")
    logging.basicConfig(level=numeric_level)

    try:
        if '<profile>' in args and args['<profile>'] is not None:
            menu.run(int(args['<profile>']))
        else:
            menu.run()

    except ValueError as e:
        raise docopt.DocoptExit(str(e))

if __name__ == '__main__':
    main()