* fix(installer): use 8 KiB HFS+ catalog B-tree nodes for REIMSTOOLS image * feat(guesttools): support Windows-to-macOS window drag-and-drop (Agent v13) --------- Co-authored-by: Shroap <184123002+YinLiaoCo@users.noreply.github.com>
360 lines
17 KiB
JavaScript
360 lines
17 KiB
JavaScript
ObjC.import('Cocoa')
|
|
ObjC.import('CoreGraphics')
|
|
ObjC.import('Foundation')
|
|
|
|
const none = 'none\t\t\t0'
|
|
const browserBundles = new Set([
|
|
'com.google.Chrome', 'com.google.Chrome.canary', 'org.chromium.Chromium',
|
|
'com.apple.Safari', 'com.apple.SafariTechnologyPreview', 'com.microsoft.edgemac',
|
|
'org.mozilla.firefox', 'company.thebrowser.Browser', 'com.brave.Browser',
|
|
'com.operasoftware.Opera', 'com.vivaldi.Vivaldi'
|
|
])
|
|
|
|
function contains(r, x, y) {
|
|
return x >= r.X && x < r.X + r.Width && y >= r.Y && y < r.Y + r.Height
|
|
}
|
|
|
|
function globalRect(frame, mainH) {
|
|
return {X: frame.origin.x, Y: mainH - frame.origin.y - frame.size.height,
|
|
Width: frame.size.width, Height: frame.size.height}
|
|
}
|
|
|
|
function hit(args) {
|
|
const [index, nx, ny] = args.slice(0, 3).map(v => v.trim() ? Number(v) : NaN)
|
|
const screens = $.NSScreen.screens
|
|
if (!Number.isInteger(index) || index < 0 || index >= screens.count ||
|
|
!Number.isFinite(nx) || !Number.isFinite(ny) || nx < 0 || nx > 1 || ny < 0 || ny > 1) return {}
|
|
const mainH = screens.objectAtIndex(0).frame.size.height
|
|
const screen = screens.objectAtIndex(index)
|
|
const frame = globalRect(screen.frame, mainH)
|
|
const x = frame.X + nx * (frame.Width - 1)
|
|
const y = frame.Y + ny * (frame.Height - 1)
|
|
const options = $.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements
|
|
const rawList = $.CGWindowListCopyWindowInfo(options, 0)
|
|
const allWindows = rawList ? (ObjC.deepUnwrap(ObjC.castRefToObject(rawList)) || []) : []
|
|
const windows = allWindows.filter(w => w && w.kCGWindowBounds &&
|
|
w.kCGWindowLayer === 0 && w.kCGWindowAlpha > 0.01 &&
|
|
w.kCGWindowOwnerName !== 'Window Server' && w.kCGWindowBounds.Width > 1 &&
|
|
w.kCGWindowBounds.Height > 1)
|
|
const top = windows.find(w => contains(w.kCGWindowBounds, x, y))
|
|
return {top, windows, desktop: contains(globalRect(screen.visibleFrame, mainH), x, y)}
|
|
}
|
|
|
|
function resolve(args) {
|
|
try { return resolveTarget(args) } catch (_) { return none }
|
|
}
|
|
|
|
function resolveTarget(args) {
|
|
if (args[3] !== 'true') return none
|
|
const {top, desktop} = hit(args)
|
|
if (!top) {
|
|
const path = $.NSHomeDirectory().js + '/Desktop'
|
|
const dir = Ref()
|
|
const fm = $.NSFileManager.defaultManager
|
|
return desktop && fm.fileExistsAtPathIsDirectory(path, dir) && dir[0] && fm.isWritableFileAtPath(path)
|
|
? ['desktop', 'Desktop', path, '0'].join('\t') : none
|
|
}
|
|
const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(top.kCGWindowOwnerPID)
|
|
const id = app && app.bundleIdentifier ? app.bundleIdentifier.js : ''
|
|
const label = ((app && app.localizedName && app.localizedName.js) ||
|
|
top.kCGWindowOwnerName || id || 'App').replace(/[\t\r\n]/g, '')
|
|
return [id === 'com.apple.Photos' ? 'photos' : 'window', label, id, String(top.kCGWindowNumber || 0)].join('\t')
|
|
}
|
|
|
|
function addStealth(item) {
|
|
for (const type of ['org.nspasteboard.TransientType', 'org.nspasteboard.AutoGeneratedType'])
|
|
if (!item.types.containsObject($(type)) && !item.setDataForType($.NSData.data, $(type))) throw Error('Cannot mark pasteboard item')
|
|
return item
|
|
}
|
|
|
|
function readImagePNG(path) {
|
|
if (!/\.(png|jpe?g|webp|gif|bmp|heic|tiff?)$/i.test(path)) return null
|
|
try {
|
|
const attrs = $.NSFileManager.defaultManager.attributesOfItemAtPathError(path, null)
|
|
if (attrs.fileType.js !== $.NSFileTypeRegular.js || !(Number(attrs.fileSize) <= 32 * 1024 * 1024)) return null
|
|
if (/\.png$/i.test(path)) {
|
|
const png = $.NSData.dataWithContentsOfFile(path)
|
|
return png && !png.isNil() ? png : null
|
|
}
|
|
const img = $.NSImage.alloc.initWithContentsOfFile(path)
|
|
const rep = $.NSBitmapImageRep.imageRepWithData(img.TIFFRepresentation)
|
|
const png = rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $({}))
|
|
return png && !png.isNil() ? png : null
|
|
} catch (_) { return null }
|
|
}
|
|
|
|
function resolveCommandKey() {
|
|
const modifiers = [
|
|
[0x7000000E3, 'meta_l'], [0x7000000E7, 'meta_r'], [0x7000000E2, 'alt'],
|
|
[0x7000000E6, 'alt_r'], [0x7000000E0, 'ctrl'], [0x7000000E4, 'ctrl_r'],
|
|
[0x700000039, 'caps_lock'], [0x7000000E1, 'shift'], [0x7000000E5, 'shift_r'],
|
|
]
|
|
const map = new Map(modifiers.map(([usage]) => [usage, usage]))
|
|
function normUsage(v) {
|
|
if (typeof v !== 'number' && !(typeof v === 'string' && /^(?:0x[\da-f]+|\d+)$/i.test(v))) return NaN
|
|
const n = Number(v)
|
|
if (!Number.isSafeInteger(n)) return NaN
|
|
return n >= 0 && n < 0x10000 ? n + 0x700000000 : n
|
|
}
|
|
function apply(src, dst) {
|
|
src = normUsage(src)
|
|
dst = normUsage(dst)
|
|
if (map.has(src) && Number.isFinite(dst)) map.set(src, dst)
|
|
}
|
|
function preference(key) {
|
|
try {
|
|
const value = $.CFPreferencesCopyValue($(key), $.kCFPreferencesAnyApplication,
|
|
$.kCFPreferencesCurrentUser, $.kCFPreferencesCurrentHost)
|
|
const entries = value ? ObjC.deepUnwrap(ObjC.castRefToObject(value)) : null
|
|
if (Array.isArray(entries)) return entries
|
|
} catch (_) {}
|
|
return []
|
|
}
|
|
let entries = preference('com.apple.keyboard.modifiermapping.1575-1-0')
|
|
if (!entries.length) entries = preference('com.apple.keyboard.modifiermapping.0-0-0')
|
|
for (const entry of entries) {
|
|
if (entry) apply(entry.HIDKeyboardModifierMappingSrc, entry.HIDKeyboardModifierMappingDst)
|
|
}
|
|
try {
|
|
const task = $.NSTask.alloc.init
|
|
const pipe = $.NSPipe.pipe
|
|
task.launchPath = '/usr/bin/hidutil'
|
|
task.arguments = $(['property', '--get', 'UserKeyMapping'])
|
|
task.standardOutput = pipe
|
|
task.standardError = $.NSFileHandle.fileHandleWithNullDevice
|
|
task.launch
|
|
const data = pipe.fileHandleForReading.readDataToEndOfFile
|
|
task.waitUntilExit
|
|
if (task.terminationStatus === 0) {
|
|
const output = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js
|
|
for (const block of output.match(/\{[^{}]*\}/g) || []) {
|
|
const src = /"?HIDKeyboardModifierMappingSrc"?\s*[:=]\s*(0x[\da-f]+|\d+)\b/i.exec(block)
|
|
const dst = /"?HIDKeyboardModifierMappingDst"?\s*[:=]\s*(0x[\da-f]+|\d+)\b/i.exec(block)
|
|
if (src && dst) apply(src[1], dst[1])
|
|
}
|
|
}
|
|
} catch (_) {}
|
|
for (const command of [0x7000000E3, 0x7000000E7]) {
|
|
for (const [usage, qcode] of modifiers) {
|
|
if (map.get(usage) === command) return qcode
|
|
}
|
|
}
|
|
return 'meta_l'
|
|
}
|
|
|
|
function requestPaste(url, id, activateClick, commandKey, focusWaitMs) {
|
|
const rawTok = $.NSProcessInfo.processInfo.environment.objectForKey($('REIMS_TOKEN'))
|
|
const token = rawTok && !rawTok.isNil() ? rawTok.js : ''
|
|
if (!token || /[\r\n\0]/.test(url + token) || !/^[A-Za-z0-9_-]+$/.test(id)) throw Error('Invalid paste request')
|
|
const body = {drop_id: id}
|
|
if (activateClick) body.activate_click = true
|
|
if (commandKey && commandKey !== 'meta_l') body.command_key = commandKey
|
|
if (focusWaitMs > 0) body.focus_wait_ms = focusWaitMs
|
|
const config = ['url = ' + JSON.stringify(url), 'header = ' + JSON.stringify('Authorization: Bearer ' + token),
|
|
'header = "Content-Type: application/json"', 'data-raw = ' + JSON.stringify(JSON.stringify(body))].join('\n') + '\n'
|
|
const task = $.NSTask.alloc.init
|
|
const input = $.NSPipe.pipe
|
|
task.launchPath = '/usr/bin/curl'
|
|
task.arguments = $(['-fsS', '-m', '10', '-X', 'POST', '-K', '-'])
|
|
task.standardInput = input
|
|
task.standardOutput = $.NSFileHandle.fileHandleWithNullDevice
|
|
task.launch
|
|
try { input.fileHandleForWriting.writeData($(config).dataUsingEncoding($.NSUTF8StringEncoding)) }
|
|
finally { input.fileHandleForWriting.closeFile }
|
|
task.waitUntilExit
|
|
if (task.terminationStatus !== 0) throw Error('Paste request failed')
|
|
}
|
|
|
|
function pasteCore(hitArgs, expected, bundleId, mode, url, id, items) {
|
|
const {top, windows} = hit(hitArgs)
|
|
if (!top || String(top.kCGWindowNumber || 0) !== expected) return 'cancelled'
|
|
const ownerApp = top.kCGWindowOwnerPID
|
|
? $.NSRunningApplication.runningApplicationWithProcessIdentifier(top.kCGWindowOwnerPID) : null
|
|
const isTopOfApp = windows.find(w => w.kCGWindowOwnerPID === top.kCGWindowOwnerPID)?.kCGWindowNumber === top.kCGWindowNumber
|
|
const fm0 = $.NSWorkspace.sharedWorkspace.frontmostApplication
|
|
const alreadyActive = !!(fm0 && !fm0.isNil() && fm0.processIdentifier === top.kCGWindowOwnerPID)
|
|
let activated = false
|
|
if (ownerApp && isTopOfApp) {
|
|
if (bundleId === 'com.apple.finder' && ownerApp.bundleURL && !ownerApp.bundleURL.isNil()) {
|
|
$.NSWorkspace.sharedWorkspace.openURL(ownerApp.bundleURL)
|
|
$.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.15))
|
|
activated = true
|
|
} else if (!alreadyActive) {
|
|
ownerApp.activateWithOptions($.NSApplicationActivateIgnoringOtherApps)
|
|
$.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.12))
|
|
activated = true
|
|
}
|
|
}
|
|
if (activated && !(hit(hitArgs).windows || []).some(w => String(w.kCGWindowNumber) === expected)) return 'cancelled'
|
|
const fm = $.NSWorkspace.sharedWorkspace.frontmostApplication
|
|
const activateClick = !!(top.kCGWindowOwnerPID && (!isTopOfApp || !fm || fm.isNil() || fm.processIdentifier !== top.kCGWindowOwnerPID))
|
|
const pb = $.NSPasteboard.generalPasteboard
|
|
const savedItems = []
|
|
const clipboardItems = pb.pasteboardItems
|
|
if (clipboardItems && !clipboardItems.isNil()) {
|
|
for (let i = 0; i < clipboardItems.count; i++) {
|
|
const item = clipboardItems.objectAtIndex(i)
|
|
const pairs = []
|
|
const types = item.types
|
|
for (let j = 0; j < types.count; j++) {
|
|
const type = types.objectAtIndex(j)
|
|
if (type.js === 'org.nspasteboard.TransientType' || type.js === 'org.nspasteboard.AutoGeneratedType') continue
|
|
try {
|
|
const data = item.dataForType(type)
|
|
if (data && !data.isNil()) pairs.push({type, data})
|
|
} catch (_) { /* The owner could not provide this promised flavor. */ }
|
|
}
|
|
if (pairs.length) savedItems.push(pairs)
|
|
}
|
|
}
|
|
let primaryErr = null
|
|
try {
|
|
pb.clearContents
|
|
const newItems = items.map(path => {
|
|
const item = $.NSPasteboardItem.alloc.init
|
|
if (mode === 'files') {
|
|
const png = items.length === 1 && bundleId !== 'com.apple.finder' ? readImagePNG(path) : null
|
|
if ((!png || !browserBundles.has(bundleId)) &&
|
|
!item.setStringForType($.NSURL.fileURLWithPath(path).absoluteString, $.NSPasteboardTypeFileURL))
|
|
throw Error('Cannot stage file')
|
|
if (png && !item.setDataForType(png, $.NSPasteboardTypePNG)) throw Error('Cannot stage PNG')
|
|
} else if (mode === 'text' || mode === 'text-raw') {
|
|
const value = mode === 'text-raw' ? $(path) : $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null)
|
|
if (!value || value.isNil() || !item.setStringForType(value, $.NSPasteboardTypeString))
|
|
throw Error('Cannot stage text')
|
|
} else throw Error('Invalid paste mode')
|
|
return addStealth(item)
|
|
})
|
|
if (!pb.writeObjects($(newItems))) throw Error('Cannot stage clipboard')
|
|
requestPaste(url, id, activateClick, resolveCommandKey(), bundleId === 'com.apple.finder' ? 220 : 0)
|
|
return 'pasted'
|
|
} catch (err) {
|
|
primaryErr = err
|
|
throw err
|
|
} finally {
|
|
pb.clearContents
|
|
const restored = savedItems.map(pairs => {
|
|
const item = $.NSPasteboardItem.alloc.init
|
|
for (const {type, data} of pairs) {
|
|
try { item.setDataForType(data, type) } catch (_) { /* Continue with the remaining flavors. */ }
|
|
}
|
|
return addStealth(item)
|
|
})
|
|
if (restored.length && !pb.writeObjects($(restored)) && !primaryErr) throw Error('Cannot restore clipboard')
|
|
}
|
|
}
|
|
|
|
function parseEventData(eventFile) {
|
|
const ev = JSON.parse($.NSString.stringWithContentsOfFileEncodingError(eventFile, $.NSUTF8StringEncoding, null).js)
|
|
if (!ev || typeof ev.drop_id !== 'string' || !/^[A-Za-z0-9_-]+$/.test(ev.drop_id)) throw Error('Invalid drop ID')
|
|
if (!Number.isInteger(ev.display_index) || ev.display_index < 0 ||
|
|
![ev.norm_x, ev.norm_y].every(n => Number.isFinite(n) && n >= 0 && n <= 1) ||
|
|
[ev.webdav_drop, ev.in_image].some(v => v !== undefined && typeof v !== 'boolean')) throw Error('Invalid drop location')
|
|
if (ev.kind === undefined) ev.kind = 'files'
|
|
ev.webdav_drop = ev.webdav_drop === true
|
|
ev.in_image = ev.in_image === true
|
|
if (ev.kind === 'text') {
|
|
if (typeof ev.text !== 'string' || !ev.text.length) throw Error('Invalid drop text')
|
|
} else {
|
|
if (ev.kind !== 'files') throw Error('Invalid drop kind')
|
|
const safePath = n => typeof n === 'string' && !/[\\\n\r\0\t]/.test(n) &&
|
|
n.split('/').every(segment => segment && segment !== '.' && segment !== '..')
|
|
if (!Array.isArray(ev.items) || !ev.items.length || !ev.items.every(safePath)) throw Error('Invalid drop item')
|
|
ev.targets = ev.target_paths === undefined ? ev.items : ev.target_paths
|
|
if (!Array.isArray(ev.targets) || ev.targets.length !== ev.items.length || !ev.targets.every(safePath))
|
|
throw Error('Invalid drop target path')
|
|
}
|
|
return ev
|
|
}
|
|
|
|
function eventLines(ev) {
|
|
const header = [ev.drop_id, ev.kind, ev.webdav_drop, ev.display_index, ev.norm_x, ev.norm_y, ev.in_image].join('\t')
|
|
return [header].concat(ev.kind === 'files' ? ev.items.map((src, i) => src + '\t' + ev.targets[i]) : [])
|
|
}
|
|
|
|
function encodeAck(drop_id, status, target_kind, label, error, names) {
|
|
return JSON.stringify({drop_id, status, target_kind, target_label: label || undefined,
|
|
error: error || undefined, placed_names: names.length ? names : undefined})
|
|
}
|
|
|
|
function mountHealthy(paths) {
|
|
try {
|
|
return paths.length > 0 && paths.every(p => {
|
|
const ref = $.NSURL.fileURLWithPath(p).fileReferenceURL
|
|
return ref && (typeof ref.isNil !== 'function' || !ref.isNil())
|
|
})
|
|
} catch (_) { return false }
|
|
}
|
|
|
|
function importPhotos(paths) {
|
|
Application('com.apple.Photos').import(paths.map(p => Path(p)), {skipCheckDuplicates: false})
|
|
return 'ok'
|
|
}
|
|
|
|
function photosError(err) {
|
|
const msg = String(err && err.message || err || '').replace(/[\r\n\t]+/g, ' ').trim()
|
|
if (/1743|not authorized|permission|privilege/i.test(msg)) return 'Photos import blocked: allow Automation access to Photos in macOS Privacy & Security'
|
|
return msg ? 'Photos import failed: ' + msg.slice(0, 140) : 'Photos import failed'
|
|
}
|
|
|
|
function runDrop(eventFile, mount, url) {
|
|
const ev = parseEventData(eventFile)
|
|
const hitArgs = [ev.display_index, ev.norm_x, ev.norm_y, ev.in_image].map(String)
|
|
const target = resolve(hitArgs)
|
|
const [kind, label, meta, expected] = target.split('\t')
|
|
function done(status) {
|
|
return 'done\t' + encodeAck(ev.drop_id, status, status === 'cancelled' ? 'cancelled' : kind,
|
|
status === 'cancelled' ? '' : label, '', [])
|
|
}
|
|
function perform(mode, paths) {
|
|
try {
|
|
if (kind === 'photos') {
|
|
importPhotos(paths)
|
|
return done('placed')
|
|
}
|
|
return done(pasteCore(hitArgs, expected, meta, mode, url, ev.drop_id, paths))
|
|
} catch (err) {
|
|
return 'done\t' + encodeAck(ev.drop_id, 'failed', kind, label,
|
|
kind === 'photos' ? photosError(err) : 'Paste failed', [])
|
|
}
|
|
}
|
|
if (kind === 'none' || (ev.kind === 'text' && kind !== 'window')) return done('cancelled')
|
|
if (ev.kind === 'text') return perform('text-raw', [ev.text])
|
|
if ((kind === 'window' || kind === 'photos') && ev.webdav_drop && mount) {
|
|
const dir = mount + '/' + ev.drop_id
|
|
const fm = $.NSFileManager.defaultManager
|
|
const dirRef = Ref()
|
|
const paths = ev.items.map(src => dir + '/' + src)
|
|
if (fm.fileExistsAtPathIsDirectory(dir, dirRef) && dirRef[0] && mountHealthy([mount, dir]) &&
|
|
paths.every(p => fm.fileExistsAtPath(p))) {
|
|
return perform('files', paths)
|
|
}
|
|
}
|
|
const [header, ...items] = eventLines(ev)
|
|
return ['fallback', header, target].concat(items).join('\n')
|
|
}
|
|
|
|
function run(argv) {
|
|
const [mode, ...args] = argv
|
|
if (mode === 'run-drop') return runDrop(...args)
|
|
if (mode === 'resolve') return resolve(args)
|
|
if (mode === 'check-mount') {
|
|
if (!mountHealthy(args)) throw Error('Unreachable mount')
|
|
return 'ok'
|
|
}
|
|
if (mode === 'paste-drop') {
|
|
const [, , , expected, bundleId, kind, url, id, ...paths] = args
|
|
return pasteCore(args.slice(0, 3), expected, bundleId, kind, url, id, paths)
|
|
}
|
|
if (mode === 'import-photos') return importPhotos(args)
|
|
if (mode === 'parse-event') {
|
|
const ev = parseEventData(args[0])
|
|
if (ev.kind === 'text' && (!args[1] ||
|
|
!$.NSString.stringWithString(ev.text).writeToFileAtomicallyEncodingError(args[1], true, $.NSUTF8StringEncoding, null)))
|
|
throw Error('Invalid drop text')
|
|
return eventLines(ev).join('\n')
|
|
}
|
|
if (mode === 'encode-ack') return encodeAck(...args.slice(0, 5), args.slice(5))
|
|
throw Error('Unknown drop command')
|
|
}
|