Search code examples
applescriptwindow-management

How to get the title of the current Aquamacs window using applescript


I'm trying to programmatically retrieve the major mode of aquamacs. I had a few ideas: get the menubar items, get the window title and parse it using regexes.

I've tried both, and ran into a problem, both the menubar and window arrays are empty, which makes it impossible to do this:

on test()
try
    tell application "System Events"
        if application "Aquamacs" exists then
            -- display notification "It's aquamacs"
            tell application "Aquamacs" to activate
            if menu bar item "File" of menu bar 1 exists then
                display notification "File exists"
                --Fails when the file menu bar item clearly is there
            else
                display notification "File doesn't exist"
            end if
        else
            display notification "It isn't aquamacs"
        end if
    end tell

end try
end test

test()

or this:

on getAppTitle(appN)

tell application appN
    activate
end tell

tell application "System Events"
    # Get the frontmost app's *process* object.
    set frontAppProcess to first application process whose frontmost is true
end tell

# Tell the *process* to count its windows and return its front window's name.
tell frontAppProcess
    if (count of windows) > 0 then --never runs because count is always zero
    set window_name to name of every window

    end if
end tell
end getAppTitle

getAppTitle("Aquamacs")

and then looking at the file extension.

I don't understand why there's such inconsistency between the system and AppleScript: it clearly has windows which definitely have titles, yet somehow are out of reach of scripts.


Solution

  • The problem is in your code!

    In the first block of code, you have if menu bar item "File" of menu bar 1 exists then inside of a tell application "System Events" block without any designated application or application process to query for that information and why it fails.

    In the first block of code, there is more then one way to fix it, and one is to change:

    if menu bar item "File" of menu bar 1 exists then
    

    To:

    if menu bar item "File" of menu bar 1 of application process "Aquamacs" exists then
    

    In the second block of code, tell frontAppProcess equates to:

    tell application process "Aquamacs"
    

    Which is why is fails and it needs to be:

    tell application "Aquamacs"
    

    In Script Editor with Aquamacs running, run the following code:

    tell application "Aquamacs" to count windows
    

    It will return a window count.