получите индекс предпоследнего окна с помощью applescript

#applescript

Вопрос:

У меня возникли проблемы с согласованием этих дел. 3 и 4 точно такие же, за исключением приложения. То же самое для 5 и 6. Я также заменил safari на brave. Похоже, они работают одинаково. textedit также, похоже, работает так же, как и другие. Это просто особый случай или происходит что-то еще?

 # Case 1) Give tell a string, get last window index: succeeds.
tell application "finder"
    get index of last window
end tell

# Case 2) Give tell a variable, get last window index: succeeds.
set the_application to "finder"
function_a(the_application)
on function_a(the_application)
    tell application the_application
        get index of last window
    end tell
end function_a

# Case 3) Give tell a variable, get next-to-last window index for finder: fails.
# 651:656: execution error: Finder got an error: Can’t get window before Finder window id 63457. (-1728)
set the_application to "finder"
function_b(the_application)
on function_b(the_application)
    tell application the_application
        get index of window before last window
    end tell
end function_b


# Case 4) Give tell a variable, get next-to-last window index for safari: succeeds.
set the_application to "safari"
function_c(the_application)
on function_c(the_application)
    tell application the_application
        get index of window before last window
    end tell
end function_c

# Case 5) Give tell a string, get next-to-last window index: succeeds.
tell application "safari"
    get index of window before last window
end tell

# Case 6) Give tell a string, get next-to-last window index: fails.
1420:1425: execution error: Finder got an error: Can’t get window before Finder window id 63457. (-1728)
tell application "finder"
    get index of window before last window
end tell

# Case 7) Give tell a string, get next-to-last finder window index: succeeds.
tell application "finder"
    get index of finder window before last window
end tell

 

Ответ №1:

Любое приложение, написанное по сценарию, имеет уникальный словарь AppleScript.

Конечно, приложения могут иметь что-то общее, например окна и документы, но реализация windows элемента и обработка индексов индивидуальны. Нет общего соглашения о том, как это сделать. Даже свойства с одним и тем же именем могут иметь разные четырехсимвольные коды (внутренний идентификатор терминологии) в разных приложениях.

Например, NSPositionalSpecifier должен быть явно реализован в целевом приложении, чтобы иметь возможность использовать before/after синтаксис.

В моем варианте попытка написать повторно используемые сценарии для нескольких приложений-пустая трата времени.

Комментарии:

1. Спасибо, вадиан. Мне пришла в голову эта мысль. Я думаю, что если я просто предположу, что у каждого приложения есть совершенно другая команда для выполнения одного и того же действия, я буду в порядке. В конце концов, я не использую так много приложений. У меня просто есть желание попытаться обобщить вещи. Иногда это хорошо, иногда плохо.

Ответ №2:

Я покажу вам решение для Сафари в качестве примера.

Случай ПЕРВЫЙ (возможно, это ваш случай): в настройках вашего Safari указано «открывать новые окна как windows».:

 set the_application to "Safari"
function_c(the_application)

on function_c(the_application)
    run script "tell application "" amp; the_application amp; ""
get index of window before last window
    end tell"
end function_c
 

Случай ВТОРОЙ (если в настройках Safari указано «открывать новые окна как вкладки»):

 set the_application to "Safari"
function_c(the_application)

on function_c(the_application)
    run script "tell application "" amp; the_application amp; ""
get index of tab before last tab of window 1
    end tell"
end function_c
 

Ответ №3:

То же самое, что и в приведенном выше коде, но для нескольких приложений:

 set the_application to choose from list {"Safari", "Finder", "TextEdit"}
if the_application is false then return

set the_application to item 1 of the_application
function_c(the_application)

on function_c(the_application)
    run script "tell application "" amp; the_application amp; ""
get index of last window
end tell"
end function_c
 

Комментарии:

1. Спасибо, Роберт. Это полезно. Но если это работает для некоторых приложений, а не для других, я думаю, что делаю это неправильно. Я пытаюсь создать библиотеку простых действий applescript, а затем, надеюсь, связать или объединить их вместе.

Ответ №4:

Другой прекрасный пример:

 return {|Safari|:function_c("Safari"), |Finder|:function_c("Finder"), |TextEdit|:function_c("TextEdit")}

on function_c(the_application)
    try
        run script "tell application "" amp; the_application amp; ""
get index of last window
end tell"
    on error
        return missing value
    end try
end function_c