Как приостановить и возобновить AppleScript без диалогового окна? - PullRequest
0 голосов
/ 22 января 2020

Я работаю, чтобы наметить рабочий процесс в AppleScript. Сценарий берет следующую задачу, которую мне нужно сделать, от Omnifocus и требует, чтобы я определил, могу ли я сделать это за 2 минуты или меньше. Если я могу, он запускает таймер, и я хочу подождать, пока я действительно выполню задачу. Прямо сейчас у меня всплывающее диалоговое окно, и я могу пометить задачу, когда я закончил с этим. К сожалению, некоторые из задач, которые мне нужно выполнить, находятся в Omnifocus, и я ничего не могу сделать в Omnifocus при открытом диалоговом окне.

Я бы не хотел использовать диалоговое окно, чтобы я мог работать в Omnifocus во время работы скрипта. Я хотел бы быть в состоянии сказать сценарию, что я сделал, чтобы он мог остановить таймер, сказать мне, сколько времени потребовалось для выполнения задачи, а затем go, чтобы отметить выполнение задачи в Omnifocus. Сначала я думал, что лучший способ сделать это - ввести комбинацию клавиш. После небольшого исследования я не думаю, что смогу сделать это в AppleScript. Я открыт для любой идеи о том, как разрешить мне работать в середине моего сценария, а затем сообщить программе, что я выполнил задание.

Вот мой код:

on run {}
    with timeout of (30 * 60) seconds
        tell application "OmniFocus"
            activate
        end tell
        tell application "OmniFocus"
            tell default document to tell front document window
                set perspective name to "Daily Wrap-Up"
                tell content to set TreeList to (value of first leaf)
                repeat with ListItem in TreeList
                    set ProjectName to name of containing project of ListItem as text
                    set TaskName to " - " & name of ListItem
                    set NoteName to " - " & note of ListItem
                    display dialog "The task is:" & return & ProjectName & TaskName & NoteName & return & "Can you do this in 2 minutes or less?" buttons {"Yes", "No"} default button "Yes"
                    set Button_Returned to button returned of result
                    if Button_Returned = "Yes" then

                        say "Get to work!"


                        set T1 to minutes of (current date)

                        set T1s to seconds of (current date)


                        display dialog "Click when done." buttons {"Complete", "Cancel"} default button "Complete"
                        set Button_Returned to button returned of result

                        if Button_Returned = "Complete" then



                            set T2 to minutes of (current date)

                            set T2s to seconds of (current date)

                            set TT_ to ((T2 * 60) + T2s) - ((T1 * 60) + T1s)

                            say "that took you" & TT_ & "seconds to complete"
                            display dialog ProjectName & TaskName & NoteName buttons {"Complete", "Defer", "Cancel"} default button "Complete"
                            set Button_Returned to button returned of result
                            if Button_Returned = "Complete" then
                                mark complete ListItem
                                tell application "OmniFocus"
                                    compact default document
                                end tell
                            else if Button_Returned = "Defer" then
                                display dialog "Defer for how long (in minutes)?" default answer "60"
                                set TimeAdd to text returned of result
                                set defer date of ListItem to ((current date) + (TimeAdd * minutes))
                                tell application "OmniFocus"
                                    compact default document
                                end tell
                            else if Button_Returned = "Cancel" then
                                tell application "OmniFocus"
                                    compact default document
                                end tell
                            else if Button_Returned = "No" then
                                tell application "OmniFocus"
                                    compact default document
                                end tell
                            end if
                        else if Button_Returned = "No" then
                            display dialog "Breakdown task."

                            set perspective name to "Projects"


                        end if
                    end if
                end repeat
            end tell
        end tell
    end timeout
end run

Заранее благодарен за любую помощь.

1 Ответ

0 голосов
/ 22 января 2020

У меня нет OmniFocus на моей машине, поэтому я не могу правильно скомпилировать этот тест, а тем более протестировать его, но в ванильном AppleScript вы можете сделать что-то вроде следующего:

global start_time, end_time, TreeList, current_task_index, TaskName, NoteName

on run
    tell application "OmniFocus"
        tell default document to tell front document window
            set perspective name to "Daily Wrap-Up"
            tell content to set TreeList to (value of first leaf)
        end 
    end
    set current_task_index to 1
    beginTask()
end

on reopen
    -- inserted try block to aid debugging
    try
        set end_time to (current date)
        set elapsed_time to end_time -start_time
        say "that took you " & elapsed_time & " seconds to complete"
        display dialog ProjectName & TaskName & NoteName buttons {"Complete", "Defer", "Cancel"} default button "Complete"
        set Button_Returned to button returned of result
            if Button_Returned = "Complete" then
                mark complete ListItem
                tell application "OmniFocus"
                    compact default document
                end tell
            else if Button_Returned = "Defer" then
                display dialog "Defer for how long (in minutes)?" default answer "60"
                set TimeAdd to text returned of result
                set defer date of ListItem to ((current date) + (TimeAdd * minutes))
                tell application "OmniFocus"
                    compact default document
                end tell
            else if Button_Returned = "Cancel" then
                tell application "OmniFocus"
                    compact default document
                end tell
            else if Button_Returned = "No" then
                tell application "OmniFocus"
                    compact default document
                end tell
            end if
        else if Button_Returned = "No" then
            display dialog "Breakdown task."
            set perspective name to "Projects"
        end if
        set current_task_index to current_task_index + 1
        if current_task_index <= count of TreeList then
            beginTask()
        else
            quit
        end
    on error errstr number errnum
        display alert "Error " & errnum & ": " & errstr
    end try
end

on idle
    (*
        you can use this handler if you want the app to give you a countdown, or 
        announce a time limit, or anything that needs doing while you're working on the task
    *)
end

on beginTask()
    tell application "OmniFocus"
        tell default document to tell front document window
            set perspective name to "Daily Wrap-Up"
            set ListItem to item current_task_index of TreeList
            set ProjectName to name of containing project of ListItem as text
            set TaskName to " - " & name of ListItem
            set NoteName to " - " & note of ListItem
            display dialog "The task is:" & return & ProjectName & TaskName & NoteName & return & "Can you do this in 2 minutes or less?" buttons {"Yes", "No"} default button "Yes"
            set Button_Returned to button returned of result
            if Button_Returned = "Yes" then
                say "Get to work!"
                set start_time to (current date)
            end if
        end tell
    end tell
end

Скопируйте это в Редактор сценариев, отладьте его и сохраните как приложение с установленным флажком «Оставаться открытым после запуска». Операция выполняется следующим образом:

  1. Когда OmniFocus готов, запустите это приложение-скрипт. Он предложит вам начать первое задание.
  2. Когда вы завершите первое задание, снова дважды щелкните значок приложения сценария, чтобы вызвать обработчик reopen. Сценарий предоставит вам истекшее время для первого задания, даст вам варианты, которые вы обрисовали в общих чертах, а затем предложит вам начать второе задание.
  3. После завершения последней задачи сценарий автоматически завершит работу.

Глобальная переменная в начале позволяет передавать необходимые данные между обработчиками по мере выполнения сценария.

Если вы хотите что-то более сложное - например, плавающее окно или элемент строки меню, который дает вам более детальный контроль - тогда вам нужно начать использовать ASO C для его создания. Но это тонкая настройка; это должно дать вам общую структуру.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...