-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaplhid.py
219 lines (186 loc) · 7.58 KB
/
aplhid.py
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env python3
#
# alphid (apple hid)
#
# Copyright 2013 Canonical Ltd.
# Original author: Alberto Milone <[email protected]>
# Modified by: Vladimir Yerilov <[email protected]>
#
# Script to switch between 2 modes of Fn keys on Apple keyboards that make most sense. Mode strings are set in switch_mode function, adjust if necessary.
#
# Usage:
# place in /usr/local/bin
# run alphid media|func|auto|query
# media: media keys as designed by Apple
# func: standard Fn keys
# auto: switches to another mode (there are only 2 anyway)
# query: checks which version is currently active and writes
# "media", "func" or "unknown" to the
# standard output
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import os
import sys
import subprocess
import itertools
import time
class Switcher(object):
def __init__(self):
self._hid_config_path = '/etc/modprobe.d/hid_apple.conf'
def _get_mode(self):
try:
settings = open(self._hid_config_path, 'r')
except:
return 'unknown'
config = settings.read().strip()
if 'fnmode=1' in config:
return 'media'
elif 'fnmode=2' in config:
return 'func'
else:
return 'disabled'
def print_mode(self):
mode = self._get_mode()
if mode == 'unknown':
return False
print('%s' % mode)
return True
def _write_mode(self, hid_text):
# Write the settings to the file
settings = open(self._hid_config_path, 'w')
settings.write(hid_text)
settings.close()
def switch_mode(self, mode):
media_string = '''options hid_apple iso_layout=0 swap_opt_cmd=1 fnmode=1'''
func_string = '''options hid_apple iso_layout=0 swap_opt_cmd=1 fnmode=2'''
match mode:
case 'media':
hid_text = media_string
sys.stdout.write('Info: selecting the %s mode\n' % (mode))
self._write_mode(hid_text)
self.reload_module()
self._update_initramfs(mode)
case 'func':
hid_text = func_string
sys.stdout.write('Info: selecting the %s mode\n' % (mode))
self._write_mode(hid_text)
self.reload_module()
self._update_initramfs(mode)
case 'auto':
mode = self._get_mode()
if mode == 'media':
mode = 'func'
hid_text = func_string
sys.stdout.write('Info: selecting the %s mode\n' % (mode))
self._write_mode(hid_text)
self.reload_module()
self._update_initramfs(mode)
else:
mode = 'media'
hid_text = media_string
sys.stdout.write('Info: selecting the %s mode\n' % (mode))
self._write_mode(hid_text)
self.reload_module()
self._update_initramfs(mode)
case _:
mode = self._get_mode()
if mode == 'media':
mode = 'func'
hid_text = func_string
sys.stdout.write('Info: selecting the %s mode\n' % (mode))
self._write_mode(hid_text)
self.reload_module()
else:
mode = 'media'
hid_text = media_string
sys.stdout.write('Info: selecting the %s mode\n' % (mode))
self._write_mode(hid_text)
self.reload_module()
return True
def reload_module(self):
subprocess.Popen(['rmmod', 'hid_apple'])
time.sleep(1)
subprocess.Popen(['modprobe', 'hid_apple'])
time.sleep(1)
def _show_spinner(self, proc, spinner):
print('Updating the initramfs. Please wait for the operation to complete:')
# Check if process is still running
while proc.poll()==None:
try:
# Print the spinner
sys.stdout.write(spinner.__next__())
sys.stdout.flush()
sys.stdout.write('\b')
time.sleep(0.2)
except BrokenPipeError:
return False
print('Done')
# Print out the output
output=proc.communicate()[0]
print("You might need to run sbupdate or similar tool to refresh your unified kernel image")
def _update_initramfs(self, mode):
# Create spinner to give feed back on the
# operation
initramfs = input("Rebuild initramfs to make %s mode permanent? (yes/no): " % (mode))
if initramfs.lower() == 'yes' or initramfs.lower() == 'y':
spinner = itertools.cycle ( ['-', '/', '|', '\\'])
if os.path.isfile('/bin/dracut'):
proc = subprocess.Popen(['dracut', '-f', '--regenerate-all'],stdout=subprocess.PIPE)
self._show_spinner(proc, spinner)
elif os.path.isfile('/bin/mkinitcpio'):
proc = subprocess.Popen(['mkinitcpio', '-P'],stdout=subprocess.PIPE)
self._show_spinner(proc, spinner)
elif os.path.isfile('/sbin/update-initramfs'):
proc = subprocess.Popen(['update-initramfs', '-u', '-k', 'all'],stdout=subprocess.PIPE)
self._show_spinner(proc, spinner)
else:
print("Unsupported distro, please update initramfs manually")
else:
print("This mode is valid only until the next boot")
def check_root():
if not os.geteuid() == 0:
sys.stderr.write("This operation requires root privileges\n")
exit(1)
def handle_query_error():
sys.stderr.write("Error: no mode can be found\n")
exit(1)
def usage():
sys.stderr.write("Usage: %s media|func|auto\n" % (sys.argv[0]))
if __name__ == '__main__':
try:
arg = sys.argv[1]
except IndexError:
arg = None
#if len(sys.argv[1:]) != 1:
# usage()
# exit(1)
switcher = Switcher()
if arg in ['media', 'func', 'auto', None]:
check_root()
switcher.switch_mode(arg)
elif arg == 'query':
if not switcher.print_mode():
handle_query_error()
else:
usage()
sys.exit(1)
exit(0)