Debian Codegraph @

DisplayCAL/util_mac.py

raw
1 """macOS utility functions for AppleScript, system info, and Terminal settings."""
2
3 import os
4 import re
5 import subprocess as sp
6 from time import sleep
7
8
9 def get_osascript_args(applescript):
10 """Return arguments ready to use for osascript."""
11 if isinstance(applescript, str):
12 applescript = applescript.splitlines()
13 args = []
14 for line in applescript:
15 args.extend(["-e", line])
16 return args
17
18
19 def get_osascript_args_or_run(applescript, run=True):
20 """Return arguments ready to use for osascript or run the AppleScript."""
21 if run:
22 return osascript(applescript)
23 return get_osascript_args(applescript)
24
25
26 def mac_app_activate(delay=0, mac_app_name="Finder"):
27 """Activate (show & bring to front) an application if it is running."""
28 applescript = [
29 f'if app "{mac_app_name}" is running then',
30 # Use 'run script' to prevent the app activating upon script
31 # compilation even if not running
32 rf'run script "tell app \"{mac_app_name}\" to activate"',
33 "end if",
34 ]
35 if delay:
36 sleep(delay)
37 return osascript(applescript)
38
39
40 def mac_terminal_do_script(script=None, do=True):
41 """Run a script in Terminal."""
42 applescript = [
43 'if app "Terminal" is running then',
44 'tell app "Terminal"',
45 "activate",
46 'do script ""', # Terminal is already running, open a new
47 # window to make sure it is not blocked by
48 # another process
49 "end tell",
50 "else",
51 'tell app "Terminal" to activate', # Terminal is not yet running,
52 # launch & use first window
53 "end if",
54 ]
55 if script:
56 applescript.extend(
57 [
58 'tell app "Terminal"',
59 'do script "{}" in first window'.format(script.replace('"', '\\"')),
60 "end tell",
61 ]
62 )
63 return get_osascript_args_or_run(applescript, script and do)
64
65
66 def mac_terminal_set_colors(
67 background="black", cursor="gray", text="gray", text_bold="gray", do=True
68 ):
69 """Set Terminal colors."""
70 applescript = [
71 'tell app "Terminal"',
72 f'set background color of first window to "{background}"',
73 f'set cursor color of first window to "{cursor}"',
74 f'set normal text color of first window to "{text}"',
75 f'set bold text color of first window to "{text_bold}"',
76 "end tell",
77 ]
78 return get_osascript_args_or_run(applescript, do)
79
80
81 def osascript(applescript):
82 """Run AppleScript with the 'osascript' command.
83
84 Return osascript's exit code.
85
86 """
87 args = get_osascript_args(applescript)
88 p = sp.Popen(
89 ["osascript", *args], # noqa: S607
90 stdin=sp.PIPE,
91 stdout=sp.PIPE,
92 stderr=sp.PIPE,
93 )
94 output, errors = p.communicate()
95 retcode = p.wait()
96 return retcode, output, errors
97
98
99 def get_model_code(serial=None):
100 """Given a mac serial number, return the model code.
101
102 If serial is None, this mac's serial number is used.
103
104 """
105 if not serial:
106 serial = get_serial()
107 if serial:
108 if "serial" in serial.lower():
109 # Workaround for machines with dummy serial numbers
110 return None
111 if len(serial) in (12, 13) and serial.startswith("S"):
112 # Remove prefix from scanned codes
113 serial = serial[1:]
114 if len(serial) in (11, 12):
115 return serial[8:]
116 return None
117
118
119 def get_serial():
120 """Return this mac's serial number."""
121 try:
122 p = sp.Popen(
123 ["ioreg", "-c", "IOPlatformExpertDevice", "-d", "2"], # noqa: S607
124 stdin=sp.PIPE,
125 stdout=sp.PIPE,
126 stderr=sp.PIPE,
127 )
128 output, errors = p.communicate()
129 except Exception:
130 return None
131 match = re.search(r'"IOPlatformSerialNumber"\s*=\s*"([^"]*)"', output.decode())
132 if match:
133 return match.group(1)
134 return None
135
136
137 def get_model_id():
138 """Return this mac's model id."""
139 try:
140 p = sp.Popen(
141 ["sysctl", "hw.model"], # noqa: S607
142 stdin=sp.PIPE,
143 stdout=sp.PIPE,
144 stderr=sp.PIPE,
145 )
146 output, errors = p.communicate()
147 except BaseException:
148 return None
149 if isinstance(output, bytes):
150 output = output.decode("utf-8")
151 return "".join(output).split(None, 1)[-1].strip()
152
153
154 def get_machine_attributes(model_id=None):
155 """Given a mac model ID, return the machine attributes.
156
157 If model_code is None, this mac's model code is used.
158
159 """
160 if not model_id:
161 model_id = get_model_id()
162 if not model_id:
163 return None
164 pf = "/System/Library/PrivateFrameworks"
165 f = ".framework/Versions/A/Resources/English.lproj"
166 sk = f"{pf}/ServerKit{f}/XSMachineAttributes"
167 si = f"{pf}/ServerInformation{f}/SIMachineAttributes"
168 # Mac OS X 10.8 or newer use "ServerInformation",
169 # Mac OS X 10.6/10.7 "ServerKit"
170 filename = si if os.path.isfile(f"{si}.plist") else sk
171 try:
172 p = sp.Popen(
173 ["defaults", "read", filename, model_id], # noqa: S607
174 stdin=sp.PIPE,
175 stdout=sp.PIPE,
176 stderr=sp.PIPE,
177 )
178 output, errors = p.communicate()
179 except Exception:
180 return None
181 attrs = {}
182 for line in output.splitlines():
183 match = re.search(r'(\w+)\s*=\s*"?(.*?)"?\s*;', line.decode())
184 if match:
185 # Need to double unescape backslashes
186 attrs[match.group(1)] = (
187 match.group(2).decode("string_escape").decode("string_escape")
188 )
189 return attrs