Kotlin Native 使用 AXUIElement

Kotlin Native use AXUIElement

我尝试获取所有应用程序的 windows。

fun main() = memScoped {
    NSWorkspace.sharedWorkspace.runningApplications()
        .map { it as NSRunningApplication }
        .filter { it.active }
        .forEach {
            val applicationRef = AXUIElementCreateApplication(it.processIdentifier)
            ...
        }
}

但是我在 kotlin 本机库中找不到 AXUIElement,但是 AXUIElementRefAXUIElementRefVar。许多文章显示 swift 代码以获得 AXUIElement,我不知道如何将代码更改为 kotlin。

swift 代码如下:

if let pid = proToolsApp?.processIdentifier {
    var result = [AXUIElement]()
    var windowList: AnyObject? = nil // [AXUIElement]

    let appRef = AXUIElementCreateApplication(pid)
    if AXUIElementCopyAttributeValue(appRef, "AXWindows" as CFString, &windowList) == .success {
            result = windowList as! [AXUIElement]
    }

    var docRef: AnyObject? = nil
    if AXUIElementCopyAttributeValue(result.first!, "AXDocument" as CFString, &docRef) == .success {
        let result = docRef as! AXUIElement
        print("Found Document: \(result)")
        let filePath = result as! String
        print(filePath)
    }
}

AXUIElement 只是 AXUIElementRef (https://developer.apple.com/documentation/applicationservices/axuielementref?language=objc)

的 swift 解释版本

这在 kotlin 中应该看起来像这样:

fun windowTest() = memScoped {
    NSWorkspace.sharedWorkspace.runningApplications()
        .map { it as NSRunningApplication }
        .filter { it.active }
        .forEach {
            val applicationRef = AXUIElementCreateApplication(it.processIdentifier)!!
            val output = alloc<CFTypeRefVar>()
            var result = AXUIElementCopyAttributeValue(
                applicationRef,
                attribute = kAXWindowsAttribute.toCFString(),
                value = output.ptr,
            )
            if (result != kAXErrorSuccess) {
                println("error $result")
                return@forEach
            }
            val firstOutput = CFArrayGetValueAtIndex(output.value as CFArrayRef, 0)!!
            result = AXUIElementCopyAttributeValue(
                element = firstOutput.reinterpret(),
                attribute = kAXDocumentAttribute.toCFString(),
                value = output.ptr,
            )
            println("$result ${output.value}")
        }
}


fun String.toCFString(): CFStringRef = CFBridgingRetain(this)!!.reinterpret()

第二个 AXUIElementCopyAttributeValue returns -25212 = kAXErrorNoValue 在我的例子中,我不确定是什么问题,但我在两个 swift/kotlin 中得到相同的结果代码