summaryrefslogtreecommitdiffstats
path: root/bin/dpmsmouse
blob: 229b9e65372c3bda043cfe84ec09a6d1b75ee86c (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
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
#!/bin/sh

set -eu

DEFAULT_POLL_TIME=5

debug=0

err()
{
	local fmt="${1}"
	shift 1

	printf "Error: ${fmt}\n" "${@}" 1>&2
	return 0
}

dbg()
{
	local fmt="${1}"
	shift 1

	case "${debug}" in '1')
		printf "DEBUG: ${fmt}\n" "${@}" 1>&2
	esac

	return 0
}

enable_devices()
{
	local device=

	dbg 'Enabling devices:'
	for device in "${@}"; do
		dbg '  %s' "${device}"
		xinput --enable "${device}" || :
	done
}

disable_devices()
{
	local device=

	dbg 'Disabling devices:'
	for device in "${@}"; do
		dbg '  %s' "${device}"
		xinput --disable "${device}" || :
	done
}

poll()
{
	local poll_time=${1}
	shift 1
	local displays=
	local prev_state=
	local displays_on=
	local displays_off=
	local display=
	local status=
	local dpms=
	local state=

	displays="$(printf '%s ' \
		/sys/devices/pci????:??/????:??:??.?/drm/card*/card*-*/ \
		/sys/devices/pci????:??/????:??:??.?/????:??:??.?/drm/card*/card*-*/)"

	prev_state=''
	while :; do
		displays_on=0
		displays_off=0
		for display in ${displays}; do
			[ -f "${display}/status" ] || continue
			read status 0<"${display}/status"
			case "${status}" in 'disconnected')
				continue
			esac
			read dpms 0<"${display}/dpms"
			case "${dpms}" in
				'On')  displays_on=1;;
				'Off') displays_off=1;;
			esac
		done

		state='enable_devices'
		case ${displays_on} in 0)
			case ${displays_off} in 1)
				state='disable_devices'
			esac
		esac

		case "${state}" in
			"${prev_state}");;
			*)
				"${state}" "${@}"
				prev_state="${state}"
				;;
		esac

		sleep ${poll_time}
	done
}

usage()
{
	printf 'Usage: %s [<options>] <device> [<device> ...]\n' "${0}"
	printf '\n'
	printf 'Options:\n'
	printf '  -p <secs>  Poll at least every <secs> seconds\n'
	printf '  -d         Enable debugging output\n'
}

main()
{
	local move_win=
	local opt=
	local dir=
	local dx=
	local dy=
	local cur_dt=
	local new_dt=

	poll_time=${DEFAULT_POLL_TIME}

	while getopts 'p:d' opt "${@}"; do
		case "${opt}" in
			'p')
				case "${OPTARG}" in *[!0-9]* | '')
					usage 1>&2
					return 1
				esac
				poll_time="${OPTARG}"
				;;
			'd') debug=1;;
			'?')
				usage 1>&2
				return 1
				;;
		esac
	done
	shift $((${OPTIND} - 1))

	if [ ${#} -lt 1 ]; then
		usage 1>&2
		return 1
	fi

	poll ${poll_time} "${@}"

	return 0
}

main "${@}"