2 # Copyright 2009 James Bunton <jamesbunton@fastmail.fm>
3 # Licensed for distribution under the GPL version 2, check COPYING for details
12 from Foundation
import *
14 from PyObjCTools
import AppHelper
19 class PlaylistModel(NSObject
):
20 outlineView
= objc
.IBOutlet()
22 def awakeFromNib(self
):
25 self
.outlineView
.setDataSource_(self
)
26 self
.outlineView
.setEnabled_(False)
28 def setPlaylists(self
, playlists
):
30 self
.playlists
= playlists
31 for playlist
in self
.playlists
:
32 if playlist
.parent
is None:
33 self
.root
.append(playlist
)
34 self
.outlineView
.reloadData()
35 self
.outlineView
.expandItem_expandChildren_(None, True)
37 def outlineView_child_ofItem_(self
, _
, childIndex
, playlist
):
39 return self
.root
[childIndex
]
41 return playlist
.children
[childIndex
]
43 def outlineView_isItemExpandable_(self
, _
, playlist
):
47 return len(playlist
.children
) > 0
49 def outlineView_numberOfChildrenOfItem_(self
, _
, playlist
):
53 return len(playlist
.children
)
55 def outlineView_objectValueForTableColumn_byItem_(self
, _
, col
, playlist
):
58 col
= col
.identifier()
61 selected
= NSApp
.delegate().playlists()
62 return playlist
.pid
in selected
64 return NSImage
.imageNamed_("playlist-" + playlist
.ptype
)
68 def outlineView_setObjectValue_forTableColumn_byItem_(self
, _
, v
, col
, playlist
):
71 col
= col
.identifier()
76 NSApp
.delegate().setPlaylist_selected_(playlist
.pid
, v
)
79 class FolderModel(NSObject
):
80 window
= objc
.IBOutlet()
81 folderPopup
= objc
.IBOutlet()
83 def loadFolders_(self
, folders
):
84 self
.folderPopup
.addItemsWithTitles_(folders
)
86 self
.folderPopup
.selectItemAtIndex_(2)
92 def doSelectFolder_(self
, sender
):
93 currentIndex
= self
.folderPopup
.indexOfSelectedItem()
95 self
.lastIndex
= currentIndex
96 NSApp
.delegate().setFolder_(self
.folderPopup
.titleOfSelectedItem())
98 panel
= NSOpenPanel
.openPanel()
99 panel
.setCanChooseFiles_(False)
100 panel
.setCanChooseDirectories_(True)
101 panel
.setCanCreateDirectories_(True)
102 panel
.setAllowsMultipleSelection_(False)
103 panel
.beginSheetForDirectory_file_types_modalForWindow_modalDelegate_didEndSelector_contextInfo_(
104 None, None, [], self
.window
, self
, self
.selectFolderEnd_returnCode_contextInfo_
, None)
106 @objc.signature("v@:@ii")
107 def selectFolderEnd_returnCode_contextInfo_(self
, panel
, ret
, _
):
108 if ret
== NSOKButton
:
109 assert len(panel
.filenames()) == 1
110 folder
= panel
.filenames()[0]
111 NSApp
.delegate().setFolder_(folder
)
112 self
.folderPopup
.insertItemWithTitle_atIndex_(folder
, 2)
113 self
.folderPopup
.selectItemAtIndex_(2)
115 self
.folderPopup
.selectItemAtIndex_(self
.lastIndex
)
118 class NotiPodController(NSObject
):
119 window
= objc
.IBOutlet()
121 loadingSheet
= objc
.IBOutlet()
122 loadingLabel
= objc
.IBOutlet()
123 loadingIndicator
= objc
.IBOutlet()
125 previewWindow
= objc
.IBOutlet()
126 previewText
= objc
.IBOutlet()
128 playlistModel
= objc
.IBOutlet()
129 folderModel
= objc
.IBOutlet()
132 def awakeFromNib(self
):
133 self
.runningGenerator
= False
136 def applicationWillFinishLaunching_(self
, _
):
139 def applicationDidFinishLaunching_(self
, _
):
143 for target
in self
.targets
:
144 folders
.append(target
["folder"])
145 self
.folderModel
.loadFolders_(folders
)
147 self
.library
= libnotipod
.ITunesLibrary
.alloc().init()
149 self
.playlistModel
.setPlaylists(self
.library
.get_playlists())
152 self
.runGenerator(lambda: self
.library
.load_(None), finish
, fail
)
154 def applicationWillTerminate_(self
, _
):
155 self
.prefs().synchronize()
157 def applicationShouldTerminateAfterLastWindowClosed_(self
, _
):
162 def runGenerator(self
, func
, finish
, fail
):
163 assert not self
.runningGenerator
164 self
.runningGenerator
= True
165 self
.loadingIndicator
.startAnimation_(self
)
166 NSApp
.beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(self
.loadingSheet
, self
.window
, None, None, None)
167 arg
= (func(), finish
, fail
)
168 self
.performSelectorInBackground_withObject_(self
.runGeneratorThread
, arg
)
170 def runGeneratorThread(self
, (gen
, finish
, fail
)):
171 pool
= NSAutoreleasePool
.alloc().init()
174 if not self
.runningGenerator
:
176 self
.loadingLabel
.performSelectorOnMainThread_withObject_waitUntilDone_(
177 self
.loadingLabel
.setStringValue_
, msg
, True)
179 NSRunAlertPanel("Error!", str(e
), "Ok", None, None)
180 traceback
.print_exc()
182 self
.performSelectorOnMainThread_withObject_waitUntilDone_(
183 self
.stopGenerator
, finish
, True)
184 self
.runningGenerator
= False
186 def stopGenerator(self
, finish
):
187 self
.runningGenerator
= False
188 NSApp
.endSheet_(self
.loadingSheet
)
189 self
.loadingSheet
.orderOut_(self
)
190 self
.loadingIndicator
.stopAnimation_(self
)
195 def doCancel_(self
, sender
):
196 self
.runningGenerator
= False
198 def getDestFolder(self
):
199 target
= self
.getCurrentTarget()
201 NSRunAlertPanel("Error!", "You must choose a folder first!", "Ok", None, None)
203 folder
= target
["folder"]
204 if not os
.path
.isdir(folder
.encode("utf-8")):
205 NSRunAlertPanel("Error!", "Destination " + folder
+ " does not exist, try mounting it first?", "Ok", None, None)
209 def doPreviewThread(self
):
210 yield "Calculating changes..."
212 folder
= self
.getDestFolder()
217 for playlist_id
in self
.playlists():
218 playlist
= self
.library
.get_playlist_pid(playlist_id
)
219 if playlist
is not None:
220 all_tracks
.update(set(playlist
.tracks
))
223 for trackID
in all_tracks
:
224 all_filenames
.append(self
.library
.get_track_filename(trackID
))
226 gen
= libnotipod
.sync(
228 source
=self
.library
.folder
,
230 files_to_copy
=all_filenames
,
232 self
.previewResult
= "\n".join(gen
)
235 def doPreview_(self
, sender
):
236 self
.previewResult
= ""
237 self
.previewWindow
.orderOut_(self
)
240 self
.previewText
.textStorage().mutableString().setString_(self
.previewResult
)
241 self
.previewWindow
.center()
242 self
.previewWindow
.makeKeyAndOrderFront_(self
)
244 self
.runGenerator(self
.doPreviewThread
, finish
, None)
247 def doSync_(self
, sender
):
248 folder
= self
.getDestFolder()
253 orig_playlists
= set(self
.playlists())
254 all_playlists
= orig_playlists
.copy()
255 for playlist_id
in all_playlists
:
256 playlist
= self
.library
.get_playlist_pid(playlist_id
)
258 print "Forgetting unknown playlist:", playlist_id
259 self
.setPlaylist_selected_(playlist_id
, False)
261 all_tracks
.update(set(playlist
.tracks
))
264 for trackID
in all_tracks
:
265 all_filenames
.append(self
.library
.get_track_filename(trackID
))
266 all_playlists
.update(self
.library
.get_track_playlists(trackID
))
268 for playlist_id
in all_playlists
:
269 playlist
= self
.library
.get_playlist_pid(playlist_id
)
273 for trackID
in playlist
.tracks
:
274 if trackID
in all_tracks
:
275 tracks
.append(self
.library
.get_track_filename(trackID
))
276 if playlist_id
not in orig_playlists
and len(tracks
) < 10:
278 libnotipod
.export_m3u(dry_run
=False, dest
=folder
, path_prefix
="",
279 playlist_name
=playlist
.name
, files
=tracks
)
282 NSRunAlertPanel("Complete!", "Synchronisation is complete", "Ok", None, None)
287 source
=self
.library
.folder
,
289 files_to_copy
=all_filenames
,
300 return NSUserDefaults
.standardUserDefaults()
302 def _migratePrefs(self
):
305 playlists
= p
.stringArrayForKey_("playlists")
306 if playlists
is not None:
307 p
.removeObjectForKey_("playlists")
311 folders
= p
.stringArrayForKey_("folders")
314 p
.removeObjectForKey_("folders")
320 target
["playlists"] = list(playlists
)
321 target
["uuid"] = uuid
.uuid1().get_hex()
324 self
.setCurrentTarget_(target
["uuid"])
325 self
.targets
.addObject_(target
)
329 def _loadPrefs(self
):
332 self
.current_target
= None
333 self
.setCurrentTarget_(p
.stringForKey_("current_target"))
335 self
.targets
= self
.prefs().arrayForKey_("targets")
336 if self
.targets
is None:
337 self
.targets
= NSMutableArray
.array()
339 self
.targets
= NSMutableArray
.arrayWithArray_(self
.targets
)
341 if self
.getCurrentTarget() is None:
344 def _savePrefs(self
):
346 p
.setObject_forKey_(self
.current_target
, "current_target")
347 p
.setObject_forKey_(self
.targets
, "targets")
350 def getCurrentTarget(self
):
351 for target
in self
.targets
:
352 if target
["uuid"] == self
.current_target
:
356 def setCurrentTarget_(self
, target_uuid
):
357 old_uuid
= self
.current_target
358 self
.current_target
= target_uuid
359 if old_uuid
is None and target_uuid
is not None:
360 self
.playlistModel
.outlineView
.setEnabled_(True)
361 if old_uuid
!= target_uuid
:
362 self
.playlistModel
.outlineView
.reloadItem_reloadChildren_(None, True)
365 target
= self
.getCurrentTarget()
368 return list(target
["playlists"])
370 def setFolder_(self
, folder
):
371 for i
, target
in enumerate(self
.targets
):
372 if target
["folder"] == folder
:
373 self
.targets
.removeObjectAtIndex_(i
)
374 self
.targets
.insertObject_atIndex_(target
, 0)
378 target
["folder"] = folder
379 target
["playlists"] = self
.playlists()
380 target
["uuid"] = uuid
.uuid1().get_hex()
381 self
.targets
.insertObject_atIndex_(target
, 0)
383 self
.setCurrentTarget_(target
["uuid"])
387 def setPlaylist_selected_(self
, playlist
, selected
):
388 target
= self
.getCurrentTarget()
390 raise AssertionError("No target selected when editing playlists")
392 playlists
= target
["playlists"]
394 playlists
.append(playlist
)
396 playlists
.remove(playlist
)
397 target
["playlists"] = list(set(playlists
))
403 ### logging.basicConfig(format="%(levelname)s: %(message)s")
404 ### logging.getLogger().setLevel(logging.DEBUG)
405 AppHelper
.runEventLoop()
407 if __name__
== "__main__":