首页 > 解决方案 > 有没有办法将 AppleScript 的输出设置为某种颜色,并根据条件进行更改?

问题描述

我有一个功能正常的脚本,它查看特定应用程序中的活动状态,以及在该状态下花费的时间,然后将其显示在 macOS 的状态栏中。它按预期工作,但我想添加一些颜色,以便如果您在某种状态下经过一定时间,文本会变成黄色或红色。例如,我可能处于空闲状态 8 分钟,它显示在状态栏中,但是当它达到 10 分钟时,我希望文本从白色变为红色。

我对“属性范围”功能进行了一些研究,但我不确定如何将其应用(或是否可以应用)到我的脚本,因为我不使用 Pages、Microsoft Word、文本编辑,或类似的东西,只是一个返回到状态栏的值。

on idle
    -- Update the status item's text here.
    tell application "System Events"
        if not (exists process appName) then
            display alert "Application " & appName & " is not running" as warning giving up after 6
            quit me
        end if
        tell process appName
            -- assume the window and toolbar are always going to be there
            repeat until exists of first window's first toolbar's fourth group's first group's first menu button
                delay 0.2
            end repeat
            tell first window's first toolbar's fourth group's first group's first menu button
                set activityState to first item of (value as list) as text
            end tell
        end tell
    end tell

    set statusItem's button's title to activityState

    (*
      The return value gives the time in seconds
    *)
    return 1
end idle

我想知道是否可以使用命令将“activityState”属性设置为某种颜色,因为该变量已定义到受影响的应用程序 GUI 的适当区域,然后设置条件以根据类型进行更改活动状态,以及在那里花费的时间。

标签: macoscolorsapplescript

解决方案


属性字符串可用于状态项标题:

set greenAttr to current application's NSDictionary's dictionaryWithObjects:{current application's NSColor's greenColor()} forKeys:{current application's NSForegroundColorAttributeName}
set redAttr to current application's NSDictionary's dictionaryWithObjects:{current application's NSColor's redColor()} forKeys:{current application's NSForegroundColorAttributeName}

set attrText to current application's NSMutableAttributedString's alloc's initWithString:"whatever"
attrText's setAttributes:greenAttr range:{0, attrText's |length|()}
statusItem's button's setAttributedTitle:attrText

然后在某些时候可以更改或替换属性,并使用新的属性字符串设置标题:

if elapsedTime > someTime then attrText's setAttributes:redAttr range:{0, attrText's |length|()}
statusItem's button's setAttributedTitle:attrText

推荐阅读