<commit_before>//
//  AppDelegate.swift
//
//  This file is part of LyricsX
//  Copyright (C) 2017 <NAME> - https://github.com/ddddxxx/LyricsX
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

import Cocoa
import ScriptingBridge

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    
    var musicPlayer: SBApplication?
    var shouldWaitForPlayerQuit = false

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        guard groupDefaults.bool(forKey: LaunchAndQuitWithPlayer) else {
            NSApplication.shared.terminate(nil)
            abort() // fake invoking, just make compiler happy.
        }
        
        let index = groupDefaults.integer(forKey: PreferredPlayerIndex)
        let ident = playerBundleIdentifiers[index]
        musicPlayer = SBApplication(bundleIdentifier: ident)
        
        let isLaunchedByMain = (groupDefaults.object(forKey: launchHelperTime) as? Date)?.timeIntervalSinceNow ?? -11 > -10
        shouldWaitForPlayerQuit = isLaunchedByMain && (musicPlayer?.isRunning == true)
        
        NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(checkiTunes), name: NSWorkspace.didLaunchApplicationNotification, object: nil)
        NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(checkiTunes), name: NSWorkspace.didTerminateApplicationNotification, object: nil)
    }
    
    @objc func checkiTunes() {
        if self.shouldWaitForPlayerQuit {
            self.shouldWaitForPlayerQuit = self.musicPlayer?.isRunning == true
            return
        }
        if self.musicPlayer?.isRunning == true {
            self.launchMainAndQuit()
        }
    }

    func launchMainAndQuit() -> Never {
        var host = Bundle.main.bundleURL
        for _ in 0..<4 {
            host.deleteLastPathComponent()
        }
        do {
            try NSWorkspace.shared.launchApplication(at: host, configuration: [:])
            NSLog("launch LyricsX succeed.")
        } catch {
            NSLog("launch LyricsX failed. reason: \(error)")
        }
        NSApp.terminate(nil)
        abort() // fake invoking, just make compiler happy.
    }

}

let playerBundleIdentifiers = [
    "com.apple.iTunes",
    "com.spotify.client",
    "com.coppertino.Vox",
]

let groupDefaults = UserDefaults(suiteName: "3665V726AE.group.ddddxxx.LyricsX")!

// Preference
let PreferredPlayerIndex = "PreferredPlayerIndex"
let LaunchAndQuitWithPlayer = "LaunchAndQuitWithPlayer"
let launchHelperTime = "launchHelperTime"

<commit_msg>fix: cannot start with iTunes when iTunes was launched as login item, #96<commit_after>//
//  AppDelegate.swift
//
//  This file is part of LyricsX
//  Copyright (C) 2017 <NAME> - https://github.com/ddddxxx/LyricsX
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

import Cocoa
import ScriptingBridge

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    
    var musicPlayer: SBApplication?
    var shouldWaitForPlayerQuit = false

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        guard groupDefaults.bool(forKey: LaunchAndQuitWithPlayer) else {
            NSApplication.shared.terminate(nil)
            abort() // fake invoking, just make compiler happy.
        }
        
        let index = groupDefaults.integer(forKey: PreferredPlayerIndex)
        let ident = playerBundleIdentifiers[index]
        musicPlayer = SBApplication(bundleIdentifier: ident)
        
        let event = NSAppleEventManager.shared().currentAppleEvent
        let isLaunchedAsLoginItem = event?.eventID == kAEOpenApplication && event?.paramDescriptor(forKeyword: keyAEPropData)?.enumCodeValue == keyAELaunchedAsLogInItem
        let isLaunchedByMain = (groupDefaults.object(forKey: launchHelperTime) as? Date).map { Date().timeIntervalSince($0) < 10 } ?? false
        shouldWaitForPlayerQuit = !isLaunchedAsLoginItem && isLaunchedByMain && (musicPlayer?.isRunning == true)
        
        NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(checkiTunes), name: NSWorkspace.didLaunchApplicationNotification, object: nil)
        NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(checkiTunes), name: NSWorkspace.didTerminateApplicationNotification, object: nil)
        
        checkiTunes()
    }
    
    @objc func checkiTunes() {
        if self.shouldWaitForPlayerQuit {
            self.shouldWaitForPlayerQuit = self.musicPlayer?.isRunning == true
            return
        }
        if self.musicPlayer?.isRunning == true {
            self.launchMainAndQuit()
        }
    }

    func launchMainAndQuit() -> Never {
        var host = Bundle.main.bundleURL
        for _ in 0..<4 {
            host.deleteLastPathComponent()
        }
        do {
            try NSWorkspace.shared.launchApplication(at: host, configuration: [:])
            NSLog("launch LyricsX succeed.")
        } catch {
            NSLog("launch LyricsX failed. reason: \(error)")
        }
        NSApp.terminate(nil)
        abort() // fake invoking, just make compiler happy.
    }

}

let playerBundleIdentifiers = [
    "com.apple.iTunes",
    "com.spotify.client",
    "com.coppertino.Vox",
]

let groupDefaults = UserDefaults(suiteName: "3665V726AE.group.ddddxxx.LyricsX")!

// Preference
let PreferredPlayerIndex = "PreferredPlayerIndex"
let LaunchAndQuitWithPlayer = "LaunchAndQuitWithPlayer"
let launchHelperTime = "launchHelperTime"


{'fraction_non_alphanumeric': 0.09132965229070288, 'fraction_numerical': 0.005521563945679749, 'mean_word_length': 3.0107719928186714, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6589138', 'n_tokens_mistral': 1900, 'n_tokens_neox': 1834, 'n_words': 512}