-
Notifications
You must be signed in to change notification settings - Fork 12
/
MailFlow.py
301 lines (253 loc) · 11.6 KB
/
MailFlow.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
from AppKit import NSAlternateKeyMask, NSApplication, NSBundle, NSLog, \
NSMenuItem, NSUserDefaults
import objc
import re
def Category(classname):
return objc.Category(objc.lookUpClass(classname))
def Class(classname):
return objc.lookUpClass(classname)
def flow(text, width = 77):
quote, indent = re.match(r'(>+ ?|)(\s*)', text, re.UNICODE).groups()
prefix = len(quote)
if text[prefix:] == u'-- ':
return [text]
text = text.rstrip(u' ')
if not quote:
if indent.startswith(u' ') or text.startswith(u'From '):
text = u' ' + text
if indent or len(text) <= width:
return [text]
matches = re.finditer(r'\S+\s*(?=\S|$)', text[prefix:], re.UNICODE)
breaks, lines = [match.end() + prefix for match in matches], []
while True:
for index, cursor in enumerate(breaks[1:]):
if len(text[:cursor].expandtabs()) >= width:
cursor = breaks[index]
break
else:
lines.append(text)
return lines
lines.append(text[:cursor] + u' ')
if not quote and text[cursor:].startswith(u'From '):
text, cursor = u' ' + text[cursor:], cursor - 1
else:
text, cursor = quote + text[cursor:], cursor - prefix
breaks = [offset - cursor for offset in breaks[index + 1:]]
def swizzle(classname, selector):
def decorator(function):
cls = objc.lookUpClass(classname)
try:
old = cls.instanceMethodForSelector_(selector)
if old.isClassMethod:
old = cls.methodForSelector_(selector)
except:
return None
def wrapper(self, *args, **kwargs):
return function(self, old, *args, **kwargs)
new = objc.selector(wrapper, selector = old.selector,
signature = old.signature,
isClassMethod = old.isClassMethod)
objc.classAddMethod(cls, selector, new)
return wrapper
return decorator
class ComposeViewController(Category('ComposeViewController')):
@swizzle('ComposeViewController', b'_finishLoadingEditor')
def _finishLoadingEditor(self, old):
result = old(self)
if self.messageType() not in [1, 2, 3, 8]:
return result
view = self.composeWebView()
document = view.mainFrame().DOMDocument()
view.contentElement().removeStrayLinefeeds()
blockquotes = document.getElementsByTagName_('BLOCKQUOTE')
for index in range(blockquotes.length()):
if blockquotes.item_(index):
blockquotes.item_(index).removeStrayLinefeeds()
if self.messageType() in [1, 2, 8]:
view.moveToBeginningOfDocument_(None)
view.moveToEndOfParagraphAndModifySelection_(None)
view.moveForwardAndModifySelection_(None)
item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
'Decrease', 'changeQuoteLevel:', '')
item.setTag_(-1)
view.changeQuoteLevel_(item)
if self._fixAttribution:
attribution = view.selectedDOMRange().stringValue()
attribution = attribution.split(u',', 2)[-1].lstrip()
if view.isAutomaticTextReplacementEnabled():
view.setAutomaticTextReplacementEnabled_(False)
view.insertText_(attribution)
view.setAutomaticTextReplacementEnabled_(True)
else:
view.insertText_(attribution)
signature = document.getElementById_('AppleMailSignature')
if signature:
domrange = document.createRange()
domrange.selectNode_(signature)
view.setSelectedDOMRange_affinity_(domrange, 0)
view.moveUp_(None)
else:
view.moveToEndOfDocument_(None)
view.insertParagraphSeparator_(None)
if self.messageType() == 3:
for index in range(blockquotes.length()):
blockquote = blockquotes.item_(index)
if blockquote.quoteLevel() == 1:
blockquote.parentNode().insertBefore__(
document.createElement_('BR'), blockquote)
view.insertParagraphSeparator_(None)
view.undoManager().removeAllActions()
self.setHasUserMadeChanges_(False)
self.backEnd().setHasChanges_(False)
return result
@swizzle('ComposeViewController', b'show')
def show(self, old):
result = old(self)
if self.messageType() in [1, 2, 8]:
view = self.composeWebView()
document = view.mainFrame().DOMDocument()
signature = document.getElementById_('AppleMailSignature')
if signature:
domrange = document.createRange()
domrange.selectNode_(signature)
view.setSelectedDOMRange_affinity_(domrange, 0)
view.moveUp_(None)
else:
view.moveToEndOfDocument_(None)
return result
class EditingMessageWebView(Category('EditingMessageWebView')):
@swizzle('EditingMessageWebView', b'decreaseIndentation:')
def decreaseIndentation_(self, original, sender, indent = 2):
if self.contentElement().className() != 'ApplePlainTextBody':
return original(self, sender)
self.undoManager().beginUndoGrouping()
affinity = self.selectionAffinity()
selection = self.selectedDOMRange()
self.moveToBeginningOfParagraph_(None)
if selection.collapsed():
for _ in range(indent):
self.moveForwardAndModifySelection_(None)
text = self.selectedDOMRange().stringValue() or ''
if re.match(u'[ \xa0]{%d}' % indent, text, re.UNICODE):
self.deleteBackward_(None)
else:
while selection.compareBoundaryPoints__(1, # START_TO_END
self.selectedDOMRange()) > 0:
for _ in range(indent):
self.moveForwardAndModifySelection_(None)
text = self.selectedDOMRange().stringValue() or ''
if re.match(u'[ \xa0]{%d}' % indent, text, re.UNICODE):
self.deleteBackward_(None)
else:
self.moveBackward_(None)
self.moveToEndOfParagraph_(None)
self.moveForward_(None)
self.setSelectedDOMRange_affinity_(selection, affinity)
self.undoManager().endUndoGrouping()
@swizzle('EditingMessageWebView', b'increaseIndentation:')
def increaseIndentation_(self, original, sender, indent = 2):
if self.contentElement().className() != 'ApplePlainTextBody':
return original(self, sender)
self.undoManager().beginUndoGrouping()
affinity = self.selectionAffinity()
selection = self.selectedDOMRange()
if selection.collapsed():
position = self.selectedRange().location
self.moveToBeginningOfParagraph_(None)
position -= self.selectedRange().location
self.insertText_(indent * u' ')
for _ in range(position):
self.moveForward_(None)
else:
self.moveToBeginningOfParagraph_(None)
while selection.compareBoundaryPoints__(1, # START_TO_END
self.selectedDOMRange()) > 0:
self.moveToEndOfParagraphAndModifySelection_(None)
if not self.selectedDOMRange().collapsed():
self.moveToBeginningOfParagraph_(None)
self.insertText_(indent * u' ')
self.moveToEndOfParagraph_(None)
self.moveForward_(None)
self.setSelectedDOMRange_affinity_(selection, affinity)
self.undoManager().endUndoGrouping()
class MCMessage(Category('MCMessage')):
@swizzle('MCMessage', b'forwardedMessagePrefixWithSpacer:')
def forwardedMessagePrefixWithSpacer_(self, old, *args):
return u''
class MCMessageGenerator(Category('MCMessageGenerator')):
@swizzle('MCMessageGenerator', b'_encodeDataForMimePart:withPartData:')
def _encodeDataForMimePart_withPartData_(self, old, part, data):
if part.type() != 'text' or part.subtype() != 'plain':
return old(self, part, data)
text = bytes(data.objectForKey_(part))
if any(len(line) > 998 for line in text.splitlines()):
return old(self, part, data)
try:
text.decode('ascii')
part.setContentTransferEncoding_('7bit')
except UnicodeDecodeError:
part.setContentTransferEncoding_('8bit')
return True
@swizzle('MCMessageGenerator',
b'_newPlainTextPartWithAttributedString:partData:')
def _newPlainTextPartWithAttributedString_partData_(self, old, *args):
event = NSApplication.sharedApplication().currentEvent()
result = old(self, *args)
width = self._flowWidth
if not result or width <= 0:
return result
if event and event.modifierFlags() & NSAlternateKeyMask:
return result
charset = result.bodyParameterForKey_('charset') or 'utf-8'
data = args[1].objectForKey_(result)
lines = bytes(data).decode(charset).split('\n')
lines = [line for text in lines for line in flow(text, width)]
encoded = u'\n'.join(lines).encode(charset)
try:
data.setData_(buffer(encoded))
except:
data.setData_(encoded)
result.setBodyParameter_forKey_('yes', 'delsp')
result.setBodyParameter_forKey_('flowed', 'format')
return result
class MCMimePart(Category('MCMimePart')):
@swizzle('MCMimePart', b'_decodeText')
def _decodeText(self, old):
result = old(self)
if result is None:
return result
if result.startswith(u' '):
result = u' ' + result[1:]
return result.replace(u'<BR> ', u'<BR> ')
class MessageViewController(Category('MessageViewController')):
@swizzle('MessageViewController', b'forward:')
def forward_(self, old, *args):
event = NSApplication.sharedApplication().currentEvent()
if event and event.modifierFlags() & NSAlternateKeyMask:
return old(self, *args)
return self._messageViewer().forwardAsAttachment_(*args)
class MessageViewer(Category('MessageViewer')):
@swizzle('MessageViewer', b'forwardMessage:')
def forwardMessage_(self, old, *args):
event = NSApplication.sharedApplication().currentEvent()
if event and event.modifierFlags() & NSAlternateKeyMask:
return old(self, *args)
return self.forwardAsAttachment_(*args)
class SingleMessageViewer(Category('SingleMessageViewer')):
@swizzle('SingleMessageViewer', b'forwardMessage:')
def forwardMessage_(self, old, *args):
event = NSApplication.sharedApplication().currentEvent()
if event and event.modifierFlags() & NSAlternateKeyMask:
return old(self, *args)
return self.forwardAsAttachment_(*args)
class MailFlow(Class('MVMailBundle')):
@classmethod
def initialize(self):
bundle = NSBundle.bundleWithIdentifier_('uk.me.cdw.MailFlow')
self.registerBundle()
defaults = NSUserDefaults.standardUserDefaults()
defaults = defaults.dictionaryForKey_('MailFlow') or {}
ComposeViewController._fixAttribution = defaults.get('FixAttribution', True)
MCMessageGenerator._flowWidth = int(defaults.get('FlowWidth', 76))
version = bundle.objectForInfoDictionaryKey_('CFBundleVersion')
NSLog('Loaded MailFlow %s' % version)