From 352bf4887cec1007f524663e08714d9a0909445c Mon Sep 17 00:00:00 2001 From: ash14 Date: Thu, 16 Sep 2021 23:49:09 +0800 Subject: [PATCH] Parse title/image from a script's output (#418) --- MTMR/ShellScriptTouchBarItem.swift | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/MTMR/ShellScriptTouchBarItem.swift b/MTMR/ShellScriptTouchBarItem.swift index 4fd51f3..13da0cc 100644 --- a/MTMR/ShellScriptTouchBarItem.swift +++ b/MTMR/ShellScriptTouchBarItem.swift @@ -12,6 +12,11 @@ class ShellScriptTouchBarItem: CustomButtonTouchBarItem { private let source: String private var forceHideConstraint: NSLayoutConstraint! + struct ScriptResult: Decodable { + var title: String? + var image: Source? + } + init?(identifier: NSTouchBarItem.Identifier, source: SourceProtocol, interval: TimeInterval) { self.interval = interval self.source = source.string ?? "echo No \"source\"" @@ -31,12 +36,25 @@ class ShellScriptTouchBarItem: CustomButtonTouchBarItem { func refreshAndSchedule() { // Execute script and get result let scriptResult = execute(source) - + var rawTitle: String, image: NSImage? + var json: Bool + + do { + let decoder = JSONDecoder() + let result = try decoder.decode(ScriptResult.self, from: scriptResult.data(using: .utf8)!) + json = true + rawTitle = result.title ?? "" + image = result.image?.image + } catch { + json = false + rawTitle = scriptResult + } + // Apply returned text attributes (if they were returned) to our result string let helper = AMR_ANSIEscapeHelper.init() helper.defaultStringColor = NSColor.white helper.font = "1".defaultTouchbarAttributedString.attribute(.font, at: 0, effectiveRange: nil) as? NSFont - let title = NSMutableAttributedString.init(attributedString: helper.attributedString(withANSIEscapedString: scriptResult) ?? NSAttributedString(string: "")) + let title = NSMutableAttributedString.init(attributedString: helper.attributedString(withANSIEscapedString: rawTitle) ?? NSAttributedString(string: "")) title.addAttributes([.baselineOffset: 1], range: NSRange(location: 0, length: title.length)) let newBackgoundColor: NSColor? = title.length != 0 ? title.attribute(.backgroundColor, at: 0, effectiveRange: nil) as? NSColor : nil @@ -46,6 +64,9 @@ class ShellScriptTouchBarItem: CustomButtonTouchBarItem { self?.backgroundColor = newBackgoundColor } self?.attributedTitle = title + if json { + self?.image = image + } self?.forceHideConstraint.isActive = scriptResult == "" }