/
notify_osx.py
203 lines (159 loc) · 5.25 KB
/
notify_osx.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
"""
Notify macOS.
Copyright (c) 2013 - 2016 Isaac Muse <isaacmuse@gmail.com>
License: MIT
"""
import subprocess
import os
# ```
# import ctypes
# import ctypes.util
# ```
import sys
import platform
__all__ = ("get_notify", "alert", "setup", "destroy")
PY3 = (3, 0) <= sys.version_info < (4, 0)
if PY3:
binary_type = bytes # noqa
else:
binary_type = str
# ```
# appkit = ctypes.cdll.LoadLibrary(ctypes.util.find_library('AppKit'))
# cf = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))
# objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
#
# kCFStringEncodingUTF8 = 0x08000100
#
# cf.CFStringCreateWithCString.restype = ctypes.c_void_p
# cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]
#
# objc.objc_getClass.restype = ctypes.c_void_p
# objc.sel_registerName.restype = ctypes.c_void_p
# objc.objc_msgSend.restype = ctypes.c_void_p
# objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
#
# NSSound = ctypes.c_void_p(objc.objc_getClass('NSSound'))
# NSAutoreleasePool = ctypes.c_void_p(objc.objc_getClass('NSAutoreleasePool'))
#
#
# def _nsstring(string):
# """Return an NSString object."""
#
# return ctypes.c_void_p(cf.CFStringCreateWithCString(None, string.encode('utf8'), kCFStringEncodingUTF8))
#
#
# def _callmethod(obj, method, *args, **kwargs):
# """Call the ObjC method."""
#
# cast_return = kwargs.get("cast_return", ctypes.c_void_p)
# return cast_return(objc.objc_msgSend(obj, objc.sel_registerName(method), *args))
# ```
def _is_ver_okay():
"""See if version is > 10.8."""
try:
return float(platform.mac_ver()[0].split('.')[:2]) >= 10.9
except Exception:
return False
class Options:
"""Notification options."""
notify = None
sender = "com.apple.Terminal"
terminal_notifier = None
app_name = ""
icon = None
sound = None
@classmethod
def clear(cls):
"""Clear."""
cls.notify = None
cls.sender = "com.apple.Terminal"
cls.terminal_notifier = None
cls.app_name = ""
cls.icon = None
cls.sound = None
def _alert(sound=None):
"""Play an alert sound for the OS."""
if sound is None and Options.sound is not None:
sound = Options.sound
try:
if sound is not None:
subprocess.call(["afplay", sound])
# ```
# pool = _callmethod(_callmethod(NSAutoreleasePool, "alloc"), "init")
# snd = _nsstring(sound if sound is not None else "Glass")
# soundobj = _callmethod(NSSound, "soundNamed:", snd)
# _callmethod(soundobj, "play")
# _callmethod(pool, "drain")
# del pool
# ```
except Exception:
pass
def alert():
"""Alert."""
_alert()
@staticmethod
def notify_osx_fallback(title, message, sound, fallback):
"""The macOS notifications fallback (just sound)."""
# Fallback to wxPython notification
fallback(title, message, sound)
@staticmethod
def notify_osx_call(title, message, sound, fallback):
"""Notifications for macOS."""
try:
if Options.terminal_notifier is None or not os.path.exists(Options.terminal_notifier):
raise ValueError("Specified terminal notifier does not appear to be valid")
# Show Notification here
params = [Options.terminal_notifier, "-title", Options.app_name, "-timeout", "5"]
if message is not None:
params += ["-message", message]
if title is not None:
params += ["-subtitle", title]
if Options.sender is not None:
params += ["-sender", Options.sender]
if Options.icon is not None:
params += ["-appIcon", Options.icon]
subprocess.Popen(params)
if sound:
# Play sound if desired
alert()
except Exception:
# Fallback notification
fallback(title, message, sound)
def setup(app_name, icon, **kwargs):
"""Setup."""
term_notify = None
sender = None
term_notify = kwargs.get('term_notify')
sender = kwargs.get('sender')
sound = kwargs.get('sound')
if sound is not None and os.path.exists(sound):
Options.sound = sound
notify_icon = icon
if term_notify is not None and isinstance(term_notify, binary_type):
term_notify = term_notify.decode('utf-8')
if sender is not None and isinstance(sender, binary_type):
sender = sender.decode('utf-8')
if _is_ver_okay():
notify_icon = None
elif notify_icon is not None and isinstance(notify_icon, binary_type):
notify_icon = notify_icon.decode('utf-8')
Options.app_name = app_name
try:
if term_notify is None or not os.path.exists(term_notify):
raise ValueError("Terminal notifier does not appear to be available")
Options.terminal_notifier = term_notify
if sender is not None:
Options.sender = sender
if notify_icon is not None and os.path.exists(notify_icon):
Options.icon = notify_icon
Options.notify = notify_osx_call
except Exception:
pass
def destroy():
"""Destroy."""
Options.clear()
Options.notify = notify_osx_fallback
def get_notify():
"""Get notification."""
return Options.notify
Options.notify = notify_osx_fallback