Sources/OrgCore/Sandbox.swift
44 lines · 1802 bytes
5 symbols in this file
1import Foundation
2
3/// Whether this process runs in the App Sandbox, as the Mac App Store build does, and the
4/// choices that follow from it.
5public enum Sandbox {
6 /// True for a sandboxed Mac process. Always false on iOS.
7 public static let isActive = isActive(environment: ProcessInfo.processInfo.environment)
8
9 /// The sandbox sets `APP_SANDBOX_CONTAINER_ID` for the processes it confines.
10 static func isActive(environment: [String: String]) -> Bool {
11 #if os(macOS)
12 environment["APP_SANDBOX_CONTAINER_ID"] != nil
13 #else
14 false
15 #endif
16 }
17
18 /// Options for a bookmark that should give access back after relaunch: security-scoped in
19 /// the Mac sandbox, plain elsewhere.
20 public static func bookmarkCreationOptions(sandboxed: Bool = isActive) -> URL.BookmarkCreationOptions {
21 #if os(macOS)
22 sandboxed ? .withSecurityScope : []
23 #else
24 []
25 #endif
26 }
27
28 /// A bookmark of `url` made with `bookmarkCreationOptions`. Access to the URL is started
29 /// first: a URL from SwiftUI's file importer is security-scoped, and the sandbox refuses a
30 /// bookmark of it until access starts. Access stays on for the session.
31 public static func bookmark(_ url: URL, sandboxed: Bool = isActive) throws -> Data {
32 _ = url.startAccessingSecurityScopedResource()
33 return try url.bookmarkData(options: bookmarkCreationOptions(sandboxed: sandboxed), includingResourceValuesForKeys: nil, relativeTo: nil)
34 }
35
36 /// The resolving side of `bookmarkCreationOptions`.
37 public static func bookmarkResolutionOptions(sandboxed: Bool = isActive) -> URL.BookmarkResolutionOptions {
38 #if os(macOS)
39 sandboxed ? .withSecurityScope : []
40 #else
41 []
42 #endif
43 }
44}