Search code examples
applescript-objc

How to show NSAlert using Sheet window in separate .XIB files?


I have a button to perform a task and if an error occurs during the process a warning is displayed using NSAlert "Sheet window" in this moment I am using multiple .XIB files in a project, I can't display the "Sheet window" in these files(.XIB) is there any way to do this? Thanks in advance!

on clickedButton:sender

try
--some code here...

on error errorMsg
           set alert to current application's NSAlert's alloc's init()
           tell alert
               its setMessageText:"This is an ERROR"
               its setInformativeText: "Error: " & errorMsg
               its setAlertStyle:2
               its beginSheetModalForWindow:theWindow modalDelegate:me didEndSelector:(missing value) contextInfo:(missing value)
               end tell
            end try
end clickedButton:

Solution

  • If you don't have a window to put the sheet on, you will need to run the normal alert dialog. You can test for a window by using NSApp's mainWindow(), which will be missing value if there isn't one, and do either alert's runModal() or the sheet depending on the result:

    use framework "Cocoa"
    use scripting additions
    
    property theWindow : missing value -- this will be the main window...
    property sheetOrNot : true -- ... or not, depending on this flag
    
    on run -- this lets the example run from the Script Editor if you forget the main thread thing
        my performSelectorOnMainThread:"doWindow" withObject:(missing value) waitUntilDone:true
        my performSelectorOnMainThread:"doAlert" withObject:(missing value) waitUntilDone:true
    end run
    
    on doWindow() -- create a window to play with
        set theWindow to current application's NSWindow's alloc's initWithContentRect:{{200, 400}, {400, 200}} styleMask:7 backing:(current application's NSBackingStoreBuffered) defer:true
        set theWindow's releasedWhenClosed to true
        if sheetOrNot then tell theWindow to makeKeyAndOrderFront:me
    end doWindow
    
    on doAlert() -- show the alert
        try
            --some code here...
            error "oops" -- ...that went badly
        on error errorMsg
            set alert to current application's NSAlert's alloc's init()
            tell alert
                its setMessageText:"This is an ERROR"
                its setInformativeText:("Error: " & errorMsg)
                its setAlertStyle:2
                if current application's NSApp's mainWindow() is not missing value then
                    its beginSheetModalForWindow:theWindow modalDelegate:me didEndSelector:(missing value) contextInfo:(missing value)
                else -- no window, so do a normal modal dialog
                    its runModal()
                end if
            end tell
        end try
    end doAlert