<commit_before>//  TouchBarHelper.swift
//  Pock
//
//  Created by <NAME> on 04/01/2020.
//  Copyright © 2020 <NAME>. All rights reserved.
//

import CoreFoundation
import Defaults

private let kPresentationModeGlobal  = "PresentationModeGlobal"   as CFString
private let kTouchBarAgentIdentifier = "com.apple.touchbar.agent" as CFString

private class CommandLineHelper {
	@discardableResult
	static func execute(launchPath: String, arguments: [String]) -> String? {
		let task = Process()
		task.launchPath = launchPath
		task.arguments = arguments
		let pipe = Pipe()
		task.standardOutput = pipe
		task.launch()
		let data = pipe.fileHandleForReading.readDataToEndOfFile()
		let output = String(data: data, encoding: String.Encoding.utf8)
		return output
	}
}

public enum PresentationMode: String {
	case app,
		 appWithControlStrip,
		 fullControlStrip,
		 functionKeys,
		 workflows,
		 workflowsWithControlStrip,
		 spaces,
		 spacesWithControlStrip
	public var hasControlStrip: Bool {
		switch self {
		case .appWithControlStrip, .workflowsWithControlStrip, .spacesWithControlStrip:
			return true
		default:
			return false
		}
	}
	/// statics
	static let `default` = PresentationMode.appWithControlStrip
}

public class TouchBarHelper {

	// MARK: Pock internal's helpers

	public static var isSystemControlStripVisible: Bool {
		return TouchBarHelper.currentPresentationMode.hasControlStrip
	}

	public static var currentPresentationMode: PresentationMode {
		guard let value = (CFPreferencesCopyAppValue(kPresentationModeGlobal, kTouchBarAgentIdentifier) as? NSObject)?.copy(),
			  let mode  = value as? String else {
			return .default
		}
		return PresentationMode(rawValue: mode) ?? .default
	}

	@discardableResult
	internal static func setPresentationMode(to mode: PresentationMode) -> Bool {
		guard currentPresentationMode != mode else {
			Roger.debug("Touch Bar Presentation mode already setted to: \(mode)")
			return false
		}
		let currentMode = currentPresentationMode
		CFPreferencesSetAppValue(kPresentationModeGlobal, mode.rawValue as CFString, kTouchBarAgentIdentifier)
		let result = CFPreferencesAppSynchronize(kTouchBarAgentIdentifier)
		reloadTouchBarAgent()
		Roger.debug("Touch Bar Presentation mode changed: [\(result ? "success" : "error")] \(currentMode) -> \(mode)")
		return result
	}
	
	@objc public static func markTouchBarAsDimmed(_ dimmed: Bool) {
		NSFunctionRow.markActiveFunctionRows(asDimmed: dimmed)
	}
	
	@objc public static func hideCloseButtonIfNeeded() {
		if let view = NSFunctionRow._topLevelViews().first(where: {
			object_getClass($0) === NSClassFromString("NSFunctionRowBackgroundColorView")
		}) as? NSView,
		   let stackView = view.subviews.first(where: { $0 is NSStackView }) as? NSStackView,
		   let closeButton = stackView.subviews.first(where: { $0 is NSButton }) {
			closeButton.isHidden = true
		}
	}

	@objc public static func reloadTouchBarAgent(_ completion: ((Bool) -> Void)? = nil) {
		let result = CommandLineHelper.execute(launchPath: "/usr/bin/pkill", arguments: ["ControlStrip"])
		completion?(result != nil)
	}

	internal static func reloadTouchBarServer(_ completion: ((Bool) -> Void)? = nil) {
		let touchBarServerPid = _DFRGetServerPID().description
		var task = STPrivilegedTask(launchPath: "/bin/kill", arguments: [touchBarServerPid])
		defer {
			task?.terminate()
			task = nil
		}
		guard let error = task?.launch() else {
			completion?(false)
			return
		}
		async(after: 1.5) { [touchBarServerPid, error] in
			switch error {
			case errAuthorizationSuccess:
				completion?(true)
			default:
				completion?(false)
			}
			Roger.debug("[TouchBarServer]: old_pid: `\(touchBarServerPid)` - new_pid: `\(_DFRGetServerPID().description)`")
		}
	}

	// MARK: NSTouchBar helpers
	@objc public static func presentOnTop(_ touchBar: NSTouchBar?) {
		guard let touchBar = touchBar else {
			return
		}
		if #available (macOS 10.14, *) {
			NSTouchBar.presentSystemModalTouchBar(touchBar, placement: 1, systemTrayItemIdentifier: nil)
		} else {
			NSTouchBar.presentSystemModalFunctionBar(touchBar, placement: 1, systemTrayItemIdentifier: nil)
		}
	}

	@objc public static func dismissFromTop(_ touchBar: NSTouchBar?) {
		guard let touchBar = touchBar else {
			return
		}
		if #available (macOS 10.14, *) {
			NSTouchBar.dismissSystemModalTouchBar(touchBar)<commit_msg>fix: increase waiting time after TouchBar relaunch<commit_after>//  TouchBarHelper.swift
//  Pock
//
//  Created by <NAME> on 04/01/2020.
//  Copyright © 2020 <NAME>. All rights reserved.
//

import CoreFoundation
import Defaults

private let kPresentationModeGlobal  = "PresentationModeGlobal"   as CFString
private let kTouchBarAgentIdentifier = "com.apple.touchbar.agent" as CFString

private class CommandLineHelper {
	@discardableResult
	static func execute(launchPath: String, arguments: [String]) -> String? {
		let task = Process()
		task.launchPath = launchPath
		task.arguments = arguments
		let pipe = Pipe()
		task.standardOutput = pipe
		task.launch()
		let data = pipe.fileHandleForReading.readDataToEndOfFile()
		let output = String(data: data, encoding: String.Encoding.utf8)
		return output
	}
}

public enum PresentationMode: String {
	case app,
		 appWithControlStrip,
		 fullControlStrip,
		 functionKeys,
		 workflows,
		 workflowsWithControlStrip,
		 spaces,
		 spacesWithControlStrip
	public var hasControlStrip: Bool {
		switch self {
		case .appWithControlStrip, .workflowsWithControlStrip, .spacesWithControlStrip:
			return true
		default:
			return false
		}
	}
	/// statics
	static let `default` = PresentationMode.appWithControlStrip
}

public class TouchBarHelper {

	// MARK: Pock internal's helpers

	public static var isSystemControlStripVisible: Bool {
		return TouchBarHelper.currentPresentationMode.hasControlStrip
	}

	public static var currentPresentationMode: PresentationMode {
		guard let value = (CFPreferencesCopyAppValue(kPresentationModeGlobal, kTouchBarAgentIdentifier) as? NSObject)?.copy(),
			  let mode  = value as? String else {
			return .default
		}
		return PresentationMode(rawValue: mode) ?? .default
	}

	@discardableResult
	internal static func setPresentationMode(to mode: PresentationMode) -> Bool {
		guard currentPresentationMode != mode else {
			Roger.debug("Touch Bar Presentation mode already setted to: \(mode)")
			return false
		}
		let currentMode = currentPresentationMode
		CFPreferencesSetAppValue(kPresentationModeGlobal, mode.rawValue as CFString, kTouchBarAgentIdentifier)
		let result = CFPreferencesAppSynchronize(kTouchBarAgentIdentifier)
		reloadTouchBarAgent()
		Roger.debug("Touch Bar Presentation mode changed: [\(result ? "success" : "error")] \(currentMode) -> \(mode)")
		return result
	}
	
	@objc public static func markTouchBarAsDimmed(_ dimmed: Bool) {
		NSFunctionRow.markActiveFunctionRows(asDimmed: dimmed)
	}
	
	@objc public static func hideCloseButtonIfNeeded() {
		if let view = NSFunctionRow._topLevelViews().first(where: {
			object_getClass($0) === NSClassFromString("NSFunctionRowBackgroundColorView")
		}) as? NSView,
		   let stackView = view.subviews.first(where: { $0 is NSStackView }) as? NSStackView,
		   let closeButton = stackView.subviews.first(where: { $0 is NSButton }) {
			closeButton.isHidden = true
		}
	}

	@objc public static func reloadTouchBarAgent(_ completion: ((Bool) -> Void)? = nil) {
		let result = CommandLineHelper.execute(launchPath: "/usr/bin/pkill", arguments: ["ControlStrip"])
		completion?(result != nil)
	}

	internal static func reloadTouchBarServer(_ completion: ((Bool) -> Void)? = nil) {
		let touchBarServerPid = _DFRGetServerPID().description
		var task = STPrivilegedTask(launchPath: "/bin/kill", arguments: [touchBarServerPid])
		defer {
			task?.terminate()
			task = nil
		}
		guard let error = task?.launch() else {
			completion?(false)
			return
		}
		async(after: 2.525) { [touchBarServerPid, error] in
			switch error {
			case errAuthorizationSuccess:
				completion?(true)
			default:
				completion?(false)
			}
			Roger.debug("[TouchBarServer]: old_pid: `\(touchBarServerPid)` - new_pid: `\(_DFRGetServerPID().description)`")
		}
	}

	// MARK: NSTouchBar helpers
	@objc public static func presentOnTop(_ touchBar: NSTouchBar?) {
		guard let touchBar = touchBar else {
			return
		}
		if #available (macOS 10.14, *) {
			NSTouchBar.presentSystemModalTouchBar(touchBar, placement: 1, systemTrayItemIdentifier: nil)
		} else {
			NSTouchBar.presentSystemModalFunctionBar(touchBar, placement: 1, systemTrayItemIdentifier: nil)
		}
	}

	@objc public static func dismissFromTop(_ touchBar: NSTouchBar?) {
		guard let touchBar = touchBar else {
			return
		}
		if #available (macOS 10.14, *) {
			NSTouchBar.dismissSystemModalTouchBar(touchBar)
{'fraction_non_alphanumeric': 0.10099508177970948, 'fraction_numerical': 0.006633878531396546, 'mean_word_length': 4.608723540731238, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '7128554', 'n_tokens_mistral': 2997, 'n_tokens_neox': 2673, 'n_words': 669}