Convert SBAppDelegate to Swift.

This commit is contained in:
Damiano Galassi committed 2018-02-17 10:46:53 +01:00
1 parent 40844819e1
commit 66f4575ffc
15 files changed
+272 -361

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ class ActivityWindowController : NSWindowController, MP42Logging {
@IBOutlet var logView: NSTextView!
let logger: Logger
@objc init(logger: Logger) {
init(logger: Logger) {
self.logger = logger
super.init(window: nil)
self.logger.delegate = self
+240
View File
@@ -0,0 +1,240 @@
//
// AppDelegate.swift
// Subler
//
// Created by Damiano Galassi on 16/02/2018.
//
import Cocoa
class DocumentController : NSDocumentController {
override func openDocument(withContentsOf url: URL, display displayDocument: Bool, completionHandler: @escaping (NSDocument?, Bool, Error?) -> Void) {
let ext = url.pathExtension.lowercased()
if ["mkv", "mka", "mks", "mov"].contains(ext) {
do {
let doc = try self.openUntitledDocumentAndDisplay(displayDocument)
completionHandler(doc, false, nil)
if let windowController = doc.windowControllers.first as? DocumentWindowController {
windowController.showImportSheet(fileURLs: [url])
}
} catch {
completionHandler(nil, false, error)
}
}
else {
super.openDocument(withContentsOf: url, display: displayDocument, completionHandler: completionHandler)
}
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
private static func appSupportURL() -> URL {
let fileManager = FileManager.default
if let url = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)
.first?.appendingPathComponent("Subler") {
do {
if fileManager.fileExists(atPath: url.path) == false {
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: [:])
}
}
catch _ {
fatalError("Couldn't create the app support directory")
}
return url
}
else {
fatalError("Couldn't find the app support directory")
}
}
private lazy var prefsController: PrefsWindowController = {
return PrefsWindowController()
}()
private lazy var logger: Logger = {
return Logger(fileURL: AppDelegate.appSupportURL().appendingPathComponent("debugLog.txt"))
}()
private lazy var activityWindowController: ActivityWindowController = {
return ActivityWindowController(logger: logger)
}()
private lazy var documentController: DocumentController = {
return DocumentController()
}()
private func runDonateAlert() {
let defaults = UserDefaults.standard
let firstLaunch = defaults.bool(forKey: "SBFirstLaunch") ? false : true
let donateNagTime = Double(60 * 60 * 24 * 7)
let donateNagTimeLong = Double(60 * 60 * 24 * 120)
let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
let lastVersion = defaults.string(forKey: "SBDonateAskVersion") ?? ""
let versionChanged = currentVersion != lastVersion
if versionChanged {
defaults.set(currentVersion, forKey: "SBDonateAskVersion")
let lastDonateDate = defaults.object(forKey: "SBDonateAskDate") as? Date
let timePassed = lastDonateDate == nil || (-1 * (lastDonateDate?.timeIntervalSinceNow ?? 0)) >= donateNagTimeLong
if timePassed {
defaults.removeObject(forKey: "SBWarningDonate")
defaults.removeObject(forKey: "SBFirstLaunch")
defaults.removeObject(forKey: "SBDonateAskDate")
}
}
if defaults.bool(forKey: "SBWarningDonate") == false {
let lastDonateDate = defaults.object(forKey: "SBDonateAskDate") as? Date
let timePassed = lastDonateDate == nil || (-1 * (lastDonateDate?.timeIntervalSinceNow ?? 0)) >= donateNagTime
if firstLaunch == false && timePassed {
defaults.set(Date(), forKey: "SBDonateAskDate")
let alert = NSAlert()
alert.messageText = NSLocalizedString("Support Subler", comment: "Donation -> title")
alert.informativeText = NSLocalizedString(" A lot of time and effort have gone into development, coding, and refinement.\n If you enjoy using it, please consider showing your appreciation with a donation.", comment: "Donation -> message")
alert.alertStyle = .informational
alert.addButton(withTitle: NSLocalizedString("Donate", comment: "Donation -> button"))
let noDonateButton = alert.addButton(withTitle: NSLocalizedString("Nope", comment: "Donation -> button"))
noDonateButton.keyEquivalent = String(format: "%c", 0x1b) // escape key
let allowAgain = lastDonateDate != nil //hide the "don't show again" check the first time - give them time to try the app
alert.showsSuppressionButton = allowAgain
if allowAgain {
alert.suppressionButton?.title = NSLocalizedString("Don't ask me about this again for this version.", comment: "Donation -> button")
}
let donateResult = alert.runModal()
if donateResult == .alertFirstButtonReturn {
donate(self)
}
if allowAgain {
defaults.set(alert.suppressionButton?.state != .on, forKey: "SBWarningDonate")
}
}
}
if firstLaunch {
defaults.set(true, forKey: "SBFirstLaunch")
}
}
// MARK: delegates
func applicationWillFinishLaunching(_ notification: Notification) {
PrefsWindowController.registerUserDefaults()
_ = documentController
logger.clear()
MP42File.setGlobalLogger(logger)
}
func applicationDidFinishLaunching(_ notification: Notification) {
_ = SBQueueController.sharedManager
if UserDefaults.standard.bool(forKey: "SBShowQueueWindow") {
SBQueueController.sharedManager.showWindow(self)
}
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
let state = SBQueueController.sharedManager.queue.status
if state == .working {
let alert = NSAlert()
alert.messageText = NSLocalizedString("Are you sure you want to quit Subler?", comment: "Quit alert title.")
alert.informativeText = NSLocalizedString("Your current queue will be lost. Do you want to quit anyway?", comment: "Quit alert description.")
alert.addButton(withTitle: NSLocalizedString("Quit", comment: "Quit alert default action."))
alert.addButton(withTitle: NSLocalizedString("Don't Quit", comment: "Quit alert cancel action."))
alert.alertStyle = .critical
let result = alert.runModal()
return result == .alertFirstButtonReturn ? .terminateNow : .terminateCancel
}
return .terminateNow
}
func applicationWillTerminate(_ notification: Notification) {
try! PresetManager.shared.save()
if SBQueueController.sharedManager.saveQueueToDisk == false {
logger.write(toLog: "Failed to save queue to disk!")
}
UserDefaults.standard.set(SBQueueController.sharedManager.window?.isVisible, forKey: "SBShowQueueWindow")
}
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
return false
}
// MARK: actions
@IBAction func openInQueue(_ sender: Any) {
SBQueueController.sharedManager.showWindow(self)
SBQueueController.sharedManager.open(sender)
}
@IBAction func showBatchWindow(_ sender: Any) {
SBQueueController.sharedManager.showWindow(self)
}
@IBAction func showPrefsWindow(_ sender: Any) {
prefsController.showWindow(self)
}
@IBAction func showDebugLog(_ sender: Any) {
activityWindowController.showWindow(self)
}
@IBAction func donate(_ sender: Any) {
guard let url = URL(string: "https://subler.org/donate.php") else { return }
NSWorkspace.shared.open(url)
}
@IBAction func help(_ sender: Any) {
guard let url = URL(string: "https://bitbucket.org/galad87/subler/wiki/Home") else { return }
NSWorkspace.shared.open(url)
}
}
extension AppDelegate {
override func application(_ sender: NSApplication, delegateHandlesKey key: String) -> Bool {
if key == "items" {
return true
} else {
return false
}
}
@objc(items) func items() -> [SBQueueItem] {
let queue = SBQueueController.sharedManager.queue
let indexes = IndexSet(integersIn: 0..<Int(queue.count))
return queue.items(at: indexes)
}
@objc(insertObject:inItemsAtIndex:) func insert(object: SBQueueItem, inItemsAtIndex index: UInt) {
SBQueueController.sharedManager.queue.insert(object, at: index)
}
@objc(removeObjectFromItemsAtIndex:) func removeObjectFromItemsAtIndex(_ index: UInt) {
SBQueueController.sharedManager.queue.removeItems(at: IndexSet(integer: IndexSet.Element(index)))
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ import IOKit.pwr_mgt
@objc(SBDocument) class Document: NSDocument {
var mp4: MP42File
private(set) var mp4: MP42File
private var unsupportedMp4Brand: Bool
override init() {
+1 -4
View File
@@ -55,9 +55,6 @@ class DocumentWindowController: NSWindowController, TracksViewControllerDelegate
window.setFrameFrom("documentSave")
}
window.contentViewController = splitViewController
window.registerForDraggedTypes([NSPasteboard.PasteboardType.backwardsCompatibleFileURL])
didSelect(tracks: [])
}
@@ -498,7 +495,7 @@ class DocumentWindowController: NSWindowController, TracksViewControllerDelegate
}
}
@objc func showImportSheet(fileURLs: [URL]) {
func showImportSheet(fileURLs: [URL]) {
do {
let controller = try FileImportController(fileURLs: fileURLs, delegate: self)
+4 -4
View File
@@ -11,10 +11,10 @@ class Logger : NSObject, MP42Logging {
var delegate: MP42Logging?
let fileURL: URL
let queue: DispatchQueue
private let fileURL: URL
private let queue: DispatchQueue
@objc init(fileURL: URL) {
init(fileURL: URL) {
self.fileURL = fileURL
self.queue = DispatchQueue(label: "org.subler.LogQueue")
}
@@ -50,7 +50,7 @@ class Logger : NSObject, MP42Logging {
write(toLog: error.localizedDescription)
}
@objc func clear() {
func clear() {
try? FileManager.default.removeItem(at: fileURL)
}
+1 -1
View File
@@ -166,7 +166,7 @@ extension PresetManager.Error: LocalizedError {
preset.changed = false
}
@objc func save() throws {
func save() throws {
let manager = FileManager.default
guard let url = appSupportURL() else { return }
@@ -14,7 +14,10 @@ class MultiSelectViewController : NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
reloadUI()
}
func reloadUI() {
if numberOfTracks == 1 {
label.stringValue = NSLocalizedString("1 track selected", comment: "")
} else {
+3 -3
View File
@@ -6,9 +6,6 @@
// Copyright 2009 Damiano Galassi. All rights reserved.
//
NSString *SublerMetadataPBoardType = @"SublerMetadataPBoardTypeV2";
NSString *SublerCoverArtPBoardType = @"SublerCoverArtPBoardType";
#import "SBMovieViewController.h"
#import <MP42Foundation/MP42Ratings.h>
@@ -18,6 +15,9 @@ NSString *SublerCoverArtPBoardType = @"SublerCoverArtPBoardType";
#import "Subler-Swift.h"
NSString *SublerMetadataPBoardType = @"SublerMetadataPBoardTypeV2";
NSString *SublerCoverArtPBoardType = @"SublerCoverArtPBoardType";
@interface SBMovieViewController () <NSTableViewDataSource, ExpandedTableViewDelegate, SBImageBrowserViewDelegate>
// Metadata tab
@@ -45,6 +45,10 @@ class SoundViewController : NSViewController {
mediaTagsView.addSubview(mediaTagsController.view)
reloadUI()
}
private func reloadUI() {
// Standard audio controls
volume.floatValue = track.volume * 100
alternateGroup.selectItem(at: Int(track.alternateGroup))
@@ -59,8 +63,8 @@ class SoundViewController : NSViewController {
if isAAC(track: audioTrack) {
let trackID = audioTrack.trackId > 0 ? String(audioTrack.trackId) : "na"
let item = NSMenuItem(title: "\(trackID) - \(audioTrack.name) - \(langs.localizedLang(forExtendedTag: audioTrack.language))",
action: #selector(seTracktFallback(_:)),
keyEquivalent: "")
action: #selector(seTrackFallback(_:)),
keyEquivalent: "")
item.target = self
item.representedObject = audioTrack
fallbacksPopUp.menu?.addItem(item)
@@ -79,8 +83,8 @@ class SoundViewController : NSViewController {
for subTrack in subtitlesTracks {
let trackID = subTrack.trackId > 0 ? String(subTrack.trackId) : "na"
let item = NSMenuItem(title: "\(trackID) - \(subTrack.name) - \(langs.localizedLang(forExtendedTag: subTrack.language))",
action: #selector(setTrackFollows(_:)),
keyEquivalent: "")
action: #selector(setTrackFollows(_:)),
keyEquivalent: "")
item.target = self
item.representedObject = subTrack
followsPopUp.menu?.addItem(item)
@@ -112,7 +116,7 @@ class SoundViewController : NSViewController {
}
}
@IBAction func seTracktFallback(_ sender: NSMenuItem) {
@IBAction func seTrackFallback(_ sender: NSMenuItem) {
if let newFallbackTrack = sender.representedObject as? MP42AudioTrack {
if newFallbackTrack != track.fallbackTrack {
track.fallbackTrack = newFallbackTrack
-24
View File
@@ -1,24 +0,0 @@
//
// SBAppDelegate.h
// Subler
//
// Created by Damiano Galassi on 29/01/09.
// Copyright 2009 Damiano Galassi. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface SBDocumentController : NSDocumentController
@end
@interface SBAppDelegate : NSObject
- (IBAction) showBatchWindow: (id) sender;
- (IBAction) showPrefsWindow: (id) sender;
- (IBAction) donate:(id)sender;
- (IBAction) help:(id)sender;
- (IBAction) linkDonate: (id) sender;
@end
-280
View File
@@ -1,280 +0,0 @@
//
// SBAppDelegate.m
// Subler
//
// Created by Damiano Galassi on 29/01/09.
// Copyright 2009 Damiano Galassi. All rights reserved.
//
#import "SBAppDelegate.h"
#import "SBQueueController.h"
#import "Subler-Swift.h"
#import <MP42Foundation/MP42File.h>
#define DONATE_NAG_TIME (60 * 60 * 24 * 7)
#define DONATE_NAG_TIME_LONG (60 * 60 * 24 * 120)
@interface SBAppDelegate ()
{
SBPrefsWindowController *prefController;
ActivityWindowController *debugLogController;
SBDocumentController *documentController;
}
@end
@implementation SBAppDelegate
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
documentController = [[SBDocumentController alloc] init];
[SBPrefsWindowController registerUserDefaults];
NSString *appSupportPath = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
NSUserDomainMask,
YES).firstObject stringByAppendingPathComponent:@"Subler"];
if (![[NSFileManager defaultManager] fileExistsAtPath:appSupportPath]) {
[[NSFileManager defaultManager] createDirectoryAtPath:appSupportPath withIntermediateDirectories:YES attributes:nil error:NULL];
}
NSString *path = [appSupportPath stringByAppendingPathComponent:@"debugLog.txt"];
Logger *logger = [[Logger alloc] initWithFileURL:[NSURL fileURLWithPath:path]];
[logger clear];
debugLogController = [[ActivityWindowController alloc] initWithLogger:logger];
MP42File.globalLogger = logger;
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"SBShowQueueWindow"]) {
[[SBQueueController sharedManager] showWindow:self];
}
}
- (void)applicationWillTerminate:(NSNotification *)notification {
[SBPresetManager.shared saveAndReturnError:nil];
if ([SBQueueController sharedManager].window.visible) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"SBShowQueueWindow"];
}
else {
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"SBShowQueueWindow"];
}
if (![[SBQueueController sharedManager] saveQueueToDisk]) {
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"Debug"]) {
NSLog(@"Failed to save queue to disk!");
}
}
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)app
{
SBQueueStatus status= SBQueueController.sharedManager.queue.status;
if (status == SBQueueStatusWorking) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = NSLocalizedString(@"Are you sure you want to quit Subler?", @"Quit alert title.");
alert.informativeText = NSLocalizedString(@"Your current queue will be lost. Do you want to quit anyway?", @"Quit alert description.");
[alert addButtonWithTitle:NSLocalizedString(@"Quit", @"Quit alert default action.")];
[alert addButtonWithTitle:NSLocalizedString(@"Don't Quit", @"Quit alert cancel action.")];
alert.alertStyle = NSAlertStyleCritical;
NSInteger result = [alert runModal];
if (result == NSAlertFirstButtonReturn) {
return NSTerminateNow;
}
else {
return NSTerminateCancel;
}
}
return NSTerminateNow;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
BOOL firstLaunch = YES;
if ([NSUserDefaults.standardUserDefaults boolForKey:@"SBFirstLaunch"]) {
firstLaunch = NO;
}
NSString *currentVersion = NSBundle.mainBundle.infoDictionary[@"CFBundleShortVersionString"];
NSString *lastVersion = [NSUserDefaults.standardUserDefaults objectForKey:@"SBDonateAskVersion"];
const BOOL versionChanged = currentVersion != nil && ![currentVersion isEqualTo:lastVersion];
if (versionChanged) {
[NSUserDefaults.standardUserDefaults setObject:currentVersion forKey:@"SBDonateAskVersion"];
NSDate *lastDonateDate = [NSUserDefaults.standardUserDefaults objectForKey:@"SBDonateAskDate"];
const BOOL timePassed = !lastDonateDate || (-1 * lastDonateDate.timeIntervalSinceNow) >= DONATE_NAG_TIME_LONG;
if (timePassed) {
[NSUserDefaults.standardUserDefaults removeObjectForKey:@"SBWarningDonate"];
[NSUserDefaults.standardUserDefaults removeObjectForKey:@"SBFirstLaunch"];
[NSUserDefaults.standardUserDefaults removeObjectForKey:@"SBDonateAskDate"];
}
}
if (![NSUserDefaults.standardUserDefaults boolForKey:@"SBWarningDonate"]) {
NSDate *lastDonateDate = [NSUserDefaults.standardUserDefaults objectForKey:@"SBDonateAskDate"];
const BOOL timePassed = !lastDonateDate || (-1 * lastDonateDate.timeIntervalSinceNow) >= DONATE_NAG_TIME;
if (!firstLaunch && timePassed) {
[NSUserDefaults.standardUserDefaults setObject:[NSDate date] forKey:@"SBDonateAskDate"];
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = NSLocalizedString(@"Support Subler", "Donation -> title");
NSString *donateMessage = [NSString stringWithFormat: @"%@",
NSLocalizedString(@" A lot of time and effort have gone into development, coding, and refinement."
" If you enjoy using it, please consider showing your appreciation with a donation.", "Donation -> message")];
alert.informativeText = donateMessage;
alert.alertStyle = NSAlertStyleInformational;
[alert addButtonWithTitle: NSLocalizedString(@"Donate", "Donation -> button")];
NSButton *noDonateButton = [alert addButtonWithTitle: NSLocalizedString(@"Nope", "Donation -> button")];
noDonateButton.keyEquivalent = [NSString stringWithFormat:@"%c", 0x1B]; //escape key
const BOOL allowAgain = lastDonateDate != nil; //hide the "don't show again" check the first time - give them time to try the app
alert.showsSuppressionButton = allowAgain;
if (allowAgain) {
alert.suppressionButton.title = NSLocalizedString(@"Don't ask me about this again for this version.", "Donation -> button");
}
const NSInteger donateResult = [alert runModal];
if (donateResult == NSAlertFirstButtonReturn) {
[self linkDonate:self];
}
if (allowAgain) {
[NSUserDefaults.standardUserDefaults setBool:(alert.suppressionButton.state != NSOnState) forKey:@"SBWarningDonate"];
}
}
}
if (firstLaunch) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"SBFirstLaunch"];
}
[SBQueueController sharedManager];
}
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender
{
return NO;
}
- (IBAction)openInQueue:(id)sender
{
[[SBQueueController sharedManager] showWindow:self];
[[SBQueueController sharedManager] open:sender];
}
- (IBAction) showBatchWindow: (id) sender
{
[[SBQueueController sharedManager] showWindow:self];
}
- (IBAction) showPrefsWindow: (id) sender
{
if (!prefController) {
prefController = [[SBPrefsWindowController alloc] init];
}
[prefController showWindow:self];
}
- (IBAction) showDebugLog:(id)sender
{
[debugLogController showWindow:self];
}
- (IBAction) donate:(id)sender
{
[self linkDonate:sender];
}
- (IBAction) help:(id)sender
{
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://bitbucket.org/galad87/subler/wiki/Home"]];
}
- (IBAction) linkDonate:(id)sender
{
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://subler.org/donate.php"]];
}
@end
@implementation SBAppDelegate (QueueScripting)
- (BOOL)application:(NSApplication *)sender delegateHandlesKey:(NSString *)key
{
if ([key isEqualToString:@"items"]) {
return YES;
}
else {
return NO;
}
}
- (NSArray<SBQueueItem *> *)items
{
SBQueue *queue = SBQueueController.sharedManager.queue;
NSMutableArray<SBQueueItem *> *items = [NSMutableArray array];
for (NSUInteger i = 0; i < queue.count; i++) {
[items addObject:[queue itemAtIndex:i]];
}
return items;
}
- (void)insertObject:(SBQueueItem *)object inItemsAtIndex:(NSUInteger)index
{
[SBQueueController.sharedManager.queue insertItem:object atIndex:index];
}
- (void)removeObjectFromItemsAtIndex:(NSUInteger)index
{
[SBQueueController.sharedManager.queue removeItemsAtIndexes:[NSIndexSet indexSetWithIndex:index]];
}
@end
@implementation SBDocumentController
- (void)openDocumentWithContentsOfURL:(NSURL * _Nonnull)url
display:(BOOL)displayDocument
completionHandler:(void (^ _Nonnull)(NSDocument * _Nullable document,
BOOL documentWasAlreadyOpen,
NSError * _Nullable error))completionHandler
{
NSString *extension = url.pathExtension.lowercaseString;
if ([extension isEqualToString: @"mkv"] ||
[extension isEqualToString: @"mka"] ||
[extension isEqualToString: @"mks"] ||
[extension isEqualToString: @"mov"]) {
NSError *outError = nil;
SBDocument *doc = [self openUntitledDocumentAndDisplay:displayDocument error:&outError];
completionHandler(doc, NO, outError);
if (doc) {
[doc.windowControllers.firstObject showImportSheetWithFileURLs:@[url]];
}
}
else {
[super openDocumentWithContentsOfURL:url display:displayDocument completionHandler:completionHandler];
}
}
@end