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()
150 def applicationWillTerminate_(self
, _
):
151 self
.prefs().synchronize()
153 def applicationShouldTerminateAfterLastWindowClosed_(self
, _
):
156 def windowDidBecomeKey_(self
, _
):
157 if self
.library
.needs_reload():
158 print "needs reload!"
161 print "no reloading this time"
165 def loadLibrary(self
):
166 if self
.runningGenerator
:
170 self
.playlistModel
.setPlaylists(self
.library
.get_playlists())
172 NSRunAlertPanel("Error!", "Unable to load iTunes library! Exiting...", "Ok", None, None)
174 self
.runGenerator(lambda: self
.library
.load_(None), finish
, fail
)
176 def runGenerator(self
, func
, finish
, fail
):
177 assert not self
.runningGenerator
178 self
.runningGenerator
= True
179 self
.loadingIndicator
.startAnimation_(self
)
180 NSApp
.beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(self
.loadingSheet
, self
.window
, None, None, None)
181 arg
= (func(), finish
, fail
)
182 self
.performSelectorInBackground_withObject_(self
.runGeneratorThread
, arg
)
184 def runGeneratorThread(self
, (gen
, finish
, fail
)):
185 pool
= NSAutoreleasePool
.alloc().init()
188 if not self
.runningGenerator
:
190 self
.loadingLabel
.performSelectorOnMainThread_withObject_waitUntilDone_(
191 self
.loadingLabel
.setStringValue_
, msg
, True)
193 NSRunAlertPanel("Error!", str(e
), "Ok", None, None)
194 traceback
.print_exc()
196 self
.performSelectorOnMainThread_withObject_waitUntilDone_(
197 self
.stopGenerator
, finish
, True)
198 self
.runningGenerator
= False
200 def stopGenerator(self
, finish
):
201 self
.runningGenerator
= False
202 NSApp
.endSheet_(self
.loadingSheet
)
203 self
.loadingSheet
.orderOut_(self
)
204 self
.loadingIndicator
.stopAnimation_(self
)
209 def doCancel_(self
, sender
):
210 self
.runningGenerator
= False
212 def getDestFolder(self
):
213 target
= self
.getCurrentTarget()
215 NSRunAlertPanel("Error!", "You must choose a folder first!", "Ok", None, None)
217 folder
= target
["folder"]
218 if not os
.path
.isdir(folder
.encode("utf-8")):
219 NSRunAlertPanel("Error!", "Destination " + folder
+ " does not exist, try mounting it first?", "Ok", None, None)
223 def doPreviewThread(self
):
224 yield "Calculating changes..."
226 folder
= self
.getDestFolder()
231 for playlist_id
in self
.playlists():
232 playlist
= self
.library
.get_playlist_pid(playlist_id
)
233 if playlist
is not None:
234 all_tracks
.update(set(playlist
.tracks
))
237 for trackID
in all_tracks
:
238 all_filenames
.append(self
.library
.get_track_filename(trackID
))
240 gen
= libnotipod
.sync(
242 source
=self
.library
.folder
,
244 files_to_copy
=all_filenames
,
246 self
.previewResult
= "\n".join(gen
)
249 def doPreview_(self
, sender
):
250 self
.previewResult
= ""
251 self
.previewWindow
.orderOut_(self
)
254 self
.previewText
.textStorage().mutableString().setString_(self
.previewResult
)
255 self
.previewWindow
.center()
256 self
.previewWindow
.makeKeyAndOrderFront_(self
)
258 self
.runGenerator(self
.doPreviewThread
, finish
, None)
261 def doSync_(self
, sender
):
262 folder
= self
.getDestFolder()
267 orig_playlists
= set(self
.playlists())
268 all_playlists
= orig_playlists
.copy()
269 for playlist_id
in all_playlists
:
270 playlist
= self
.library
.get_playlist_pid(playlist_id
)
272 print "Forgetting unknown playlist:", playlist_id
273 self
.setPlaylist_selected_(playlist_id
, False)
275 all_tracks
.update(set(playlist
.tracks
))
278 for trackID
in all_tracks
:
279 all_filenames
.append(self
.library
.get_track_filename(trackID
))
280 all_playlists
.update(self
.library
.get_track_playlists(trackID
))
282 for playlist_id
in all_playlists
:
283 playlist
= self
.library
.get_playlist_pid(playlist_id
)
287 for trackID
in playlist
.tracks
:
288 if trackID
in all_tracks
:
289 tracks
.append(self
.library
.get_track_filename(trackID
))
290 if playlist_id
not in orig_playlists
and len(tracks
) < 10:
292 libnotipod
.export_m3u(dry_run
=False, dest
=folder
, path_prefix
="",
293 playlist_name
=playlist
.name
, files
=tracks
)
296 NSRunAlertPanel("Complete!", "Synchronisation is complete", "Ok", None, None)
301 source
=self
.library
.folder
,
303 files_to_copy
=all_filenames
,
314 return NSUserDefaults
.standardUserDefaults()
316 def _migratePrefs(self
):
319 playlists
= p
.stringArrayForKey_("playlists")
320 if playlists
is not None:
321 p
.removeObjectForKey_("playlists")
325 folders
= p
.stringArrayForKey_("folders")
328 p
.removeObjectForKey_("folders")
334 target
["playlists"] = list(playlists
)
335 target
["uuid"] = uuid
.uuid1().get_hex()
338 self
.setCurrentTarget_(target
["uuid"])
339 self
.targets
.addObject_(target
)
343 def _loadPrefs(self
):
346 self
.currentTarget
= None
347 self
.setCurrentTarget_(p
.stringForKey_("currentTarget"))
349 self
.targets
= self
.prefs().arrayForKey_("targets")
350 if self
.targets
is None:
351 self
.targets
= NSMutableArray
.array()
353 self
.targets
= NSMutableArray
.arrayWithArray_(self
.targets
)
355 if self
.getCurrentTarget() is None:
358 def _savePrefs(self
):
360 p
.setObject_forKey_(self
.currentTarget
, "currentTarget")
361 p
.setObject_forKey_(self
.targets
, "targets")
364 def getCurrentTarget(self
):
365 for target
in self
.targets
:
366 if target
["uuid"] == self
.currentTarget
:
370 def setCurrentTarget_(self
, targetUuid
):
371 oldUuid
= self
.currentTarget
372 self
.currentTarget
= targetUuid
373 if oldUuid
is None and targetUuid
is not None:
374 self
.playlistModel
.outlineView
.setEnabled_(True)
375 if oldUuid
!= targetUuid
:
376 self
.playlistModel
.outlineView
.reloadItem_reloadChildren_(None, True)
379 target
= self
.getCurrentTarget()
382 return list(target
["playlists"])
384 def setFolder_(self
, folder
):
385 for i
, target
in enumerate(self
.targets
):
386 if target
["folder"] == folder
:
387 self
.targets
.removeObjectAtIndex_(i
)
388 self
.targets
.insertObject_atIndex_(target
, 0)
392 target
["folder"] = folder
393 target
["playlists"] = self
.playlists()
394 target
["uuid"] = uuid
.uuid1().get_hex()
395 self
.targets
.insertObject_atIndex_(target
, 0)
397 self
.setCurrentTarget_(target
["uuid"])
401 def setPlaylist_selected_(self
, playlist
, selected
):
402 target
= self
.getCurrentTarget()
404 raise AssertionError("No target selected when editing playlists")
406 playlists
= target
["playlists"]
408 playlists
.append(playlist
)
410 playlists
.remove(playlist
)
411 target
["playlists"] = list(set(playlists
))
417 ### logging.basicConfig(format="%(levelname)s: %(message)s")
418 ### logging.getLogger().setLevel(logging.DEBUG)
419 AppHelper
.runEventLoop()
421 if __name__
== "__main__":