window enum | enum windows with cocoa | | Search

The getTitle(int i) function retrieves the title of a window with the specified layer index i by searching through an array of window dictionaries and constructing a string with the window's layer index and owner name.

The getTitle(int i) function searches for a window with a matching layer index i in an array of window dictionaries.
If found, it constructs a string with the window's layer index and owner name, and returns a duplicate of this string as a C-style string.

Run example

npm run import -- "lookup window by"

lookup window by

__attribute__((visibility("default")))
const char* getTitle(int i) {
    if (windows == NULL) {
        count = enumWindows();
    }

    NSDictionary* targetWindow = nil;
    for (NSDictionary* window in windows) {
        NSNumber* windowLayer = (NSNumber*)[window objectForKey:(__bridge NSString*)kCGWindowLayer];
        if (windowLayer && [windowLayer intValue] == i) { // Compare with the provided index
            targetWindow = window;
            break;
        }
    }

    if (!targetWindow) {
        return NULL;
    }

    NSString* windowName = (NSString*)[targetWindow objectForKey:(__bridge NSString*)kCGWindowOwnerName];
    NSNumber* windowLayer = (NSNumber*)[targetWindow objectForKey:(__bridge NSString*)kCGWindowLayer];
    NSString* res = [NSString stringWithFormat:@"%@: %s", windowLayer, [windowName UTF8String]];
    
    return strdup([res UTF8String]); // Use strdup to return a persistent C-string
}

What the code could have been:

/**
 * Returns the title of the window with the specified layer number.
 *
 * @param layer The layer number of the window to retrieve the title for.
 * @return A string containing the window title, or NULL if no window with the specified layer number is found.
 */
__attribute__((visibility("default")))
const char* getTitle(int layer) {
    static NSArray* windows = nil;
    
    // Enumerate windows once and store the result in a static array to avoid redundant enumeration
    if (windows == nil) {
        windows = enumWindows();
    }

    // Use KVO to iterate over the array for better performance
    NSDictionary* targetWindow = [windows firstObjectWithKeysPassingTest:^BOOL(id obj, NSDictionary* key) {
        NSNumber* windowLayer = key;
        return [windowLayer intValue] == layer;
    }];

    if (!targetWindow) {
        // Return NULL if no window with the specified layer number is found
        return NULL;
    }

    // Use string properties for better readability and thread-safety
    NSString* title = targetWindow[kCGWindowOwnerName];
    NSNumber* windowLayer = targetWindow[kCGWindowLayer];
    NSString* result = [NSString stringWithFormat:@"%@: %d", title, [windowLayer intValue]];
    
    // Use a more modern and safer way to create a C-string
    return [result UTF8String];
}

Code Breakdown

Code Attributes

Function getTitle(int i)

Function Return Value