about summary refs log tree commit diff
path: root/pkgs/profpatsch/xrandr.nix
blob: 02dc564a10422373cce901479843945414643e55 (plain) (blame)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
{ pkgs, getBins, writeExecline, runExeclineLocal, toNetstringKeyVal, ... }:

let
  inherit (pkgs) lib;
  bins = getBins pkgs.nodejs [ "node" ]
      // getBins pkgs.coreutils [ "echo" "ln" "mkdir" ]
      // getBins pkgs.dhall-json [ "json-to-dhall" ]
      // getBins pkgs.xorg.xrandr [ "xrandr" ]
      ;

  writeNodejs = {
    name,
    # an attrset of node dependency name to source directory;
    # will be made into a node_modules directory and set as `NODE_PATH`.
    dependencies
  }:
    let
      node_modules = runExeclineLocal "${name}-node_modules" {
        stdin = toNetstringKeyVal dependencies;
      } [
        "importas" "out" "out"
        "if" [ bins.mkdir "$out" ]
        "forstdin" "-o" "0" "-Ed" "" "dep"
        "multidefine" "-d" "" "$dep" [ "name" "source" ]
        "if" [ bins.echo "\${name} - \${source}" ]
        bins.ln "-sT" "\${source}" "\${out}/\${name}"
      ];

    in pkgs.writers.makeScriptWriter {
      interpreter = writeExecline "nodejs-with-modules" {} [
        "export" "NODE_PATH" node_modules
        bins.node "$@"
      ];
    } name;

  dhall-typecheck = {
    name,
    dhallType,
    recordsLoose ? false
  }:
    writeExecline name {} ([
      bins.json-to-dhall
    ]
    ++ lib.optional recordsLoose "--records-loose"
    ++ [
      dhallType
    ]);

  parse = writeNodejs {
    name = "xrandr-parse";
    dependencies = {
      xrandr-parse =
        (pkgs.fetchFromGitHub {
          owner = "lionep";
          repo = "xrandr-parse";
          rev = "a35bfd625c1b0834aa94f136cf8282b25624b3e6";
          sha256 = "0c8mfsvgg76ia2i9gsgdwy567xzba5274xpj8si37yah5qpp8dkm";
        });
    };
  } ''
    var parse = require('xrandr-parse');
    var exec = require('child_process').exec;

    exec('xrandr', function (err, stdout) {
        var query = parse(stdout);
        console.log(JSON.stringify(query, null, 2));
    });
  '';

  type = pkgs.writeText "type.dhall" ''
    let Resolution = {
      height: Text,
      width: Text,
      rate: Double
    }
    let Monitor =
      < NotConnected : {}
      | Connected : {
          connected: Bool,
          modes: List Resolution,
          index: Natural,
          native: Resolution
      }
      | Active : {
          modes: List Resolution,
          index: Natural,
          native: Resolution,
          current: Resolution
      } >

    in List {
      mapKey: Text,
      mapValue: Monitor
    }
  '';


  two-monitor-setup = writeExecline "test" {} [
    "backtick" "-Ei" "json" [ parse ]
    "if" [
      "pipeline" [ bins.echo "$json" ]
      "redirfd" "-w" "1" "/dev/null"
      (dhall-typecheck {
        name = "typecheck-xrandr";
        dhallType = type;
        recordsLoose = true;
      })
    ]
    "pipeline" [ bins.echo "$json" ]
    two-monitor-setup-script
  ];


  two-monitor-setup-script = pkgs.writers.writePython3 "xrandr-two-monitor-setup" {} ''
    import json
    import sys
    import os

    # TODO: use netencode for input
    monitors = json.load(sys.stdin)

    connected = {
      k: v for k, v in monitors.items()
      if 'connected' in v and v['connected']
    }

    if 'eDP1' not in connected:
        print("could not find eDP1 (laptop screen)", file=sys.stderr)
        sys.exit(1)

    if len(connected) != 2:
        print("only know how to configure two monitors")
        sys.exit(1)

    eDP1 = connected['eDP1']

    # laptop screen is active
    assert 'current' in eDP1

    # how far the laptop screen should be offset to end
    # at the bottom of the monitor
    h_offset = 0
    for k, v in connected.items():
        if k == 'eDP1':
            assert 'current' in v

        else:
            h = int(v['native']['height'])
            h_offset = h - int(eDP1['native']['height'])
            external_monitor = (k, v)
            # can’t handle bigger laptop screens atm
            assert h_offset >= 0

    xrandr_command = [
        "--verbose",

        "--output", external_monitor[0],
        "--primary",
        "--mode", "{}x{}".format(
            external_monitor[1]['native']['width'],
            external_monitor[1]['native']['height']
        ),
        "--pos", "{}x{}".format(
            # offset by the laptop size to the right
            eDP1['native']['width'],
            # monitor starts at 0
            0
        ),

        "--output", "eDP1",
        "--mode", "{}x{}".format(
            eDP1['native']['width'],
            eDP1['native']['height'],
        ),
        "--pos", "{}x{}".format(
            # laptop is the leftmost screen
            0,
            # but offset to the bottom so that it always aligns on the left bottom
            h_offset
        ),
    ]

    os.execvp(
        "${bins.xrandr}",
        ["${bins.xrandr}"]
        + xrandr_command
    )
  '';

in {
  inherit
    parse
    two-monitor-setup
    ;
}