/
FinderSidebarEditor.py
246 lines (202 loc) · 8.74 KB
/
FinderSidebarEditor.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
from platform import mac_ver
from Cocoa import NSURL
from CoreFoundation import CFPreferencesAppSynchronize
from CoreFoundation import CFURLCreateWithString
from CoreFoundation import kCFAllocatorDefault
from Foundation import NSBundle
from LaunchServices import kLSSharedFileListFavoriteItems
from objc import loadBundleFunctions, initFrameworkWrapper, pathForFramework
os_version = int(mac_ver()[0].split('.')[1])
if os_version > 10:
SFL_bundle = NSBundle.bundleWithIdentifier_(
'com.apple.coreservices.SharedFileList'
)
functions = [
('LSSharedFileListCreate', b'^{OpaqueLSSharedFileListRef=}^{__CFAllocator=}^{__CFString=}@'),
('LSSharedFileListCopySnapshot', b'^{__CFArray=}^{OpaqueLSSharedFileListRef=}o^I'),
('LSSharedFileListItemCopyDisplayName', b'^{__CFString=}^{OpaqueLSSharedFileListItemRef=}'),
('LSSharedFileListItemResolve', b'i^{OpaqueLSSharedFileListItemRef=}Io^^{__CFURL=}o^{FSRef=[80C]}'),
('LSSharedFileListItemMove', b'i^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}^{OpaqueLSSharedFileListItemRef=}'),
('LSSharedFileListItemRemove', b'i^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}'),
('LSSharedFileListRemoveAllItems', b'i^{OpaqueLSSharedFileListRef=}'),
('LSSharedFileListInsertItemURL', b'^{OpaqueLSSharedFileListItemRef=}^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}^{__CFString=}^{OpaqueIconRef=}^{__CFURL=}^{__CFDictionary=}^{__CFArray=}'),
('kLSSharedFileListItemBeforeFirst', b'^{OpaqueLSSharedFileListItemRef=}')
]
loadBundleFunctions(SFL_bundle, globals(), functions)
from LaunchServices import LSSharedFileListItemCopyResolvedURL
else:
from LaunchServices import kLSSharedFileListItemBeforeFirst
from LaunchServices import LSSharedFileListCreate
from LaunchServices import LSSharedFileListCopySnapshot
from LaunchServices import LSSharedFileListItemCopyDisplayName
from LaunchServices import LSSharedFileListItemResolve
from LaunchServices import LSSharedFileListItemMove
from LaunchServices import LSSharedFileListItemRemove
from LaunchServices import LSSharedFileListRemoveAllItems
from LaunchServices import LSSharedFileListInsertItemURL
# Shoutout to Mike Lynn for the mount_share function below, allowing for the
# scripting of mounting network shares. See his blog post for more details:
# http://michaellynn.github.io/2015/08/08/learn-you-a-better-pyobjc-bridgesupport-signature/
class attrdict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
NetFS = attrdict()
# Can cheat and provide 'None' for the identifier, it'll just use
# frameworkPath instead scan_classes=False means only add the
# contents of this Framework
NetFS_bundle = initFrameworkWrapper(
'NetFS', frameworkIdentifier=None,
frameworkPath=pathForFramework('NetFS.framework'), globals=NetFS,
scan_classes=False
)
def mount_share(share_path):
# Mounts a share at /Volumes, returns the mount point or raises an error
sh_url = CFURLCreateWithString(None, share_path, None)
# Set UI to reduced interaction
open_options = {NetFS.kNAUIOptionKey: NetFS.kNAUIOptionNoUI}
# Allow mounting sub-directories of root shares
mount_options = {NetFS.kNetFSAllowSubMountsKey: True}
# Mount!
result, output = NetFS.NetFSMountURLSync(
sh_url, None, None, None, open_options, mount_options, None
)
# Check if it worked
if result != 0:
raise Exception('Error mounting url "%s": %s' % (share_path, output))
# Return the mount path
return str(output[0])
# https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
# Fix NetFSMountURLSync signature
del NetFS['NetFSMountURLSync']
loadBundleFunctions(
NetFS_bundle, NetFS, [('NetFSMountURLSync', b'i@@@@@@o^@')]
)
class FinderSidebar:
"""
Finder Sidebar instance for modifying favorites entries for logged in user.
Attributes:
sflRef (LSSharedFileList): Reference to sfl object containing Finder
favorites data.
snapshot (tuple): Snapshot of Finder sfl object containing readable
entries for each favorite.
favorites (dict): Dictionary containing name: uri pairs for
each favorite.
"""
def __init__(self):
self.sflRef = LSSharedFileListCreate(
kCFAllocatorDefault, kLSSharedFileListFavoriteItems, None
)
self.snapshot = LSSharedFileListCopySnapshot(self.sflRef, None)
self.favorites = dict()
self.update()
def update(self):
"""
Updates snapshot and favorites attributes.
"""
self.favorites = dict()
self.snapshot = LSSharedFileListCopySnapshot(self.sflRef, None)
for item in self.snapshot[0]:
name = LSSharedFileListItemCopyDisplayName(item)
path = ""
if name not in ["AirDrop", "All My Files", "iCloud"]:
path = LSSharedFileListItemResolve(item, 0, None, None)[1]
self.favorites[name] = path
@staticmethod
def synchronize():
"""
Synchronizes CF prefs for sidebarlists identifier.
"""
CFPreferencesAppSynchronize("com.apple.sidebarlists")
def move(self, to_mv, after):
"""
Moves sidebar list item to position immediately other sidebar
list item.
Args:
to_mv (str): Name of sidebar list item to move.
after (str): Name of sidebar list item to move "to_mv" after.
"""
if to_mv not in self.favorites.keys() or \
after not in self.favorites.keys() or to_mv == after:
return
for item in self.snapshot[0]:
name = LSSharedFileListItemCopyDisplayName(item)
if name == after:
after = item
elif name == to_mv:
to_mv = item
LSSharedFileListItemMove(self.sflRef, to_mv, after)
self.synchronize()
self.update()
def remove(self, to_rm):
"""
Removes sidebar list item.
Args:
to_rm (str): Name of sidebar list item to remove.
"""
for item in self.snapshot[0]:
name = LSSharedFileListItemCopyDisplayName(item)
if to_rm.upper() == name.upper():
LSSharedFileListItemRemove(self.sflRef, item)
self.synchronize()
self.update()
def remove_all(self):
"""
Removes all sidebar list items.
"""
LSSharedFileListRemoveAllItems(self.sflRef)
self.synchronize()
self.update()
def remove_by_path(self, path):
"""
Removes sidebar list item.
Args:
path (str): Path of sidebar list item to remove.
"""
comparison_path = f'file://{path}/'.upper()
for item in self.snapshot[0]:
sidebar_item = LSSharedFileListItemCopyResolvedURL(item, 0, None)
if comparison_path == str(sidebar_item[0]).upper():
LSSharedFileListItemRemove(self.sflRef, item)
self.synchronize()
self.update()
def add(self, to_add, uri="file://localhost"):
"""
Append item to sidebar list items.
Args:
:param to_add: Path to item to append to sidebar list.
Keyword Args:
:param uri: URI of server where item resides if not on localhost.
"""
if uri.startswith("afp") or uri.startswith("smb"):
path = "%s%s" % (uri, to_add)
to_add = mount_share(path)
item = NSURL.alloc().initFileURLWithPath_(to_add)
LSSharedFileListInsertItemURL(
self.sflRef, kLSSharedFileListItemBeforeFirst,
None, None, item, None, None
)
self.synchronize()
self.update()
def get_index_from_name(self, name):
"""
Gets index of sidebar list item identified by name.
Args:
name (str): Display name to identfy sidebar list item by.
Returns:
Index of sidebar list item identified by name
"""
for index, item in enumerate(self.snapshot[0]):
found_name = LSSharedFileListItemCopyDisplayName(item)
if name == found_name:
return index
def get_name_from_index(self, index):
"""
Gets name of sidebar list item identified by index.
Args:
index (str): Index to identify sidebar list item by.
Returns:
Name of sidebar list item identified by index.
"""
if index > len(self.snapshot[0]):
index = -1
return LSSharedFileListItemCopyDisplayName(self.snapshot[0][index])