Something went wrong. Try again.
Open a URI in the user's chosen application from Zig: the desktop portal on Linux, ShellExecuteExW on Windows, Launch Services on macOS.
Something went wrong. Try again.
2.3 kB · 74 lines
Zig
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Opening a URI with Launch Services' `LSOpenCFURLRef`, a plain C call that//! needs no Objective-C runtime://! https://developer.apple.com/documentation/coreservices/1442850-lsopencfurlref//!//! The few CoreFoundation and Launch Services symbols are declared here//! rather than imported from the SDK's headers, so that the library compiles//! for macOS on any machine; only linking needs the SDK.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;
const root = @import("root.zig");const Error = root.Error;const Options = root.Options;const Outcome = root.Outcome;
const CFTypeRef = *const anyopaque;const CFAllocatorRef = ?*const anyopaque;const CFURLRef = *const opaque {};const CFIndex = isize;const CFStringEncoding = u32;const OSStatus = i32;
const kCFStringEncodingUTF8: CFStringEncoding = 0x08000100;
extern "c" fn CFURLCreateWithBytes( allocator: CFAllocatorRef, bytes: [*]const u8, length: CFIndex, encoding: CFStringEncoding, base: ?CFURLRef,) ?CFURLRef;extern "c" fn CFRelease(object: CFTypeRef) void;extern "c" fn LSOpenCFURLRef(url: CFURLRef, launched: ?*?CFURLRef) OSStatus;
// From <CarbonCore/MacErrors.h> and <LaunchServices/LSInfo.h>.const noErr: OSStatus = 0;const userCanceledErr: OSStatus = -128;const fnfErr: OSStatus = -43;const permErr: OSStatus = -54;const kLSApplicationNotFoundErr: OSStatus = -10814;const kLSNoExecutableErr: OSStatus = -10827;
pub fn open( io: Io, gpa: Allocator, environ: std.process.Environ, uri: []const u8, is_file: bool, options: Options,) Error!Outcome { _ = io; _ = gpa; _ = environ; _ = is_file; _ = options;
const url = CFURLCreateWithBytes(null, uri.ptr, @intCast(uri.len), kCFStringEncodingUTF8, null) orelse return error.InvalidUri; defer CFRelease(url);
return switch (LSOpenCFURLRef(url, null)) { noErr => .opened, userCanceledErr => .cancelled, fnfErr => error.FileNotFound, permErr => error.AccessDenied, kLSApplicationNotFoundErr, kLSNoExecutableErr => error.NoHandler, else => error.Unexpected, };}