#!/usr/bin/python

#####CONFIGURATION#####
screen="eDP1"
inputnames=[
        "NTRG0001:01 1B96:1B05 Pen",
        "TOUCHPAD"
        ]

#####PROGRAM CODE#####
#Do not change unless you know what you are doing!

xinput="/usr/bin/xinput"
xrandr="/usr/bin/xrandr"

import re
import subprocess
from time import sleep

oldstate = ""
state = ""
while True:
    oldstate = state
    state = subprocess.check_output([xrandr, "-q"])
    if state != oldstate:
        for input_ in inputnames:
            pattern = re.compile(".*" + input_ + ".* *\tid=([0-9]+)\t.* pointer .*")
            output = subprocess.check_output([xinput, "list"]).decode("unicode_escape")
            matches = re.findall(pattern, output)

            # Find the display we are interested to move (= the laptop panel)
            POSSIBLE_OUTPUT = [ "DSI1", "eDP1", "LVDS", "LVDS1" ]
            for out in POSSIBLE_OUTPUT:
                match = re.search("^" + out +  r" connected .* \(.*\) (?P<rotation>.*) .*",
                                  state,
                                  re.MULTILINE
                                 )
                if match:
                    screen = out
                    break

            for id in matches:
                subprocess.call([xinput, "map-to-output", id, screen])

    sleep(1)
