Home > database >  How to activate a terminal window after opening (and closing) NSOpenPanel requestor from a CLI app?
How to activate a terminal window after opening (and closing) NSOpenPanel requestor from a CLI app?

Time:09-03

I have a command line application running in a terminal and I want to be able use AppKit file requestor. In the C code I initialise the AppKit using:

[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory]; // no additional window in the Dock
[NSApp setDelegate: my_app_delegate];

To open a dialog I than call from the C side such a function:

void request_file(void) {
    NSOpenPanel* openPanel = [NSOpenPanel openPanel];
    openPanel.canChooseFiles = YES;

    [NSApp activateIgnoringOtherApps:YES]; // to activate the dialog
    [openPanel makeKeyAndOrderFront:nil];

    [openPanel beginWithCompletionHandler:^(NSInteger result) {
        if (result==NSModalResponseOK) {
            // do something with URLs
        }
        [NSApp stopModal];
    }];
    [openPanel runModal];
}

It works, but after closing the requestor, I must manually click with a mouse back on the terminal window to continue typing there.

Is there some way how to activate the terminal window automatically after stopping the modal loop?

CodePudding user response:

It looks that I can use NSRunningApplication like:

void request_file(void) {
    // store currently active application so it can be reactivated later
    NSRunningApplication* wasRunningApp = [[NSWorkspace sharedWorkspace] frontmostApplication];

    NSOpenPanel* openPanel = [NSOpenPanel openPanel];
    openPanel.canChooseFiles = YES;

    [NSApp activateIgnoringOtherApps:YES]; // to activate the dialog
    [openPanel makeKeyAndOrderFront:nil];

    [openPanel beginWithCompletionHandler:^(NSInteger result) {
        if (result==NSModalResponseOK) {
            // do something with URLs
        }
        [NSApp stopModal];

        // try to reactivate the previous application
        [wasRunningApp activateWithOptions:NSApplicationActivateIgnoringOtherApps];
    }];
    [openPanel runModal];
}
  • Related