From 3074bee3ddfec2210aff86efbcc588d90ee7006f Mon Sep 17 00:00:00 2001 From: Damiano Galassi Date: Sun, 27 Jan 2019 14:47:01 +0100 Subject: [PATCH] Rewrite the queue in Swift. --- Classes/AppDelegate.swift | 8 +- Classes/Document.swift | 2 +- Classes/Queue.swift | 325 ++++++++++++++++++++++++++++ Classes/QueueController.swift | 135 ++++++------ Classes/SBQueue.h | 55 ----- Classes/SBQueue.m | 359 ------------------------------- Classes/SBQueueItem.m | 2 +- Subler-Bridging-Header.h | 1 - Subler.xcodeproj/project.pbxproj | 10 +- 9 files changed, 407 insertions(+), 490 deletions(-) create mode 100644 Classes/Queue.swift delete mode 100644 Classes/SBQueue.h delete mode 100644 Classes/SBQueue.m diff --git a/Classes/AppDelegate.swift b/Classes/AppDelegate.swift index 8645e17..10e7e79 100644 --- a/Classes/AppDelegate.swift +++ b/Classes/AppDelegate.swift @@ -165,7 +165,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { - let state = QueueController.shared.queue.status + let state = QueueController.shared.status if state == .working { let alert = NSAlert() @@ -237,17 +237,17 @@ extension AppDelegate { } @objc(items) func items() -> [SBQueueItem] { - let queue = QueueController.shared.queue + let queue = QueueController.shared let indexes = IndexSet(integersIn: 0.. Bool in + return item.status != .completed && item.status != .failed + }) + first?.status = .working + } + return first + } + } + + //MARK: Item management + + func append(_ item: SBQueueItem) { + arrayQueue.sync { + items.append(item) + } + } + + func item(at index: Int) -> SBQueueItem { + var result: SBQueueItem? + arrayQueue.sync { + result = items[index] + } + return result! + } + + func items(at indexes: IndexSet) -> [SBQueueItem] { + var result: [SBQueueItem] = Array() + arrayQueue.sync { + result = items.enumerated().filter { indexes.contains($0.offset) == true } .map { $0.element } + } + return result + } + + func index(of item: SBQueueItem) -> Int { + var index = -1 + arrayQueue.sync { + index = items.firstIndex(of: item) ?? -1 + } + return index + } + + func indexesOfItems(with status: SBQueueItemStatus) -> IndexSet { + var indexes: [Int] = Array() + arrayQueue.sync { + indexes = items.enumerated().filter { $0.element.status == status } .map { $0.offset } + } + return IndexSet(indexes) + } + + func insert(_ item: SBQueueItem, at index: Int) { + arrayQueue.sync { + items.insert(item, at: index) + } + } + + func remove(at indexes: IndexSet) { + arrayQueue.sync { + items = items.enumerated().filter { indexes.contains($0.offset) == false } .map { $0.element } + } + } + + func remove(_ item: SBQueueItem) { + arrayQueue.sync { + if let index = items.firstIndex(of: item) { + items.remove(at: index) + } + } + } + + func removeCompletedItems() -> IndexSet { + var indexes: [Int] = Array() + arrayQueue.sync { + indexes = items.enumerated().filter { $0.element.status == .completed } .map { $0.offset } + items = items.enumerated().filter { indexes.contains($0.offset) == false } .map { $0.element } + } + return IndexSet(indexes) + } + + //MARK: Sleep + + private func disableSleep() { + sleepAssertionSuccess = IOPMAssertionCreateWithName(kIOPMAssertPreventUserIdleSystemSleep as CFString, + IOPMAssertionLevel(kIOPMAssertionLevelOn), + "Subler Queue" as CFString, + &sleepAssertion) + } + + private func enableSleep() { + if sleepAssertionSuccess == kIOReturnSuccess { + IOPMAssertionRelease(sleepAssertion) + sleepAssertionSuccess = kIOReturnInvalid + sleepAssertion = IOPMAssertionID(0) + } + } + + // MARK: Notifications + + func updateProgress(_ progress: Double) { + handleSBStatusWorking(progress: progress, index: -1) + } + + /// Processes SBQueueStatusWorking state information. Current implementation just + /// sends SBQueueWorkingNotification. + private func handleSBStatusWorking(progress: Double, index: Int) { + let itemDescription = currentItem?.localizedWorkingDescription ?? NSLocalizedString("Working", comment: "Queue Working.") + let info = String.localizedStringWithFormat(NSLocalizedString("%@, item %ld.", comment: ""), itemDescription, index + 1) + + NotificationCenter.default.post(name: Queue.Working, object: self, userInfo: ["ProgressString": info, "Progress": progress, "ItemIndex": index]) + } + + /// Processes SBQueueStatusCompleted state information. Current implementation just + /// sends SBQueueCompletedNotification. + private func handleSBStatusCompleted(completed: UInt, failed: UInt) { + NotificationCenter.default.post(name: Queue.Completed, object: self, userInfo: ["CompletedCount": completed, "FailedCount": failed]) + } + + /// Processes SBQueueStatusFailed state information. Current implementation just + /// sends SBQueueFailedNotification. + private func handleSBStatusFailed(error: Error) { + NotificationCenter.default.post(name: Queue.Failed, object: self, userInfo: ["Error": error]) + } + + /// Processes SBQueueStatusCancelled state information. Current implementation just + /// sends SBQueueCancelledNotification. + private func handleSBStatusCancelled() { + NotificationCenter.default.post(name: Queue.Cancelled, object: self) + } + +} diff --git a/Classes/QueueController.swift b/Classes/QueueController.swift index d998bdc..49b76a9 100644 --- a/Classes/QueueController.swift +++ b/Classes/QueueController.swift @@ -12,20 +12,19 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, static let shared = QueueController() - let queue: SBQueue - - private lazy var docImg: NSImage = { - // Load a generic movie icon to display in the table view - let img = NSWorkspace.shared.icon(forFileType: "mov") - img.size = NSSize(width: 16, height: 16) - return img - }() + private let queue: Queue private let prefs = QueuePreferences() private var popover: NSPopover? private var itemPopover: NSPopover? private var windowController: OptionsViewController? private let tablePasteboardType = NSPasteboard.PasteboardType("SublerBatchTableViewDataType") + private lazy var docImg: NSImage = { + // Load a generic movie icon to display in the table view + let img = NSWorkspace.shared.icon(forFileType: "mov") + img.size = NSSize(width: 16, height: 16) + return img + }() @IBOutlet var table: ExpandedTableView! @IBOutlet var startItem: NSToolbarItem! @@ -42,7 +41,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, windowController = nil QueuePreferences.registerUserDefaults() if let url = prefs.queueURL { - queue = SBQueue(url: url) + queue = Queue(url: url) } else { fatalError("Invalid queue url") } @@ -56,22 +55,17 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, override func windowDidLoad() { super.windowDidLoad() - guard let window = window else { - fatalError("`window` is expected to be non nil by this time.") - } - if #available(OSX 10.12, *) { - window.tabbingMode = .disallowed + window?.tabbingMode = .disallowed } table.registerForDraggedTypes([NSPasteboard.PasteboardType.backwardsCompatibleFileURL, tablePasteboardType]) - progressBar.isHidden = true let main = OperationQueue.main let nc = NotificationCenter.default - nc.addObserver(forName: NSNotification.Name.SBQueueWorking, object: queue, queue: main) {(note) in + nc.addObserver(forName: Queue.Working, object: queue, queue: main) {(note) in guard let info = note.userInfo, let status = info["ProgressString"] as? String, let progress = info["Progress"] as? Double, @@ -87,7 +81,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } } - nc.addObserver(forName: NSNotification.Name.SBQueueCompleted, object: queue, queue: main) { (note) in + nc.addObserver(forName: Queue.Completed, object: queue, queue: main) { (note) in self.progressBar.isHidden = true self.progressBar.stopAnimation(self) self.progressBar.doubleValue = 0 @@ -125,12 +119,12 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, if action == #selector(removeSelectedItems(_:)) { if let row = table?.selectedRow, row != -1 { - let item = queue.item(at: UInt(row)) + let item = queue.item(at: row) if item.status != .working { return true } } else if let row = table?.clickedRow, row != -1 { - let item = queue.item(at: UInt(row)) + let item = queue.item(at: row) if item.status != .working { return true } @@ -139,7 +133,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, if action == #selector(showInFinder(_:)) { if let row = table?.clickedRow, row != -1 { - let item = queue.item(at: UInt(row)) + let item = queue.item(at: row) if item.status == .completed { return true } @@ -148,7 +142,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, if action == #selector(edit(_:)) { if let row = table?.clickedRow, row != -1 { - let item = queue.item(at: UInt(row)) + let item = queue.item(at: row) if item.status == .completed || item.status == .ready { return true } @@ -170,10 +164,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, func saveToDisk() throws { prefs.saveUserDefaults() - let result = queue.saveToDisk() - if result { - //FIXME - } + try queue.saveToDisk() } internal func edit(item: SBQueueItem) { @@ -192,16 +183,16 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } } - if let mp4 = item.mp4File { - DispatchQueue.main.async { - do { - var doc: Document - if originalStatus == SBQueueItemStatus.completed { - try doc = Document(contentsOf: item.destURL, ofType: "") - } else { - try doc = Document(mp4: mp4) - } + DispatchQueue.main.async { + do { + var doc: Document? + if originalStatus == SBQueueItemStatus.completed { + try doc = Document(contentsOf: item.destURL, ofType: "") + } else if let mp4 = item.mp4File { + doc = Document(mp4: mp4) + } + if let doc = doc { NSDocumentController.shared.addDocument(doc) doc.makeWindowControllers() doc.showWindows() @@ -212,10 +203,10 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, let index = self.queue.index(of: item) self.remove(at: index) self.updateUI() - } catch { - //FIXME - print(error) } + } catch { + //FIXME + print(error) } } } @@ -280,9 +271,25 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, //MARK: Queue management + var status: Queue.Status { + get { + return queue.status + } + } + + var count: Int { + get { + return queue.count + } + } + + func items(at indexes: IndexSet) -> [SBQueueItem] { + return queue.items(at: indexes) + } + /// Adds a SBQueueItem to the queue func add(_ item: SBQueueItem) { - add(items: [item], at: IndexSet(integer: IndexSet.Element(queue.count))) + insert(items: [item], at: IndexSet(integer: IndexSet.Element(queue.count))) } func add(_ item: SBQueueItem, applyPreset: Bool) { @@ -293,14 +300,14 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, add(item) } - private func add(_ items: [SBQueueItem]) { - let indexes = IndexSet(integersIn: Int(queue.count) ..< (Int(queue.count) + items.count)) - add(items: items, at: indexes) + private func add(_ items: [SBQueueItem], at index: Int) { + let indexes = IndexSet(integersIn: index ..< (index + items.count)) + insert(items: items, at: indexes) } /// Adds an array of SBQueueItem to the queue. /// Implements the undo manager. - private func add(items: [SBQueueItem], at indexes: IndexSet) { + func insert(items: [SBQueueItem], at indexes: IndexSet) { guard let firstIndex = indexes.first else { fatalError() } table.beginUpdates() @@ -310,7 +317,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, var currentObjectIndex = 0 while currentIndex != NSNotFound { - queue.insert(items[currentObjectIndex], at: UInt(currentIndex)) + queue.insert(items[currentObjectIndex], at: currentIndex) currentIndex = indexes.integerGreaterThan(currentIndex) ?? NSNotFound currentObjectIndex += 1 } @@ -336,11 +343,11 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } } - private func remove(at index: UInt) { + private func remove(at index: Int) { remove(at: IndexSet(integer: IndexSet.Element(index))) } - private func remove(at indexes: IndexSet) { + func remove(at indexes: IndexSet) { if indexes.isEmpty { return } @@ -350,7 +357,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, let removedItems = queue.items(at: indexes) if queue.count > indexes.last! { - queue.removeItems(at: indexes) + queue.remove(at: indexes) } table.removeRows(at: indexes, withAnimation: .slideUp) @@ -362,7 +369,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, guard let undo = window?.undoManager else { return } undo.registerUndo(withTarget: self) { (target) in - self.add(items: removedItems, at: indexes) + self.insert(items: removedItems, at: indexes) } if undo.isUndoing == false { @@ -370,16 +377,16 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } } - private func move(items: [SBQueueItem], at index: UInt) { + private func move(items: [SBQueueItem], at index: Int) { var currentIndex = index - var source: [UInt] = Array() - var dest: [UInt] = Array() + var source: [Int] = Array() + var dest: [Int] = Array() table.beginUpdates() for item in items.reversed() { let sourceIndex = queue.index(of: item) - queue.removeItems(at: IndexSet(integer: IndexSet.Element(sourceIndex))) + queue.remove(at: IndexSet(integer: IndexSet.Element(sourceIndex))) if sourceIndex < currentIndex { currentIndex -= 1 @@ -406,9 +413,9 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } } - private func move(at source: [UInt], to dest: [UInt]) { - var newSource: [UInt] = Array() - var newDest: [UInt] = Array() + private func move(at source: [Int], to dest: [Int]) { + var newSource: [Int] = Array() + var newDest: [Int] = Array() table.beginUpdates() @@ -417,10 +424,10 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, newDest.append(sourceIndex) if let item = queue.items(at: IndexSet(integer: IndexSet.Element(sourceIndex))).first { - queue.removeItems(at: IndexSet(integer: IndexSet.Element(sourceIndex))) + queue.remove(at: IndexSet(integer: IndexSet.Element(sourceIndex))) queue.insert(item, at: destIndex) - table.moveRow(at: Int(sourceIndex), to: Int(destIndex)) + table.moveRow(at: sourceIndex, to: destIndex) } } @@ -529,6 +536,8 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, progressBar.isHidden = false progressBar.startAnimation(self) + window?.undoManager?.removeAllActions(withTarget: self) + queue.start() } @@ -560,7 +569,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, @IBAction func toggleItemsOptions(_ sender: Any?) { guard let sender = sender as? NSView else { return } let index = table.row(for: sender) - let item = queue.item(at: UInt(index)) + let item = queue.item(at: index) if let p = itemPopover, p.isShown, let controller = p.contentViewController as? ItemViewController, controller.item == item { p.close() @@ -607,7 +616,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, items.append(item) } } - add(items) + add(items, at: index) } @IBAction func open(_ sender: Any?) { @@ -635,7 +644,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, private let nameColumn = NSUserInterfaceItemIdentifier(rawValue: "nameColumn") func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { - let item = queue.item(at: UInt(row)) + let item = queue.item(at: row) if tableColumn?.identifier == nameColumn { let cell = tableView.makeView(withIdentifier: nameColumn, owner: self) as? NSTableCellView @@ -688,7 +697,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, @IBAction func edit(_ sender: Any?) { let clickedRow = table.clickedRow if clickedRow > -1 { - let item = queue.item(at: UInt(clickedRow)) + let item = queue.item(at: clickedRow) edit(item: item) } } @@ -696,7 +705,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, @IBAction func showInFinder(_ sender: Any?) { let clickedRow = table.clickedRow if clickedRow > -1 { - let item = queue.item(at: UInt(clickedRow)) + let item = queue.item(at: clickedRow) NSWorkspace.shared.activateFileViewerSelecting([item.destURL]) } } @@ -710,7 +719,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, if indexes.isEmpty == false { table.removeRows(at: indexes, withAnimation: .slideUp) - queue.removeItems(at: indexes) + queue.remove(at: indexes) updateState() } } @@ -743,7 +752,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? IndexSet { let items = queue.items(at: rowIndexes) - move(items: items, at: UInt(row)) + move(items: items, at: row) return true } else { diff --git a/Classes/SBQueue.h b/Classes/SBQueue.h deleted file mode 100644 index b6c846e..0000000 --- a/Classes/SBQueue.h +++ /dev/null @@ -1,55 +0,0 @@ -// -// SBQueue.h -// Subler -// -// Created by Damiano Galassi on 27/02/14. -// -// - -#import -#import "SBQueueItem.h" - -NS_ASSUME_NONNULL_BEGIN - -typedef NS_ENUM(NSUInteger, SBQueueStatus) { - SBQueueStatusUnknown = 0, - SBQueueStatusWorking, - SBQueueStatusCompleted, -}; - -extern NSString *SBQueueWorkingNotification; -extern NSString *SBQueueCompletedNotification; -extern NSString *SBQueueFailedNotification; -extern NSString *SBQueueCancelledNotification; - -@interface SBQueue : NSObject - -@property (atomic, readonly) SBQueueStatus status; - -- (instancetype)init NS_UNAVAILABLE; -- (instancetype)initWithURL:(NSURL *)queueURL NS_DESIGNATED_INITIALIZER; - -- (void)start; -- (void)stop; - -- (void)addItem:(SBQueueItem *)item; - -@property (nonatomic, readonly) NSUInteger count; -@property (nonatomic, readonly) NSUInteger readyCount; - -- (SBQueueItem *)itemAtIndex:(NSUInteger)index; -- (NSUInteger)indexOfItem:(SBQueueItem *)item; -- (NSIndexSet *)indexesOfItemsWithStatus:(SBQueueItemStatus)status; -- (NSArray *)itemsAtIndexes:(NSIndexSet *)indexes; - -- (void)insertItem:(SBQueueItem *)anItem atIndex:(NSUInteger)index; - -- (void)removeItemsAtIndexes:(NSIndexSet *)indexes; -- (void)removeItem:(SBQueueItem *)item; - -- (NSIndexSet *)removeCompletedItems; -- (BOOL)saveQueueToDisk; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Classes/SBQueue.m b/Classes/SBQueue.m deleted file mode 100644 index 2f52993..0000000 --- a/Classes/SBQueue.m +++ /dev/null @@ -1,359 +0,0 @@ -// -// SBQueue.m -// Subler -// -// Created by Damiano Galassi on 27/02/14. -// -// - -#import "SBQueue.h" -#import - -NSString *SBQueueWorkingNotification = @"SBQueueWorkingNotification"; -NSString *SBQueueCompletedNotification = @"SBQueueCompletedNotification"; -NSString *SBQueueFailedNotification = @"SBQueueFailedNotification"; -NSString *SBQueueCancelledNotification = @"SBQueueCancelledNotification"; - -@interface SBQueue () - -@property (atomic) SBQueueStatus status; - -@property (nonatomic, copy) NSURL *URL; -@property (nonatomic) NSMutableArray *items; - -@property (nonatomic) NSUInteger currentIndex; -@property (atomic) SBQueueItem *currentItem; -@property (atomic) BOOL cancelled; - -@property (nonatomic) IOPMAssertionID assertionID; -@property (nonatomic) IOReturn io_success; - -@property (nonatomic) dispatch_queue_t workQueue; -@property (nonatomic) dispatch_queue_t arrayQueue; - -@end - -@implementation SBQueue - -- (instancetype)initWithURL:(NSURL *)queueURL { - self = [super init]; - if (self) { - _workQueue = dispatch_queue_create("org.subler.WorkQueue", DISPATCH_QUEUE_SERIAL); - _arrayQueue = dispatch_queue_create("org.subler.SaveQueue", DISPATCH_QUEUE_SERIAL); - _URL = [queueURL copy]; - - @try { - NSData *queue = [NSData dataWithContentsOfURL:queueURL]; - if (queue) { - NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:queue]; - unarchiver.requiresSecureCoding = YES; - _items = [unarchiver decodeObjectOfClasses:[NSSet setWithObjects:[NSMutableArray class], [SBQueueItem class], nil] - forKey:NSKeyedArchiveRootObjectKey]; - [unarchiver finishDecoding]; - } - } - @catch (NSException *exception) { - [[NSFileManager defaultManager] removeItemAtURL:queueURL error:nil]; - _items = nil; - } - - for (SBQueueItem *item in _items) { - if (item.status == SBQueueItemStatusWorking) { - item.status = SBQueueItemStatusFailed; - } - } - - if (!_items) { - _items = [[NSMutableArray alloc] init]; - } - - } - return self; -} - -- (BOOL)saveQueueToDisk { - __block BOOL result; - dispatch_sync(self.arrayQueue, ^{ - NSMutableData *data = [[NSMutableData alloc] init]; - - NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; - archiver.requiresSecureCoding = YES; - [archiver encodeObject:self.items forKey:NSKeyedArchiveRootObjectKey]; - [archiver finishEncoding]; - - result = [data writeToURL:self.URL atomically:YES]; - }); - return result; -} - -- (SBQueueItem *)firstItemInQueue { - __block SBQueueItem *firstItem = nil; - dispatch_sync(self.arrayQueue, ^{ - for (SBQueueItem *item in self.items) { - if ((item.status != SBQueueItemStatusCompleted) && (item.status != SBQueueItemStatusFailed)) { - firstItem = item; - firstItem.status = SBQueueItemStatusWorking; - break; - } - } - }); - return firstItem; -} - -- (NSUInteger)indexOfCurrentItem { - __block NSUInteger index; - dispatch_sync(self.arrayQueue, ^{ - index = [self.items indexOfObject:self.currentItem]; - }); - return index; -} - -#pragma mark - item management - -- (void)addItem:(SBQueueItem *)item { - dispatch_sync(self.arrayQueue, ^{ - [self.items addObject:item]; - }); -} - -- (NSUInteger)count { - __block NSUInteger count; - dispatch_sync(self.arrayQueue, ^{ - count = self.items.count; - }); - return count; -} - -- (NSUInteger)readyCount { - __block NSUInteger count = 0; - dispatch_sync(self.arrayQueue, ^{ - for (SBQueueItem *item in self.items) { - if (item.status == SBQueueItemStatusReady) { - count++; - } - } - }); - return count; -} - -- (SBQueueItem *)itemAtIndex:(NSUInteger)index { - __block SBQueueItem *item; - dispatch_sync(self.arrayQueue, ^{ - item = self.items[index]; - }); - return item; -} - -- (NSArray *)itemsAtIndexes:(NSIndexSet *)indexes { - __block NSArray *items; - dispatch_sync(self.arrayQueue, ^{ - items = [self.items objectsAtIndexes:indexes]; - }); - return items; -} - -- (NSUInteger)indexOfItem:(SBQueueItem *)item { - __block NSUInteger index = 0; - dispatch_sync(self.arrayQueue, ^{ - index = [self.items indexOfObject:item]; - }); - return index; -} - -- (NSIndexSet *)indexesOfItemsWithStatus:(SBQueueItemStatus)status { - NSMutableIndexSet *indexes = [NSMutableIndexSet indexSet]; - dispatch_sync(self.arrayQueue, ^{ - [self.items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - if (((SBQueueItem *)obj).status == status) { - [indexes addIndex:idx]; - } - }]; - }); - return indexes; -} - -- (void)insertItem:(SBQueueItem *)anItem atIndex:(NSUInteger)index { - dispatch_sync(self.arrayQueue, ^{ - [self.items insertObject:anItem atIndex:index]; - }); -} - -- (void)removeItemsAtIndexes:(NSIndexSet *)indexes { - dispatch_sync(self.arrayQueue, ^{ - [self.items removeObjectsAtIndexes:indexes]; - }); -} - -- (void)removeItem:(SBQueueItem *)item { - dispatch_sync(self.arrayQueue, ^{ - [self.items removeObject:item]; - }); -} - -- (NSIndexSet *)removeCompletedItems { - NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc] init]; - - dispatch_sync(self.arrayQueue, ^{ - for (SBQueueItem *item in self.items) - if (item.status == SBQueueItemStatusCompleted) - [indexes addIndex:[self.items indexOfObject:item]]; - - [self.items removeObjectsAtIndexes:indexes]; - }); - - return indexes; -} - -#pragma mark - Queue control - -- (void)disableSleep { - CFStringRef reasonForActivity= CFSTR("Subler Queue Started"); - _io_success = IOPMAssertionCreateWithName(kIOPMAssertPreventUserIdleSystemSleep, - kIOPMAssertionLevelOn, reasonForActivity, &_assertionID); -} - -- (void)enableSleep { - if (_io_success == kIOReturnSuccess) { - IOPMAssertionRelease(_assertionID); - } -} - -/* - * Starts the queue. - */ -- (void)start { - dispatch_sync(self.arrayQueue, ^{ - if (self.status == SBQueueStatusWorking || self.cancelled) { - return; - } else { - self.status = SBQueueStatusWorking; - } - }); - - dispatch_async(self.workQueue, ^{ - // Enable sleep assertion - [self disableSleep]; - - NSUInteger completedCount = 0; - NSUInteger failedCount = 0; - - for (;;) { - @autoreleasepool { - // Save to disk - [self saveQueueToDisk]; - - NSError *outError = nil; - BOOL noErr = NO; - - // Save the queue - [self saveQueueToDisk]; - - // Get the first item available in the queue - self.currentItem = [self firstItemInQueue]; - - if (!self.currentItem) { - break; - } - - self.currentIndex = [self indexOfCurrentItem]; - self.currentItem.status = SBQueueItemStatusWorking; - self.currentItem.delegate = self; - - [self handleSBStatusWorking:0 index:self.currentIndex]; - noErr = [self.currentItem process:&outError]; - - // Check results - if (self.cancelled) { - if (outError.code != 12) { - self.currentItem.status = SBQueueItemStatusCancelled; - } - self.currentItem = nil; - [self handleSBStatusCancelled]; - break; - } - - if (noErr) { - self.currentItem.status = SBQueueItemStatusCompleted; - completedCount += 1; - } - else { - self.currentItem.status = SBQueueItemStatusFailed; - failedCount += 1; - [self handleSBStatusFailed:outError]; - } - - self.currentItem.delegate = nil; - self.currentItem = nil; - - [self handleSBStatusWorking:100 index:self.currentIndex]; - } - - if (self.cancelled) { - break; - } - } - - // Disable sleep assertion - [self enableSleep]; - [self handleSBStatusCompleted:completedCount failed:failedCount]; - - // Reset cancelled state - self.cancelled = NO; - }); -} - -/** - * Stops the queue and abort the current work. - */ -- (void)stop { - self.cancelled = YES; - [self.currentItem cancel]; -} - -- (void)progressStatus:(double)progress { - [self handleSBStatusWorking:progress index:-1]; -} - -/** - * Processes SBQueueStatusWorking state information. Current implementation just - * sends SBQueueWorkingNotification. - */ -- (void)handleSBStatusWorking:(CGFloat)progress index:(NSInteger)index { - NSString *itemDescription = self.currentItem.localizedWorkingDescription; - if (!itemDescription) { - itemDescription = NSLocalizedString(@"Working", @"Queue Working."); - } - NSString *info = [NSString stringWithFormat:NSLocalizedString(@"%@, item %ld.", nil), itemDescription, (long)self.currentIndex + 1]; - - [[NSNotificationCenter defaultCenter] postNotificationName:SBQueueWorkingNotification object:self userInfo:@{@"ProgressString": info, - @"Progress": @(progress), - @"ItemIndex": @(index)}]; -} - -/** - * Processes SBQueueStatusCompleted state information. Current implementation just - * sends SBQueueCompletedNotification. - */ -- (void)handleSBStatusCompleted:(NSUInteger)completedCount failed:(NSUInteger)failedCount { - self.status = SBQueueStatusCompleted; - [[NSNotificationCenter defaultCenter] postNotificationName:SBQueueCompletedNotification object:self userInfo:@{@"CompletedCount": @(completedCount), - @"FailedCount": @(failedCount)}]; -} - -/** - * Processes SBQueueStatusFailed state information. Current implementation just - * sends SBQueueFailedNotification. - */ -- (void)handleSBStatusFailed:(NSError *)error { - [[NSNotificationCenter defaultCenter] postNotificationName:SBQueueFailedNotification object:self userInfo:@{@"Error" : error != nil ? error : [NSNull null]}]; -} - -/** - * Processes SBQueueStatusCancelled state information. Current implementation just - * sends SBQueueCancelledNotification. - */ -- (void)handleSBStatusCancelled { - [[NSNotificationCenter defaultCenter] postNotificationName:SBQueueCancelledNotification object:self]; -} - -@end diff --git a/Classes/SBQueueItem.m b/Classes/SBQueueItem.m index c845552..aa43663 100755 --- a/Classes/SBQueueItem.m +++ b/Classes/SBQueueItem.m @@ -436,7 +436,7 @@ bail: } - (void)progressStatus:(double)progress { - [self.delegate progressStatus:progress]; + [self updateProgress:progress]; } #pragma mark NSSecureCoding diff --git a/Subler-Bridging-Header.h b/Subler-Bridging-Header.h index 6907650..1e6a6e9 100644 --- a/Subler-Bridging-Header.h +++ b/Subler-Bridging-Header.h @@ -2,6 +2,5 @@ // Use this file to import your target's public headers that you would like to expose to Swift. // -#import "SBQueue.h" #import "SBQueueItem.h" #import "SBMovieViewController.h" diff --git a/Subler.xcodeproj/project.pbxproj b/Subler.xcodeproj/project.pbxproj index 9f547b5..6e89d5c 100644 --- a/Subler.xcodeproj/project.pbxproj +++ b/Subler.xcodeproj/project.pbxproj @@ -67,6 +67,7 @@ A98542DD20D1A7E500EB9803 /* ArtworkSelectorViewItem.xib in Resources */ = {isa = PBXBuildFile; fileRef = A98542DB20D1A7E500EB9803 /* ArtworkSelectorViewItem.xib */; }; A9859ACE1F4B43CC00022828 /* QueuePreset.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9859ACD1F4B43CC00022828 /* QueuePreset.swift */; }; A98D44102036F661005CB092 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A98D440F2036F661005CB092 /* AppDelegate.swift */; }; + A98D6BAB21FDC62800F0D886 /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = A98D6BAA21FDC62800F0D886 /* Queue.swift */; }; A98D98461F0280CB00A77ABC /* TheMovieDB.swift in Sources */ = {isa = PBXBuildFile; fileRef = A98D98451F0280CB00A77ABC /* TheMovieDB.swift */; }; A98D98481F02820F00A77ABC /* TheMovieDBService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A98D98471F02820F00A77ABC /* TheMovieDBService.swift */; }; A9907E192063DAA000DB992E /* VideoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9907E182063DAA000DB992E /* VideoViewController.swift */; }; @@ -112,7 +113,6 @@ A9CBAB1E1F29C083001C26B3 /* MetadataImporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CBAB1D1F29C083001C26B3 /* MetadataImporter.swift */; }; A9D4B8671C05BD04007845C4 /* SBChapterSearch.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9D4B8651C05BD04007845C4 /* SBChapterSearch.xib */; }; A9D64527202CA92400BA172B /* SaveOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9D64525202CA92400BA172B /* SaveOptions.swift */; }; - A9D73C5218BF3F1100C6FFA6 /* SBQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = A9D73C5118BF3F1100C6FFA6 /* SBQueue.m */; }; A9DA3B9C1B918D5C00F1E40C /* SBApplication.m in Sources */ = {isa = PBXBuildFile; fileRef = A9DA3B991B918D5C00F1E40C /* SBApplication.m */; }; A9DA3BA31B918D6F00F1E40C /* ExceptionAlert.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9DA3BA11B918D6F00F1E40C /* ExceptionAlert.xib */; }; A9E97F141F274F1100DBA586 /* iTunesStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E97F131F274F1100DBA586 /* iTunesStore.swift */; }; @@ -277,6 +277,7 @@ A98BC09F20E623700035278B /* it */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = it; path = it.lproj/ArtworkSelector.strings; sourceTree = ""; }; A98BC0A020E623700035278B /* it */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = it; path = it.lproj/PrefsWindowController.strings; sourceTree = ""; }; A98D440F2036F661005CB092 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = Classes/AppDelegate.swift; sourceTree = ""; }; + A98D6BAA21FDC62800F0D886 /* Queue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Classes/Queue.swift; sourceTree = ""; }; A98D98451F0280CB00A77ABC /* TheMovieDB.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = TheMovieDB.swift; path = Classes/MetadataImporters/TheMovieDB.swift; sourceTree = ""; }; A98D98471F02820F00A77ABC /* TheMovieDBService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = TheMovieDBService.swift; path = Classes/MetadataImporters/TheMovieDBService.swift; sourceTree = ""; }; A9907E182063DAA000DB992E /* VideoViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = VideoViewController.swift; path = Classes/PropertyView/VideoViewController.swift; sourceTree = ""; }; @@ -334,8 +335,6 @@ A9C73535206B8F9900794673 /* QueuePreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = QueuePreferences.swift; path = Classes/QueuePreferences.swift; sourceTree = ""; }; A9CBAB1D1F29C083001C26B3 /* MetadataImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MetadataImporter.swift; path = Classes/MetadataImporters/MetadataImporter.swift; sourceTree = ""; }; A9D64525202CA92400BA172B /* SaveOptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SaveOptions.swift; path = Classes/SaveOptions.swift; sourceTree = ""; }; - A9D73C5018BF3F1100C6FFA6 /* SBQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SBQueue.h; path = Classes/SBQueue.h; sourceTree = ""; }; - A9D73C5118BF3F1100C6FFA6 /* SBQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SBQueue.m; path = Classes/SBQueue.m; sourceTree = ""; }; A9DA3B991B918D5C00F1E40C /* SBApplication.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SBApplication.m; path = Classes/SBApplication.m; sourceTree = ""; }; A9DA3BA01B918D6200F1E40C /* SBApplication.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SBApplication.h; path = Classes/SBApplication.h; sourceTree = ""; }; A9E97F131F274F1100DBA586 /* iTunesStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = iTunesStore.swift; path = Classes/MetadataImporters/iTunesStore.swift; sourceTree = ""; }; @@ -579,8 +578,7 @@ A9676A2F1FB6E85300C1E300 /* LanguageTransformer.swift */, A9676A331FB6EAAD00C1E300 /* ItemViewController.swift */, A9BC410618D9ABC000F8C92C /* QueueItem.xib */, - A9D73C5018BF3F1100C6FFA6 /* SBQueue.h */, - A9D73C5118BF3F1100C6FFA6 /* SBQueue.m */, + A98D6BAA21FDC62800F0D886 /* Queue.swift */, A982D0BE140AB66400B92357 /* SBQueueItem.h */, A982D0BF140AB66400B92357 /* SBQueueItem.m */, A91B196B1F2B0DCB0008675F /* QueueAction.swift */, @@ -846,6 +844,7 @@ A959001A202AF21800FD8F23 /* ProgressViewController.swift in Sources */, A91576EB204ECA6E00D93CE7 /* Token.swift in Sources */, A9676A341FB6EAAD00C1E300 /* ItemViewController.swift in Sources */, + A98D6BAB21FDC62800F0D886 /* Queue.swift in Sources */, A98542DC20D1A7E500EB9803 /* ArtworkSelectorViewItem.swift in Sources */, A90C3E0C1FD16AF200F64532 /* TokensViewController.swift in Sources */, A9AB485617F0AEAC000AA72E /* SBMovieViewController.m in Sources */, @@ -885,7 +884,6 @@ A9C09C981F99F971007939EE /* ExpandedTableView.swift in Sources */, A90240DB2063BD3700E762FA /* MediaTagsController.swift in Sources */, A997B0AA1F348AB000974C9C /* MetadataSearchController.swift in Sources */, - A9D73C5218BF3F1100C6FFA6 /* SBQueue.m in Sources */, A956CE6B1F99EAAD00093992 /* Logger.swift in Sources */, A956CE691F99E93D00093992 /* ButtonToolbarItem.swift in Sources */, A98D44102036F661005CB092 /* AppDelegate.swift in Sources */,