├── .github └── FUNDING.yml ├── .gitignore ├── Chinotto-release.xcconfig ├── Chinotto.xcconfig ├── Chinotto.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist └── xcshareddata │ └── xcschemes │ └── Chinotto.xcscheme ├── Chinotto ├── AppDelegate.swift ├── Assets.xcassets │ ├── AccentColor.colorset │ │ └── Contents.json │ ├── AppIcon.appiconset │ │ └── Contents.json │ └── Contents.json ├── Chinotto.entitlements ├── ChinottoApp.swift ├── ChinottoMenuBarApp.swift ├── ContentView.swift ├── CoreSimulatorsRootView.swift ├── Directories │ └── Xcode 15 │ │ ├── Directories.swift │ │ ├── Scoped Directory Views │ │ ├── CachesView.swift │ │ ├── _CoreSimulatorDevicesView.swift │ │ ├── _CoreSimulatorSystemCachesView.swift │ │ ├── _CoreSimulatorSystemView.swift │ │ ├── _CoreSimulatorUserCachesView.swift │ │ └── _CoreSimulatorUserView.swift │ │ ├── Subdirectories.swift │ │ └── User Scope │ │ ├── CoreSimulatorView.swift │ │ ├── DeveloperDiskImagesView.swift │ │ ├── ToolchainsView.swift │ │ ├── XCPGDevicesView.swift │ │ ├── XCTestDevicesView.swift │ │ └── XcodeView.swift ├── DirectoriesStorageView.swift ├── Localizable.xcstrings ├── LoginItemBehaviour.swift ├── Preferences │ ├── AppPreferencesView.swift │ └── GeneralPreferencesView.swift ├── Preview Content │ └── Preview Assets.xcassets │ │ └── Contents.json ├── StorageView.swift ├── UnifiedStorageView.swift └── XcodeVersion.swift ├── ChinottoTests └── ChinottoTests.swift ├── ChinottoUITests ├── ChinottoUITests.swift └── ChinottoUITestsLaunchTests.swift ├── LICENSE ├── Packages ├── CoreSimulatorTools │ ├── .gitignore │ ├── Package.swift │ ├── Sources │ │ └── CoreSimulatorTools │ │ │ ├── CoreSimDevice.swift │ │ │ └── DeviceIdiom.swift │ └── Tests │ │ └── CoreSimulatorToolsTests │ │ └── CoreSimulatorToolsTests.swift ├── CoreSimulatorUI │ ├── .gitignore │ ├── Package.swift │ ├── Sources │ │ └── CoreSimulatorUI │ │ │ ├── CoreSimDeviceInspectView.swift │ │ │ └── CoreSimDeviceView.swift │ └── Tests │ │ └── CoreSimulatorUITests │ │ └── CoreSimulatorUITests.swift ├── DestructiveActions │ ├── .gitignore │ ├── Package.swift │ ├── README.md │ ├── Sources │ │ └── DestructiveActions │ │ │ ├── DeletionBehaviour.swift │ │ │ └── DestructiveActions.swift │ └── Tests │ │ └── DestructiveActionsTests │ │ └── DestructiveActionsTests.swift ├── FileSystem │ ├── .gitignore │ ├── Package.swift │ ├── Sources │ │ └── FileSystem │ │ │ └── FileSystem.swift │ └── Tests │ │ └── FileSystemTests │ │ └── FileSystemTests.swift └── FileSystemUI │ ├── .gitignore │ ├── Package.swift │ ├── Sources │ └── FileSystemUI │ │ └── AnyDirectory.swift │ └── Tests │ └── FileSystemUITests │ └── FileSystemUITests.swift └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: boscojwho # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## User settings 6 | xcuserdata/ 7 | 8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 9 | *.xcscmblueprint 10 | *.xccheckout 11 | 12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 13 | build/ 14 | DerivedData/ 15 | *.moved-aside 16 | *.pbxuser 17 | !default.pbxuser 18 | *.mode1v3 19 | !default.mode1v3 20 | *.mode2v3 21 | !default.mode2v3 22 | *.perspectivev3 23 | !default.perspectivev3 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | 28 | ## App packaging 29 | *.ipa 30 | *.dSYM.zip 31 | *.dSYM 32 | 33 | ## Playgrounds 34 | timeline.xctimeline 35 | playground.xcworkspace 36 | 37 | # Swift Package Manager 38 | # 39 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 40 | # Packages/ 41 | # Package.pins 42 | # Package.resolved 43 | # *.xcodeproj 44 | # 45 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 46 | # hence it is not needed unless you have added a package configuration file to your project 47 | # .swiftpm 48 | 49 | .build/ 50 | 51 | # CocoaPods 52 | # 53 | # We recommend against adding the Pods directory to your .gitignore. However 54 | # you should judge for yourself, the pros and cons are mentioned at: 55 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 56 | # 57 | # Pods/ 58 | # 59 | # Add this line if you want to avoid checking in source code from the Xcode workspace 60 | # *.xcworkspace 61 | 62 | # Carthage 63 | # 64 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 65 | # Carthage/Checkouts 66 | 67 | Carthage/Build/ 68 | 69 | # Accio dependency management 70 | Dependencies/ 71 | .accio/ 72 | 73 | # fastlane 74 | # 75 | # It is recommended to not store the screenshots in the git repo. 76 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 77 | # For more information about the recommended setup visit: 78 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 79 | 80 | fastlane/report.xml 81 | fastlane/Preview.html 82 | fastlane/screenshots/**/*.png 83 | fastlane/test_output 84 | 85 | # Code Injection 86 | # 87 | # After new code Injection tools there's a generated folder /iOSInjectionProject 88 | # https://github.com/johnno1962/injectionforxcode 89 | 90 | iOSInjectionProject/ 91 | -------------------------------------------------------------------------------- /Chinotto-release.xcconfig: -------------------------------------------------------------------------------- 1 | DEVELOPMENT_TEAM = 4G96725NK5 2 | BUNDLE_ID_PREFIX = com.bosco.ho 3 | -------------------------------------------------------------------------------- /Chinotto.xcconfig: -------------------------------------------------------------------------------- 1 | // Replace placeholder values with your own. 2 | // [2023.11] How to find your development team id: https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/ 3 | DEVELOPMENT_TEAM = abcde12345 4 | BUNDLE_ID_PREFIX = com.example 5 | -------------------------------------------------------------------------------- /Chinotto.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Chinotto.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Chinotto.xcodeproj/xcshareddata/xcschemes/Chinotto.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 31 | 32 | 35 | 41 | 42 | 43 | 46 | 52 | 53 | 54 | 55 | 56 | 66 | 68 | 74 | 75 | 76 | 77 | 83 | 85 | 91 | 92 | 93 | 94 | 96 | 97 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /Chinotto/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-12-04. 6 | // 7 | 8 | import Foundation 9 | import AppKit 10 | 11 | class AppDelegate: NSObject, NSApplicationDelegate { 12 | 13 | func applicationDidFinishLaunching(_ notification: Notification) { 14 | LoginItemBehaviour.hideWindowsOnDidFinishLaunching( 15 | NSApplication.shared.windows, 16 | notification 17 | ) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chinotto/Assets.xcassets/AccentColor.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "colors" : [ 3 | { 4 | "idiom" : "universal" 5 | } 6 | ], 7 | "info" : { 8 | "author" : "xcode", 9 | "version" : 1 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chinotto/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "mac", 5 | "scale" : "1x", 6 | "size" : "16x16" 7 | }, 8 | { 9 | "idiom" : "mac", 10 | "scale" : "2x", 11 | "size" : "16x16" 12 | }, 13 | { 14 | "idiom" : "mac", 15 | "scale" : "1x", 16 | "size" : "32x32" 17 | }, 18 | { 19 | "idiom" : "mac", 20 | "scale" : "2x", 21 | "size" : "32x32" 22 | }, 23 | { 24 | "idiom" : "mac", 25 | "scale" : "1x", 26 | "size" : "128x128" 27 | }, 28 | { 29 | "idiom" : "mac", 30 | "scale" : "2x", 31 | "size" : "128x128" 32 | }, 33 | { 34 | "idiom" : "mac", 35 | "scale" : "1x", 36 | "size" : "256x256" 37 | }, 38 | { 39 | "idiom" : "mac", 40 | "scale" : "2x", 41 | "size" : "256x256" 42 | }, 43 | { 44 | "idiom" : "mac", 45 | "scale" : "1x", 46 | "size" : "512x512" 47 | }, 48 | { 49 | "idiom" : "mac", 50 | "scale" : "2x", 51 | "size" : "512x512" 52 | } 53 | ], 54 | "info" : { 55 | "author" : "xcode", 56 | "version" : 1 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Chinotto/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Chinotto/Chinotto.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.files.user-selected.read-only 8 | 9 | com.apple.security.temporary-exception.files.home-relative-path.read-write 10 | 11 | /Library/Developer/CoreSimulator 12 | /Library/Developer/DeveloperDiskImages 13 | /Library/Developer/Xcode 14 | /Library/Developer/XCPGDevices 15 | /Library/Developer/XCTestDevices 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Chinotto/ChinottoApp.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ChinottoApp.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-12. 6 | // 7 | 8 | import SwiftUI 9 | import CoreSimulatorTools 10 | import CoreSimulatorUI 11 | 12 | @main 13 | struct ChinottoApp: App { 14 | @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate 15 | @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true 16 | 17 | var body: some Scene { 18 | MenuBarExtra( 19 | "Chinotto Menu Bar App", 20 | systemImage: "chart.bar.doc.horizontal", 21 | isInserted: $showMenuBarExtra 22 | ) { 23 | ChinottoMenuBarApp() 24 | } 25 | .menuBarExtraStyle(.window) 26 | 27 | Window("", id: "Main Window") { 28 | ContentView() 29 | .frame(maxWidth: 1440) 30 | } 31 | .defaultPosition(.center) 32 | .defaultSize(width: 840, height: 1080) 33 | .windowResizability(.contentSize) 34 | /// [2023.11] Feature exists in another branch. 35 | // .modelContainer(sharedModelContainer) 36 | 37 | WindowGroup(Text("Core Simulator (Devices)"), id: "CoreSimulators", for: CoreSimulator_User.self) { value in 38 | CoreSimulatorsRootView() 39 | } 40 | .defaultPosition(.topLeading) 41 | .defaultSize(width: 1440, height: 1080) 42 | 43 | WindowGroup(Text("Xcode Playground Devices (XCPGDevices)"), id: "XCPGDevices", for: Directories.self) { value in 44 | if let dir = value.wrappedValue, dir == .xcPGDevices { 45 | XCPGDevicesRootView() 46 | } 47 | } 48 | .defaultPosition(.topLeading) 49 | .defaultSize(width: 1440, height: 1080) 50 | 51 | WindowGroup(Text("Device Inspector"), id: "CoreSimInspectDevice", for: CoreSimulatorDevice.self) { value in 52 | CoreSimDeviceInspectView(device: value) 53 | } 54 | 55 | Settings { 56 | AppPreferencesView() 57 | } 58 | .defaultPosition(.center) 59 | .defaultSize(width: 480, height: 720) 60 | .windowResizability(.contentMinSize) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Chinotto/ChinottoMenuBarApp.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ChinottoMenuBarApp.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-28. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct ChinottoMenuBarApp: View { 11 | @Environment(\.openWindow) var openWindow 12 | @Environment(\.dismissWindow) var dismissWindow 13 | 14 | @State private var directories: [StorageViewModel] = [ 15 | .init(directory: .coreSimulator), 16 | .init(directory: .xcode), 17 | .init(directory: .xcPGDevices), 18 | .init(directory: .xcTestDevices), 19 | .init(directory: .developerDiskImages), 20 | .init(directory: .toolchains), 21 | ] 22 | 23 | var body: some View { 24 | DirectoriesStorageView(viewModels: $directories) 25 | .frame(width: 480, height: 720) 26 | .environment(\.horizontalSizeClass, .compact) 27 | .safeAreaInset(edge: .top) { 28 | HStack { 29 | Text("Chinotto") 30 | .fontWeight(.medium) 31 | .foregroundStyle(.secondary) 32 | Spacer() 33 | Button("Open App...") { 34 | openWindow(id: "Main Window") 35 | dismissWindow() 36 | } 37 | .buttonStyle(.borderedProminent) 38 | .tint(.accentColor) 39 | } 40 | .padding(8) 41 | .background(.regularMaterial) 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Chinotto/ContentView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContentView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-12. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct ContentView: View { 11 | @State private var selectedXcodeVersion: XcodeVersion = .default 12 | 13 | @State private var viewModels: [StorageViewModel] 14 | @State private var selectedViewModel: StorageViewModel? 15 | 16 | @State private var selectedDir: Directories? 17 | @State private var selectedDetailItem: URL? 18 | @State private var selectedInspectorItem: URL? 19 | 20 | @State private var isPresentingDownloadsPopover: Bool = false 21 | 22 | init() { 23 | let viewModels = Directories.allCases.map { 24 | StorageViewModel(directory: $0) 25 | } 26 | _viewModels = .init(wrappedValue: viewModels) 27 | } 28 | 29 | var body: some View { 30 | NavigationSplitView { 31 | List(selection: $selectedDir) { 32 | Section { 33 | Button("Home", systemImage: "house.fill") { 34 | selectedDir = nil 35 | } 36 | .containerRelativeFrame(.horizontal, alignment: .leading) 37 | .controlSize(.large) 38 | } 39 | 40 | Section("/Developer (User)") { 41 | ForEach(Directories.allCases) { value in 42 | NavigationLink(value: value) { 43 | HStack(spacing: 10) { 44 | Group { 45 | Image(systemName: value.systemImage) 46 | .frame(alignment: .leading) 47 | } 48 | .frame(width: 12, alignment: .leading) 49 | Text(value.dirName) 50 | } 51 | } } 52 | } 53 | 54 | Section("/Developer (System)") { 55 | HStack(alignment: .center) { 56 | Button("Downloads", systemImage: "square.and.arrow.down.on.square.fill") { 57 | let url = URL(filePath: "/Library/Developer/CoreSimulator/Cryptex/Images/Inbox", directoryHint: .isDirectory) 58 | NSWorkspace.shared.activateFileViewerSelecting([url]) 59 | } 60 | .controlSize(.large) 61 | 62 | Button("", systemImage: "questionmark.circle") { 63 | isPresentingDownloadsPopover = true 64 | } 65 | .buttonStyle(.plain) 66 | .controlSize(.large) 67 | .popover(isPresented: $isPresentingDownloadsPopover) { 68 | downloadsPopover() 69 | } 70 | } 71 | } 72 | } 73 | .navigationSplitViewColumnWidth(min: 200, ideal: 240) 74 | .toolbar { 75 | ToolbarItem { 76 | SettingsLink { 77 | Image(systemName: "gear") 78 | .buttonBorderShape(.roundedRectangle) 79 | } 80 | } 81 | } 82 | } detail: { 83 | if let selectedDir { 84 | makeSelectedDirectoryView(selectedDir) 85 | .navigationSplitViewColumnWidth(min: 600, ideal: 720) 86 | } else { 87 | DirectoriesStorageView(viewModels: $viewModels) 88 | .navigationTitle("Chinotto") 89 | .navigationSplitViewColumnWidth(min: 600, ideal: 720) 90 | } 91 | } 92 | .navigationSplitViewStyle(.balanced) 93 | .toolbar { 94 | ToolbarItem(placement: .automatic) { 95 | Picker("Xcode", selection: $selectedXcodeVersion) { 96 | ForEach(XcodeVersion.allCases) { value in 97 | Text(value.description) 98 | } 99 | } 100 | } 101 | } 102 | } 103 | 104 | @ViewBuilder 105 | private func downloadsPopover() -> some View { 106 | ScrollView { 107 | VStack { 108 | HStack(spacing: 0) { 109 | Text("Downloads") 110 | .multilineTextAlignment(.leading) 111 | .lineLimit(nil) 112 | .fontWeight(.bold) 113 | .foregroundStyle(.primary) 114 | Spacer() 115 | } 116 | HStack(spacing: 0) { 117 | Text("This is where simulator images are stored when downloaded via Xcode.") 118 | .multilineTextAlignment(.leading) 119 | .lineLimit(nil) 120 | .font(.subheadline) 121 | .foregroundStyle(.primary) 122 | Spacer() 123 | } 124 | Divider() 125 | 126 | HStack { 127 | Image(systemName: "lightbulb.max") 128 | .resizable() 129 | .aspectRatio(contentMode: .fit) 130 | .frame(width: 24) 131 | .symbolEffect( 132 | .variableColor.iterative, 133 | options: .repeat(4), 134 | isActive: isPresentingDownloadsPopover 135 | ) 136 | .symbolRenderingMode(.palette) 137 | .foregroundStyle(Color.yellow, Color.blue) 138 | Text("Tip") 139 | .fontWeight(.black) 140 | .foregroundStyle(.primary) 141 | Spacer() 142 | } 143 | .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) 144 | 145 | HStack(spacing: 0) { 146 | Text("If download finishes, but Xcode is unable to install a simulator runtime (e.g. due to insufficient storage), you may wish to manually install the simulator, instead.\n\nRun \"`xcrun simctl runtime add`\" on the downloaded .dmg file here to do so.\n\nUsing Xcode's built-in reload button in the Download panel causes it to re-download the entire file, which is unnecessarily time-consuming.") 147 | .multilineTextAlignment(.leading) 148 | .lineLimit(nil) 149 | .foregroundStyle(.primary) 150 | } 151 | } 152 | .frame(width: 280) 153 | .padding(10) 154 | } 155 | } 156 | 157 | @ViewBuilder 158 | private func makeSelectedDirectoryView(_ directory: Directories) -> some View { 159 | switch directory { 160 | case .coreSimulator: 161 | CoreSimulatorView(directoryScope: .user) 162 | case .developerDiskImages: 163 | DeveloperDiskImagesView() 164 | case .toolchains: 165 | ToolchainsView() 166 | case .xcode: 167 | XcodeView() 168 | case .xcPGDevices: 169 | XCPGDevicesView() 170 | case .xcTestDevices: 171 | XCTestDevicesView() 172 | } 173 | } 174 | } 175 | 176 | #Preview { 177 | ContentView() 178 | } 179 | -------------------------------------------------------------------------------- /Chinotto/CoreSimulatorsRootView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CoreSimulatorsRootView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-16. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct CoreSimulatorsRootView: View { 11 | 12 | @State private var storageViewModel: StorageViewModel = .init(directory: .coreSimulator) 13 | 14 | var body: some View { 15 | @Bindable var vm = storageViewModel 16 | _CoreSimulatorDevicesView( 17 | dirScope: .user, 18 | storageViewModel: $vm 19 | ) 20 | } 21 | } 22 | 23 | #Preview { 24 | CoreSimulatorsRootView() 25 | } 26 | 27 | struct XCPGDevicesRootView: View { 28 | @State private var storageViewModel: StorageViewModel = .init(directory: .xcPGDevices) 29 | var body: some View { 30 | @Bindable var vm = storageViewModel 31 | _CoreSimulatorDevicesView( 32 | dirScope: .user, 33 | storageViewModel: $vm 34 | ) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/Directories.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Directories.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-12. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | import Charts 11 | import FileSystem 12 | 13 | /// A non-exhaustive list of top-level directories in `/Developer`. 14 | enum Directories: CaseIterable, Identifiable, Codable { 15 | case coreSimulator 16 | 17 | case xcode 18 | case xcPGDevices 19 | case xcTestDevices 20 | 21 | case developerDiskImages 22 | case toolchains 23 | 24 | var id: String { dirName } 25 | 26 | /// Base path for `/Developer` directory in current user's directory. 27 | static var userBasePath: String { 28 | "/Users/\(NSUserName())/Library/Developer" 29 | } 30 | 31 | /// Base path for `/Developer` directory not associated with any user. 32 | static var systemBasePath: String { 33 | "/Library/Developer" 34 | } 35 | 36 | var dirName: String { 37 | switch self { 38 | case .coreSimulator: 39 | "CoreSimulator" 40 | case .developerDiskImages: 41 | "DeveloperDiskImages" 42 | case .toolchains: 43 | "Toolchains" 44 | case .xcode: 45 | "Xcode" 46 | case .xcPGDevices: 47 | "XCPGDevices" 48 | case .xcTestDevices: 49 | "XCTestDevices" 50 | } 51 | } 52 | 53 | var userPath: String { 54 | "\(Self.userBasePath)/\(dirName)" 55 | } 56 | 57 | var systemPath: String { 58 | "\(Self.systemBasePath)/\(dirName)" 59 | } 60 | 61 | func path(scope: DirectoryScope) -> String { 62 | switch scope { 63 | case .system: 64 | systemPath 65 | case .user: 66 | userPath 67 | } 68 | } 69 | 70 | var systemImage: String { 71 | switch self { 72 | case .coreSimulator: 73 | "apps.iphone" 74 | case .developerDiskImages: 75 | "externaldrive.fill" 76 | case .toolchains: 77 | "screwdriver" 78 | case .xcode: 79 | "wrench.and.screwdriver.fill" 80 | case .xcPGDevices: 81 | "circle.filled.iphone" 82 | case .xcTestDevices: 83 | "circle.filled.iphone.fill" 84 | } 85 | } 86 | } 87 | 88 | extension Directories { 89 | 90 | var accentColor: Color { 91 | switch self { 92 | case .coreSimulator: 93 | Color.orange 94 | case .developerDiskImages: 95 | Color.purple 96 | case .toolchains: 97 | .teal 98 | case .xcode: 99 | Color.blue 100 | case .xcPGDevices: 101 | Color.pink 102 | case .xcTestDevices: 103 | Color.mint 104 | } 105 | } 106 | } 107 | 108 | extension Directories: Plottable { 109 | var primitivePlottable: String { 110 | dirName 111 | } 112 | 113 | init?(primitivePlottable: String) { 114 | if let match = Directories.allCases.first(where: { $0.dirName == primitivePlottable }) { 115 | self = match 116 | } else { 117 | return nil 118 | } 119 | } 120 | 121 | typealias PrimitivePlottable = String 122 | 123 | 124 | } 125 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/Scoped Directory Views/CachesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CachesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct CachesView: View { 11 | 12 | let directory: CoreSimulator 13 | 14 | var body: some View { 15 | switch directory.directoryScope { 16 | case .system: 17 | _CoreSimulatorSystemCachesView() 18 | case .user: 19 | _CoreSimulatorUserCachesView() 20 | } 21 | } 22 | } 23 | 24 | #Preview { 25 | CachesView(directory: CoreSimulator_User.caches) 26 | } 27 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/Scoped Directory Views/_CoreSimulatorDevicesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // _CoreSimulatorDevicesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-15. 6 | // 7 | 8 | import SwiftUI 9 | import Charts 10 | import CoreSimulatorTools 11 | import CoreSimulatorUI 12 | import DestructiveActions 13 | 14 | @Observable 15 | final class CoreSimulatorDevicesViewModel { 16 | let directory: Directories 17 | let dirScope: DirectoryScope 18 | init(directory: Directories, dirScope: DirectoryScope) { 19 | self.directory = directory 20 | self.dirScope = dirScope 21 | } 22 | 23 | var devices: [CoreSimulatorDevice] = [] 24 | 25 | func loadDevices() { 26 | let path = directory.path(scope: dirScope) 27 | 28 | let url: URL 29 | if directory == .coreSimulator { 30 | url = URL(string: path)!.appending(path: "Devices", directoryHint: .isDirectory) 31 | } else { 32 | url = URL(string: path)! 33 | } 34 | 35 | let contents: [URL] 36 | do { 37 | contents = try FileManager.default.contentsOfDirectory( 38 | at: url, 39 | includingPropertiesForKeys: [.isRegularFileKey, .isDirectoryKey], 40 | options: [.skipsPackageDescendants, .skipsHiddenFiles] 41 | ) 42 | 43 | let devices: [CoreSimulatorDevice] = try contents.compactMap { deviceDir in 44 | guard deviceDir.hasDirectoryPath else { return nil } 45 | 46 | let deviceContents = try FileManager.default.contentsOfDirectory( 47 | at: deviceDir, 48 | includingPropertiesForKeys: [.isRegularFileKey, .isDirectoryKey], 49 | options: [.skipsPackageDescendants, .skipsHiddenFiles] 50 | ) 51 | 52 | let devicePlist = deviceContents.first { $0.lastPathComponent == "device.plist" } 53 | let dataDir = deviceContents.first { $0.lastPathComponent == "data" } 54 | if let devicePlist, let dataDir, let uuid = UUID(uuidString: deviceDir.lastPathComponent) { 55 | return CoreSimulatorDevice(root: deviceDir, uuid: uuid, plist: devicePlist, data: dataDir) 56 | } else { 57 | return nil 58 | } 59 | } 60 | 61 | self.devices = devices 62 | } catch { 63 | print(error) 64 | } 65 | } 66 | } 67 | 68 | struct _CoreSimulatorDevicesView: View { 69 | 70 | @AppStorage("preferences.general.deletionBehaviour") var deletionBehaviour: DeletionBehaviour = .moveToTrash 71 | 72 | @Environment(\.openWindow) var openWindow 73 | 74 | @Bindable var storageViewModel: StorageViewModel 75 | @State private var devicesViewModel: CoreSimulatorDevicesViewModel 76 | 77 | @State private var selectedDevices: Set = .init() 78 | @State private var tableSortOrder = [KeyPathComparator(\CoreSimulatorDevice.totalSize)] 79 | 80 | @State private var isPresentingInspectorViewForDevice = true 81 | @State private var deviceForInspectorView: CoreSimulatorDevice? = nil 82 | 83 | @State private var isPresentingDeleteDeviceAlert = false 84 | 85 | @State private var isPresentingDeleteErrorAlert = false 86 | @State private var deleteError: DestructiveActionError? 87 | 88 | private let dateTimeFormatter: RelativeDateTimeFormatter = .init() 89 | 90 | init(dirScope: DirectoryScope, storageViewModel: Bindable) { 91 | _storageViewModel = storageViewModel 92 | _devicesViewModel = .init( 93 | wrappedValue: .init( 94 | directory: storageViewModel.wrappedValue.directory, 95 | dirScope: dirScope 96 | ) 97 | ) 98 | } 99 | 100 | private var isSelectingMultipleDevices: Bool { 101 | selectedDevices.count > 1 102 | } 103 | 104 | private var selectedDevicesSize: Int { 105 | devicesViewModel.devices 106 | .filter { devices in 107 | selectedDevices.contains { selected in selected == devices.id } 108 | } 109 | .reduce(0) { $0 + $1.totalSize } 110 | } 111 | 112 | private func selectedCoreSimDevices() -> [CoreSimulatorDevice] { 113 | devicesViewModel.devices 114 | .filter { devices in 115 | selectedDevices.contains { selected in selected == devices.id } 116 | } 117 | } 118 | 119 | var body: some View { 120 | Group { 121 | tableView() 122 | .padding(.top, 80 + 64) 123 | .overlay(alignment: .top) { 124 | VStack { 125 | GroupBox { 126 | storageChartView() 127 | } 128 | 129 | GroupBox { 130 | HStack { 131 | Spacer() 132 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(selectedDevicesSize), countStyle: .file))") 133 | Button("Delete selected (\(selectedDevices.count))...", role: .destructive) { 134 | isPresentingDeleteDeviceAlert = true 135 | } 136 | .buttonStyle(.borderedProminent) 137 | .tint(.red) 138 | .disabled(selectedDevices.isEmpty) 139 | } 140 | .frame(height: 36) 141 | .padding(.horizontal, 12) 142 | } 143 | } 144 | .padding(8) 145 | } 146 | .task { 147 | devicesViewModel.loadDevices() 148 | } 149 | } 150 | .inspector(isPresented: $isPresentingInspectorViewForDevice) { 151 | if let deviceForInspectorView { 152 | /// [2023.11] Using `device.isLoadingDataContents` here triggers SwiftUI recursive loop for some reason. 153 | CoreSimDeviceView(device: $deviceForInspectorView) 154 | .inspectorColumnWidth(min: 480, ideal: 520, max: 720) /// [2023.11] This was crashing on some builds on relaunch (state restoration) for some reason. 155 | } else { 156 | GroupBox { 157 | Text("Double-click to select a device") 158 | .foregroundStyle(.secondary) 159 | } 160 | } 161 | } 162 | .alert("Are you sure you wish to permanently delete\n\"^[\(selectedDevices.count) device](inflect: true)\"?", isPresented: $isPresentingDeleteDeviceAlert) { 163 | Button("Cancel", role: .cancel) { 164 | 165 | } 166 | Button("Delete", role: .destructive) { 167 | defer { selectedDevices.removeAll() } 168 | let devices = selectedCoreSimDevices() 169 | devices.forEach { device in 170 | do { 171 | try FileManager.default.delete(coreSimDevice: device, moveToTrash: deletionBehaviour == .moveToTrash) 172 | if let index = devicesViewModel.devices.firstIndex(where: { $0.id == device.id }) { 173 | devicesViewModel.devices.remove(at: index) 174 | } 175 | } catch { 176 | if let error = error as? DestructiveActionError { 177 | isPresentingDeleteErrorAlert = true 178 | deleteError = error 179 | } 180 | } 181 | } 182 | } 183 | } message: { 184 | Text("This operation cannot be reversed.\n\nYou may wish to backup test data associated with this device before proceeding.") 185 | } 186 | } 187 | 188 | @ViewBuilder 189 | private func tableView() -> some View { 190 | Table( 191 | devicesViewModel.devices.filter { !$0.isDeleted }, 192 | selection: $selectedDevices, 193 | sortOrder: $tableSortOrder 194 | ) { 195 | TableColumn("Device Name", value: \.name) { value in 196 | HStack { 197 | Text(value.name) 198 | Spacer() 199 | Image(systemName: "chevron.forward") 200 | .foregroundStyle(.secondary) 201 | .onTapGesture { 202 | openWindow(id: "CoreSimulatorDevice", value: value) 203 | } 204 | } 205 | } 206 | .width(min: 200, ideal: 240, max: .infinity) 207 | 208 | TableColumn("Size", value: \.totalSize) { value in 209 | if let totalSize = value.size { 210 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(totalSize), countStyle: .file))") 211 | } else { 212 | ProgressView() 213 | .controlSize(.small) 214 | } 215 | } 216 | .width(min: 100, ideal: 144, max: 144) 217 | 218 | TableColumn("Date Added", value: \.creationDate) { value in 219 | Text("\(dateTimeFormatter.localizedString(for: value.creationDate, relativeTo: Date()))") 220 | } 221 | .width(min: 120, ideal: 144, max: 180) 222 | 223 | /// Not very useful, since /tmp directory gets updated often. [2023.11] 224 | // TableColumn("Last Modified", value: \.contentModificationDate) { value in 225 | // Text("\(dateTimeFormatter.localizedString(for: value.contentModificationDate, relativeTo: Date()))") 226 | // } 227 | 228 | TableColumn("Last Boot Time", value: \.lastBootedAt) { value in 229 | if value.lastBootedAt == .distantPast { 230 | Text("Never Booted") 231 | } else { 232 | Text("\(dateTimeFormatter.localizedString(for: value.lastBootedAt, relativeTo: Date()))") 233 | } 234 | } 235 | .width(min: 120, ideal: 144, max: 180) 236 | 237 | TableColumn("Device Kind", value: \.deviceKind) { value in 238 | HStack(spacing: 10) { 239 | Group { 240 | Image(systemName: value.deviceKind.systemImage) 241 | .frame(alignment: .trailing) 242 | } 243 | .frame(width: 12, alignment: .trailing) 244 | Text(value.deviceKind.description) 245 | } 246 | } 247 | .width(min: 100, ideal: 144, max: 144) 248 | } 249 | .contextMenu(forSelectionType: CoreSimulatorDevice.ID.self) { items in 250 | if items.isEmpty { 251 | Button("Show in Finder", action: {}) 252 | .disabled(true) 253 | } else { 254 | Button { 255 | let devicesToShow = devicesViewModel.devices.filter { devices in 256 | items.contains { selected in selected == devices.id } 257 | } 258 | let fileUrls = devicesToShow.compactMap { $0.root } 259 | NSWorkspace.shared.activateFileViewerSelecting(fileUrls) 260 | } label: { 261 | let text = items.count > 1 ? "Show in Finder (\(items.count))" : "Show in Finder" 262 | Text(text) 263 | } 264 | } 265 | } primaryAction: { deviceIds in 266 | for id in deviceIds { 267 | if let device = devicesViewModel.devices.first(where: { $0.id == id }) { 268 | isPresentingInspectorViewForDevice = true 269 | deviceForInspectorView = device 270 | // openWindow(id: "CoreSimulatorDevice", value: device) 271 | } 272 | } 273 | } 274 | .onChange(of: tableSortOrder) { _, sortOrder in 275 | devicesViewModel.devices.sort(using: sortOrder) 276 | } 277 | } 278 | 279 | @ViewBuilder 280 | private func listView() -> some View { 281 | List { 282 | ForEach(devicesViewModel.devices) { value in 283 | GroupBox { 284 | HStack { 285 | Text("\(value.devicePlist?.name ?? value.uuid.uuidString)") 286 | if let metadata = value.dataContents?.metadata { 287 | let totalSize = metadata.reduce(0) { $0 + $1.size } 288 | Text("[\(ByteCountFormatter.string(fromByteCount: Int64(totalSize), countStyle: .file))]") 289 | } 290 | } 291 | } 292 | .containerRelativeFrame(.horizontal) 293 | .onTapGesture { 294 | /// Open new window for device. 295 | value.dirsMetadata = storageViewModel.dirMetadata 296 | value.filesMetadata = storageViewModel.fileMetadata 297 | openWindow(id: "CoreSimulatorDevice", value: value) 298 | } 299 | } 300 | } 301 | } 302 | 303 | @ViewBuilder 304 | private func storageChartView() -> some View { 305 | let sizeForAllDevices = devicesViewModel.devices.reduce(0) { $0 + $1.totalSize } 306 | let volumeTotalCapacity = devicesViewModel.devices.first?.root.volumeTotalCapacity() ?? 0 307 | let maxValue = volumeTotalCapacity 308 | let xAxisValues = [ 309 | Int64(0), 310 | Int64(((maxValue/2)/2)), 311 | Int64((maxValue/2)), 312 | Int64((Double(maxValue/2)*1.5)), 313 | Int64(maxValue) 314 | ] 315 | Chart { 316 | Plot { 317 | BarMark(x: .value("Size", sizeForAllDevices)) 318 | .cornerRadius(6, style: .continuous) 319 | .annotation(position: .overlay) { 320 | GroupBox { 321 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(sizeForAllDevices), countStyle: .file))") 322 | } 323 | } 324 | } 325 | } 326 | .chartXAxisLabel(position: .top) { 327 | let count = devicesViewModel.devices.filter { $0.dataContents == nil }.count 328 | if count > 0 { 329 | Text("Disk Space Used - Calculating \(count) ^[of \(devicesViewModel.devices.count) device](inflect: true)") 330 | } else { 331 | Text("Disk Space Used - ^[Showing \(devicesViewModel.devices.count) device](inflect: true)") 332 | } 333 | } 334 | .chartXAxis { 335 | AxisMarks( 336 | format: .byteCount(style: .memory, allowedUnits: .all, spellsOutZero: true, includesActualByteCount: false), 337 | values: xAxisValues 338 | ) 339 | } 340 | .chartXScale(domain: [0, volumeTotalCapacity]) 341 | .chartYAxis(.hidden) 342 | .chartLegend(.hidden) 343 | .frame(height: 64) 344 | } 345 | } 346 | 347 | #Preview { 348 | _CoreSimulatorDevicesView( 349 | dirScope: .user, 350 | storageViewModel: .init(.init(directory: .developerDiskImages)) 351 | ) 352 | } 353 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/Scoped Directory Views/_CoreSimulatorSystemCachesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // _CoreSImulatorSystemCachesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct _CoreSimulatorSystemCachesView: View { 11 | var body: some View { 12 | Text("_CoreSimulatorSystemCachesView") 13 | } 14 | } 15 | 16 | #Preview { 17 | _CoreSimulatorSystemCachesView() 18 | } 19 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/Scoped Directory Views/_CoreSimulatorSystemView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // _CoreSimulatorSystemView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct _CoreSimulatorSystemView: View { 11 | var body: some View { 12 | Text("_CoreSimulatorSystemView") 13 | } 14 | } 15 | 16 | #Preview { 17 | _CoreSimulatorSystemView() 18 | } 19 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/Scoped Directory Views/_CoreSimulatorUserCachesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // _CoreSimulatorUserCachesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct _CoreSimulatorUserCachesView: View { 11 | var body: some View { 12 | Text("_CoreSimulatorUserCachesView") 13 | } 14 | } 15 | 16 | #Preview { 17 | _CoreSimulatorUserCachesView() 18 | } 19 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/Scoped Directory Views/_CoreSimulatorUserView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // _CoreSimulatorUserView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct _CoreSimulatorUserView: View { 11 | 12 | @Environment(\.openWindow) var openWindow 13 | 14 | @State private var storageViewModel: StorageViewModel = .init(directory: .coreSimulator) 15 | 16 | var body: some View { 17 | VSplitView { 18 | List { 19 | Section { 20 | EmptyView() 21 | } header: { 22 | Text("/CoreSimulator") 23 | } 24 | 25 | StorageView(viewModel: storageViewModel) 26 | 27 | ForEach(CoreSimulator_User.allCases) { value in 28 | Section { 29 | GroupBox { 30 | VStack { 31 | HStack { 32 | Text("/\(value.dirName)") 33 | .fontWeight(.bold) 34 | Spacer() 35 | if value == .devices { 36 | Button("Inspect Devices...") { 37 | openWindow(id: "CoreSimulators", value: value) 38 | } 39 | .tint(.accentColor) 40 | .buttonStyle(.borderedProminent) 41 | } else { 42 | Button("Show in Finder") { 43 | let url = URL(filePath: value.dirPath, directoryHint: .isDirectory) 44 | NSWorkspace.shared.activateFileViewerSelecting([url]) 45 | } 46 | } 47 | } 48 | Divider() 49 | HStack { 50 | Text("\(value.dirDescription)") 51 | .fontWeight(.medium) 52 | Spacer() 53 | } 54 | } 55 | .padding(2) 56 | } 57 | } 58 | } 59 | } 60 | .listStyle(.inset) 61 | } 62 | } 63 | } 64 | 65 | #Preview { 66 | _CoreSimulatorUserView() 67 | } 68 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/Subdirectories.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Subdirectories.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import Foundation 9 | 10 | enum DirectoryScope { 11 | case system 12 | case user 13 | } 14 | 15 | protocol CoreSimulator { 16 | var directoryScope: DirectoryScope { get } 17 | var dirName: String { get } 18 | var dirDescription: String { get } 19 | } 20 | 21 | /// `/Users/{username}/Library/Developer/CoreSimulator` 22 | enum CoreSimulator_User: CoreSimulator, CaseIterable, Identifiable, Codable { 23 | case devices 24 | case caches 25 | case temp 26 | 27 | var id: String { dirName } 28 | 29 | var directoryScope: DirectoryScope { .user } 30 | var dirName: String { 31 | switch self { 32 | case .caches: 33 | "Caches" 34 | case .devices: 35 | "Devices" 36 | case .temp: 37 | "Temp" 38 | } 39 | } 40 | var dirPath: String { 41 | "\(Self.basePath)/\(dirName)" 42 | } 43 | var dirDescription: String { 44 | switch self { 45 | case .caches: 46 | "This is where the Dynamic Linker for various simulator runtimes are stored (e.g. iOS, watchOS, tvOS)." 47 | case .devices: 48 | "This is where all the simulator devices that have been downloaded are stored, and typically consumes the most storage space." 49 | case .temp: 50 | "Temporary files associated with any simulators are stored here. This directory doesn't appear to contain anything of much permanent interest." 51 | } 52 | } 53 | 54 | static var basePath: String { 55 | "/Users/\(NSUserName())/Library/Developer/CoreSimulator" 56 | } 57 | } 58 | 59 | /// `/Library/Developer/CoreSimulator` 60 | enum CoreSimulator_System: CoreSimulator, CaseIterable, Identifiable { 61 | case caches 62 | case cryptex 63 | case images 64 | case volumes 65 | 66 | var id: String { dirName } 67 | 68 | var directoryScope: DirectoryScope { .system } 69 | var dirName: String { 70 | switch self { 71 | case .caches: 72 | "Caches" 73 | case .cryptex: 74 | "Cryptex" 75 | case .images: 76 | "Images" 77 | case .volumes: 78 | "Volumes" 79 | } 80 | } 81 | var dirDescription: String { 82 | switch self { 83 | case .caches: 84 | "" 85 | case .cryptex: 86 | "" 87 | case .images: 88 | "" 89 | case .volumes: 90 | "" 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/User Scope/CoreSimulatorView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CoreSimulatorView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct CoreSimulatorView: View { 11 | 12 | /// The /CoreSimulator directory to show. 13 | /// 14 | /// Each scope's file contents are different. 15 | let directoryScope: DirectoryScope 16 | 17 | var body: some View { 18 | switch directoryScope { 19 | case .system: 20 | _CoreSimulatorSystemView() 21 | case .user: 22 | _CoreSimulatorUserView() 23 | } 24 | } 25 | } 26 | 27 | #Preview { 28 | CoreSimulatorView(directoryScope: .user) 29 | } 30 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/User Scope/DeveloperDiskImagesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DeveloperDiskImagesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct SizeMetadata: Identifiable { 11 | var id: String { key.absoluteString } 12 | 13 | let key: URL 14 | let value: String 15 | } 16 | 17 | struct DeveloperDiskImagesView: View { 18 | 19 | @State private var storageViewModel: StorageViewModel = .init(directory: .developerDiskImages) 20 | 21 | @State private var selectedFiles: Set = .init() 22 | @State private var selectedDirs: Set = .init() 23 | 24 | var body: some View { 25 | VSplitView { 26 | List { 27 | Section { 28 | Button("Show in Finder") { 29 | let url = URL(filePath: storageViewModel.directory.path(scope: .user), directoryHint: .isDirectory) 30 | NSWorkspace.shared.activateFileViewerSelecting([url]) 31 | } 32 | } header: { 33 | Text("/\(storageViewModel.directory.dirName)") 34 | } 35 | 36 | StorageView(viewModel: storageViewModel) 37 | 38 | ForEach(storageViewModel.dirMetadata.sorted(by: { lhs, rhs in lhs.value > rhs.value }), id: \.key) { key, value in 39 | GroupBox { 40 | Text("\(key.lastPathComponent) - \(value)") 41 | .font(.footnote) 42 | } 43 | } 44 | 45 | Section("Description") { 46 | Text("Manually managing this directory is not recommended.") 47 | } 48 | } 49 | .listStyle(.inset) 50 | } 51 | } 52 | 53 | private func showFilesInFinder() { 54 | let filePaths = selectedFiles 55 | let fileUrls = filePaths.compactMap { URL(string: $0 ) } 56 | NSWorkspace.shared.activateFileViewerSelecting(fileUrls) 57 | } 58 | 59 | private func showDirsInFinder() { 60 | let dirPaths = selectedDirs 61 | let dirUrls = dirPaths.compactMap { URL(string: $0 ) } 62 | NSWorkspace.shared.activateFileViewerSelecting(dirUrls) 63 | } 64 | } 65 | 66 | #Preview { 67 | DeveloperDiskImagesView() 68 | } 69 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/User Scope/ToolchainsView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ToolchainsView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct ToolchainsView: View { 11 | 12 | @State private var storageViewModel: StorageViewModel = .init(directory: .toolchains) 13 | 14 | @State private var selectedFiles: Set = .init() 15 | @State private var selectedDirs: Set = .init() 16 | 17 | var body: some View { 18 | VSplitView { 19 | List { 20 | Section { 21 | Button("Show in Finder") { 22 | let url = URL(filePath: storageViewModel.directory.path(scope: .user), directoryHint: .isDirectory) 23 | NSWorkspace.shared.activateFileViewerSelecting([url]) 24 | } 25 | } header: { 26 | Text("/\(storageViewModel.directory.dirName)") 27 | } 28 | 29 | StorageView(viewModel: storageViewModel) 30 | 31 | Section("Description") { 32 | Text("Recommended: Manage Toolchains using Xcode's built-in tool (Xcode > Toolchains > Manage Toolchains...).") 33 | } 34 | } 35 | .listStyle(.inset) 36 | } 37 | } 38 | 39 | private func showFilesInFinder() { 40 | let filePaths = selectedFiles 41 | let fileUrls = filePaths.compactMap { URL(string: $0 ) } 42 | NSWorkspace.shared.activateFileViewerSelecting(fileUrls) 43 | } 44 | 45 | private func showDirsInFinder() { 46 | let dirPaths = selectedDirs 47 | let dirUrls = dirPaths.compactMap { URL(string: $0 ) } 48 | NSWorkspace.shared.activateFileViewerSelecting(dirUrls) 49 | } 50 | } 51 | 52 | #Preview { 53 | ToolchainsView() 54 | } 55 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/User Scope/XCPGDevicesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // XCPGDevicesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct XCPGDevicesView: View { 11 | @Environment(\.openWindow) var openWindow 12 | 13 | @State private var storageViewModel: StorageViewModel = .init(directory: .xcPGDevices) 14 | 15 | @State private var selectedFiles: Set = .init() 16 | @State private var selectedDirs: Set = .init() 17 | 18 | var body: some View { 19 | VSplitView { 20 | List { 21 | Section { 22 | Button("Show in Finder") { 23 | let url = URL(filePath: storageViewModel.directory.path(scope: .user), directoryHint: .isDirectory) 24 | NSWorkspace.shared.activateFileViewerSelecting([url]) 25 | } 26 | } header: { 27 | Text("/\(storageViewModel.directory.dirName)") 28 | } 29 | 30 | StorageView(viewModel: storageViewModel) 31 | 32 | Section("Description") { 33 | Text("Xcode Playground Devices.") 34 | Button("Inspect Devices...") { 35 | openWindow(id: "XCPGDevices", value: Directories.xcPGDevices) 36 | } 37 | } 38 | } 39 | .listStyle(.inset) 40 | } 41 | } 42 | 43 | private func showFilesInFinder() { 44 | let filePaths = selectedFiles 45 | let fileUrls = filePaths.compactMap { URL(string: $0 ) } 46 | NSWorkspace.shared.activateFileViewerSelecting(fileUrls) 47 | } 48 | 49 | private func showDirsInFinder() { 50 | let dirPaths = selectedDirs 51 | let dirUrls = dirPaths.compactMap { URL(string: $0 ) } 52 | NSWorkspace.shared.activateFileViewerSelecting(dirUrls) 53 | } 54 | } 55 | 56 | #Preview { 57 | XCPGDevicesView() 58 | } 59 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/User Scope/XCTestDevicesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // XCTestDevicesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct XCTestDevicesView: View { 11 | 12 | @State private var storageViewModel: StorageViewModel = .init(directory: .xcTestDevices) 13 | 14 | @State private var selectedFiles: Set = .init() 15 | @State private var selectedDirs: Set = .init() 16 | 17 | var body: some View { 18 | VSplitView { 19 | List { 20 | Section { 21 | Button("Show in Finder") { 22 | let url = URL(filePath: storageViewModel.directory.path(scope: .user), directoryHint: .isDirectory) 23 | NSWorkspace.shared.activateFileViewerSelecting([url]) 24 | } 25 | } header: { 26 | Text("/\(storageViewModel.directory.dirName)") 27 | } 28 | 29 | StorageView(viewModel: storageViewModel) 30 | 31 | Section("Description") { 32 | Text("Xcode Test Devices.") 33 | } 34 | } 35 | .listStyle(.inset) 36 | } 37 | } 38 | 39 | private func showFilesInFinder() { 40 | let filePaths = selectedFiles 41 | let fileUrls = filePaths.compactMap { URL(string: $0 ) } 42 | NSWorkspace.shared.activateFileViewerSelecting(fileUrls) 43 | } 44 | 45 | private func showDirsInFinder() { 46 | let dirPaths = selectedDirs 47 | let dirUrls = dirPaths.compactMap { URL(string: $0 ) } 48 | NSWorkspace.shared.activateFileViewerSelecting(dirUrls) 49 | } 50 | } 51 | 52 | #Preview { 53 | XCTestDevicesView() 54 | } 55 | -------------------------------------------------------------------------------- /Chinotto/Directories/Xcode 15/User Scope/XcodeView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // XcodeView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct XcodeView: View { 11 | 12 | @State private var storageViewModel: StorageViewModel = .init(directory: .xcode) 13 | 14 | @State private var selectedFiles: Set = .init() 15 | @State private var selectedDirs: Set = .init() 16 | 17 | var body: some View { 18 | VSplitView { 19 | List { 20 | Section { 21 | Button("Show in Finder") { 22 | let url = URL(filePath: storageViewModel.directory.path(scope: .user), directoryHint: .isDirectory) 23 | NSWorkspace.shared.activateFileViewerSelecting([url]) 24 | } 25 | } header: { 26 | Text("/\(storageViewModel.directory.dirName)") 27 | } 28 | 29 | StorageView(viewModel: storageViewModel) 30 | 31 | Section("Description") { 32 | Text("Xcode.app related directories.") 33 | } 34 | } 35 | .listStyle(.inset) 36 | } 37 | } 38 | 39 | private func showFilesInFinder() { 40 | let filePaths = selectedFiles 41 | let fileUrls = filePaths.compactMap { URL(string: $0 ) } 42 | NSWorkspace.shared.activateFileViewerSelecting(fileUrls) 43 | } 44 | 45 | private func showDirsInFinder() { 46 | let dirPaths = selectedDirs 47 | let dirUrls = dirPaths.compactMap { URL(string: $0 ) } 48 | NSWorkspace.shared.activateFileViewerSelecting(dirUrls) 49 | } 50 | } 51 | 52 | #Preview { 53 | XcodeView() 54 | } 55 | -------------------------------------------------------------------------------- /Chinotto/DirectoriesStorageView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DirectoriesStorageView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-13. 6 | // 7 | 8 | import SwiftUI 9 | 10 | /// Shows the storage consumed for each directory, separately. 11 | struct DirectoriesStorageView: View { 12 | @Environment(\.horizontalSizeClass) var horizontalSizeClass 13 | @Binding var viewModels: [StorageViewModel] 14 | 15 | init(viewModels: Binding<[StorageViewModel]>) { 16 | _viewModels = viewModels 17 | } 18 | 19 | var body: some View { 20 | ScrollView { 21 | LazyVStack(spacing: 12, pinnedViews: .sectionHeaders) { 22 | Section { 23 | UnifiedStorageView(viewModels: $viewModels) 24 | } header: { 25 | HStack { 26 | Text("All Directories") 27 | .fontWeight(.medium) 28 | .padding(8) 29 | } 30 | .background(.regularMaterial) 31 | .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) 32 | } 33 | 34 | Divider() 35 | 36 | Section { 37 | ForEach(viewModels) { value in 38 | StorageView(viewModel: value) 39 | .contextMenu { 40 | Button("Show in Finder") { 41 | let url = URL(filePath: value.directory.userPath, directoryHint: .isDirectory) 42 | NSWorkspace.shared.activateFileViewerSelecting([url]) 43 | } 44 | } 45 | } 46 | } header: { 47 | HStack { 48 | Text("By Directory") 49 | .fontWeight(.medium) 50 | .padding(8) 51 | } 52 | .background(.regularMaterial) 53 | .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) 54 | } 55 | } 56 | } 57 | .contentMargins(12) 58 | .contentMargins(-12, for: .scrollIndicators) 59 | } 60 | } 61 | 62 | #Preview { 63 | DirectoriesStorageView(viewModels: .constant([.init(directory: .developerDiskImages)])) 64 | } 65 | -------------------------------------------------------------------------------- /Chinotto/Localizable.xcstrings: -------------------------------------------------------------------------------- 1 | { 2 | "sourceLanguage" : "en", 3 | "strings" : { 4 | "" : { 5 | "localizations" : { 6 | "zh-Hans" : { 7 | "stringUnit" : { 8 | "state" : "translated", 9 | "value" : "" 10 | } 11 | } 12 | } 13 | }, 14 | "_CoreSimulatorSystemCachesView" : { 15 | "localizations" : { 16 | "zh-Hans" : { 17 | "stringUnit" : { 18 | "state" : "translated", 19 | "value" : "_CoreSimulatorSystemCachesView" 20 | } 21 | } 22 | } 23 | }, 24 | "_CoreSimulatorSystemView" : { 25 | "localizations" : { 26 | "zh-Hans" : { 27 | "stringUnit" : { 28 | "state" : "translated", 29 | "value" : "_CoreSimulatorSystemView" 30 | } 31 | } 32 | } 33 | }, 34 | "_CoreSimulatorUserCachesView" : { 35 | "localizations" : { 36 | "zh-Hans" : { 37 | "stringUnit" : { 38 | "state" : "translated", 39 | "value" : "_CoreSimulatorUserCachesView" 40 | } 41 | } 42 | } 43 | }, 44 | "[%@]" : { 45 | "localizations" : { 46 | "zh-Hans" : { 47 | "stringUnit" : { 48 | "state" : "translated", 49 | "value" : "[%@]" 50 | } 51 | } 52 | } 53 | }, 54 | "/%@" : { 55 | "localizations" : { 56 | "zh-Hans" : { 57 | "stringUnit" : { 58 | "state" : "translated", 59 | "value" : "/%@" 60 | } 61 | } 62 | } 63 | }, 64 | "/CoreSimulator" : { 65 | "localizations" : { 66 | "zh-Hans" : { 67 | "stringUnit" : { 68 | "state" : "translated", 69 | "value" : "/CoreSimulator" 70 | } 71 | } 72 | } 73 | }, 74 | "/Developer (System)" : { 75 | "localizations" : { 76 | "zh-Hans" : { 77 | "stringUnit" : { 78 | "state" : "translated", 79 | "value" : "/Developer (系统)" 80 | } 81 | } 82 | } 83 | }, 84 | "/Developer (User)" : { 85 | "localizations" : { 86 | "zh-Hans" : { 87 | "stringUnit" : { 88 | "state" : "translated", 89 | "value" : "/Developer (用户)" 90 | } 91 | } 92 | } 93 | }, 94 | "%.1f GB" : { 95 | "localizations" : { 96 | "zh-Hans" : { 97 | "stringUnit" : { 98 | "state" : "translated", 99 | "value" : "%.1f GB" 100 | } 101 | } 102 | } 103 | }, 104 | "%@" : { 105 | "localizations" : { 106 | "zh-Hans" : { 107 | "stringUnit" : { 108 | "state" : "translated", 109 | "value" : "%@" 110 | } 111 | } 112 | } 113 | }, 114 | "%@ - %lld" : { 115 | "localizations" : { 116 | "en" : { 117 | "stringUnit" : { 118 | "state" : "new", 119 | "value" : "%1$@ - %2$lld" 120 | } 121 | }, 122 | "zh-Hans" : { 123 | "stringUnit" : { 124 | "state" : "translated", 125 | "value" : "%1$@ - %2$lld" 126 | } 127 | } 128 | } 129 | }, 130 | "%@ ago" : { 131 | "localizations" : { 132 | "zh-Hans" : { 133 | "stringUnit" : { 134 | "state" : "translated", 135 | "value" : "%@ 前" 136 | } 137 | } 138 | } 139 | }, 140 | "%@ of %@" : { 141 | "localizations" : { 142 | "en" : { 143 | "stringUnit" : { 144 | "state" : "new", 145 | "value" : "%1$@ of %2$@" 146 | } 147 | }, 148 | "zh-Hans" : { 149 | "stringUnit" : { 150 | "state" : "translated", 151 | "value" : "%2$@ 中的 %1$@" 152 | } 153 | } 154 | } 155 | }, 156 | "All Directories" : { 157 | "localizations" : { 158 | "zh-Hans" : { 159 | "stringUnit" : { 160 | "state" : "translated", 161 | "value" : "所有目录" 162 | } 163 | } 164 | } 165 | }, 166 | "All Directories (%lld files)" : { 167 | "extractionState" : "stale", 168 | "localizations" : { 169 | "zh-Hans" : { 170 | "stringUnit" : { 171 | "state" : "translated", 172 | "value" : "所有目录 (%lld 个文件)" 173 | } 174 | } 175 | } 176 | }, 177 | "Are you sure you want to reset storage data?" : { 178 | "localizations" : { 179 | "zh-Hans" : { 180 | "stringUnit" : { 181 | "state" : "translated", 182 | "value" : "你确定要重置储存数据吗?" 183 | } 184 | } 185 | } 186 | }, 187 | "Are you sure you wish to permanently delete\n\"^[%lld device](inflect: true)\"?" : { 188 | "localizations" : { 189 | "zh-Hans" : { 190 | "stringUnit" : { 191 | "state" : "translated", 192 | "value" : "你确定要删除\n\"^[%lld 设备吗](inflect: true)\"?" 193 | } 194 | } 195 | } 196 | }, 197 | "By Directory" : { 198 | "localizations" : { 199 | "zh-Hans" : { 200 | "stringUnit" : { 201 | "state" : "translated", 202 | "value" : "按目录" 203 | } 204 | } 205 | } 206 | }, 207 | "Calculate" : { 208 | "localizations" : { 209 | "zh-Hans" : { 210 | "stringUnit" : { 211 | "state" : "translated", 212 | "value" : "计算" 213 | } 214 | } 215 | } 216 | }, 217 | "Calculating..." : { 218 | "localizations" : { 219 | "zh-Hans" : { 220 | "stringUnit" : { 221 | "state" : "translated", 222 | "value" : "计算中..." 223 | } 224 | } 225 | } 226 | }, 227 | "Cancel" : { 228 | "localizations" : { 229 | "zh-Hans" : { 230 | "stringUnit" : { 231 | "state" : "translated", 232 | "value" : "取消" 233 | } 234 | } 235 | } 236 | }, 237 | "Chinotto" : { 238 | "localizations" : { 239 | "zh-Hans" : { 240 | "stringUnit" : { 241 | "state" : "translated", 242 | "value" : "Chinotto" 243 | } 244 | } 245 | } 246 | }, 247 | "Chinotto Menu Bar App" : { 248 | "localizations" : { 249 | "zh-Hans" : { 250 | "stringUnit" : { 251 | "state" : "translated", 252 | "value" : "Chinotto 菜单栏应用" 253 | } 254 | } 255 | } 256 | }, 257 | "Core Simulator (Devices)" : { 258 | "localizations" : { 259 | "zh-Hans" : { 260 | "stringUnit" : { 261 | "state" : "translated", 262 | "value" : "Core Simulator (设备)" 263 | } 264 | } 265 | } 266 | }, 267 | "Data Category" : { 268 | "localizations" : { 269 | "zh-Hans" : { 270 | "stringUnit" : { 271 | "state" : "translated", 272 | "value" : "数据分类" 273 | } 274 | } 275 | } 276 | }, 277 | "Date Added" : { 278 | "localizations" : { 279 | "zh-Hans" : { 280 | "stringUnit" : { 281 | "state" : "translated", 282 | "value" : "添加日期" 283 | } 284 | } 285 | } 286 | }, 287 | "Delete" : { 288 | "localizations" : { 289 | "zh-Hans" : { 290 | "stringUnit" : { 291 | "state" : "translated", 292 | "value" : "删除" 293 | } 294 | } 295 | } 296 | }, 297 | "Delete selected (%lld)..." : { 298 | "localizations" : { 299 | "zh-Hans" : { 300 | "stringUnit" : { 301 | "state" : "translated", 302 | "value" : "删除选择的 (%lld) 个设备..." 303 | } 304 | } 305 | } 306 | }, 307 | "Deleted items are moved to Trash, where you may recover items, if needed." : { 308 | "extractionState" : "manual", 309 | "localizations" : { 310 | "zh-Hans" : { 311 | "stringUnit" : { 312 | "state" : "translated", 313 | "value" : "删除项目将被移到废纸篓,你可以在哪里恢复需要的项目" 314 | } 315 | } 316 | } 317 | }, 318 | "Deletion Behavior:" : { 319 | "localizations" : { 320 | "zh-Hans" : { 321 | "stringUnit" : { 322 | "state" : "translated", 323 | "value" : "删除选项: " 324 | } 325 | } 326 | } 327 | }, 328 | "Description" : { 329 | "localizations" : { 330 | "zh-Hans" : { 331 | "stringUnit" : { 332 | "state" : "translated", 333 | "value" : "描述" 334 | } 335 | } 336 | } 337 | }, 338 | "Device Inspector" : { 339 | "localizations" : { 340 | "zh-Hans" : { 341 | "stringUnit" : { 342 | "state" : "translated", 343 | "value" : "设备查看器" 344 | } 345 | } 346 | } 347 | }, 348 | "Device Kind" : { 349 | "localizations" : { 350 | "zh-Hans" : { 351 | "stringUnit" : { 352 | "state" : "translated", 353 | "value" : "设备类型" 354 | } 355 | } 356 | } 357 | }, 358 | "Device Name" : { 359 | "localizations" : { 360 | "zh-Hans" : { 361 | "stringUnit" : { 362 | "state" : "translated", 363 | "value" : "设备名称" 364 | } 365 | } 366 | } 367 | }, 368 | "Directory Size" : { 369 | "localizations" : { 370 | "zh-Hans" : { 371 | "stringUnit" : { 372 | "state" : "translated", 373 | "value" : "目录大小" 374 | } 375 | } 376 | } 377 | }, 378 | "Disk Space Used" : { 379 | "localizations" : { 380 | "zh-Hans" : { 381 | "stringUnit" : { 382 | "state" : "translated", 383 | "value" : "磁盘空间使用" 384 | } 385 | } 386 | } 387 | }, 388 | "Disk Space Used - ^[Showing %lld device](inflect: true)" : { 389 | "localizations" : { 390 | "zh-Hans" : { 391 | "stringUnit" : { 392 | "state" : "translated", 393 | "value" : "已使用的磁盘空间 - ^[正在显示 %lld 个设备](inflect: true)" 394 | } 395 | } 396 | } 397 | }, 398 | "Disk Space Used - Calculating %lld ^[of %lld device](inflect: true)" : { 399 | "localizations" : { 400 | "en" : { 401 | "stringUnit" : { 402 | "state" : "new", 403 | "value" : "Disk Space Used - Calculating %1$lld ^[of %2$lld device](inflect: true)" 404 | } 405 | }, 406 | "zh-Hans" : { 407 | "stringUnit" : { 408 | "state" : "translated", 409 | "value" : "已使用的磁盘空间 - 正在计算 %2$lld 中的第 %1$lld 个设备" 410 | } 411 | } 412 | } 413 | }, 414 | "Dismiss" : { 415 | "localizations" : { 416 | "zh-Hans" : { 417 | "stringUnit" : { 418 | "state" : "translated", 419 | "value" : "关闭" 420 | } 421 | } 422 | } 423 | }, 424 | "Double-click to select a device" : { 425 | "localizations" : { 426 | "zh-Hans" : { 427 | "stringUnit" : { 428 | "state" : "translated", 429 | "value" : "双击以选择设备" 430 | } 431 | } 432 | } 433 | }, 434 | "Downloads" : { 435 | "localizations" : { 436 | "zh-Hans" : { 437 | "stringUnit" : { 438 | "state" : "translated", 439 | "value" : "下载" 440 | } 441 | } 442 | } 443 | }, 444 | "Error" : { 445 | "localizations" : { 446 | "zh-Hans" : { 447 | "stringUnit" : { 448 | "state" : "translated", 449 | "value" : "错误" 450 | } 451 | } 452 | } 453 | }, 454 | "General" : { 455 | "localizations" : { 456 | "zh-Hans" : { 457 | "stringUnit" : { 458 | "state" : "translated", 459 | "value" : "通用" 460 | } 461 | } 462 | } 463 | }, 464 | "Hide windows when app launches on login" : { 465 | "localizations" : { 466 | "zh-Hans" : { 467 | "stringUnit" : { 468 | "state" : "translated", 469 | "value" : "在应用于登录时启动后不显示窗口" 470 | } 471 | } 472 | } 473 | }, 474 | "Home" : { 475 | "localizations" : { 476 | "zh-Hans" : { 477 | "stringUnit" : { 478 | "state" : "translated", 479 | "value" : "主页" 480 | } 481 | } 482 | } 483 | }, 484 | "If download finishes, but Xcode is unable to install a simulator runtime (e.g. due to insufficient storage), you may wish to manually install the simulator, instead.\n\nRun \"`xcrun simctl runtime add`\" on the downloaded .dmg file here to do so.\n\nUsing Xcode's built-in reload button in the Download panel causes it to re-download the entire file, which is unnecessarily time-consuming." : { 485 | "localizations" : { 486 | "zh-Hans" : { 487 | "stringUnit" : { 488 | "state" : "translated", 489 | "value" : "如果下载完成,但 Xcode 无法安装 Simulator 运行环境 (例如: 储存空间不足),你可能需要手动安装 Simulator\n\n在下载好的 .dmg 文件上运行 \"`xcrun simctl runtime add`\" 来手动安装\n\n使用 Xcode Download 页面内置的重试按钮会重新下载整个文件,这是不必要的费时操作" 490 | } 491 | } 492 | } 493 | }, 494 | "Inspect Devices..." : { 495 | "localizations" : { 496 | "zh-Hans" : { 497 | "stringUnit" : { 498 | "state" : "translated", 499 | "value" : "检查设备" 500 | } 501 | } 502 | } 503 | }, 504 | "Last Boot Time" : { 505 | "localizations" : { 506 | "zh-Hans" : { 507 | "stringUnit" : { 508 | "state" : "translated", 509 | "value" : "上次启动时间" 510 | } 511 | } 512 | } 513 | }, 514 | "Last Updated: %@" : { 515 | "localizations" : { 516 | "zh-Hans" : { 517 | "stringUnit" : { 518 | "state" : "translated", 519 | "value" : "上次更新: %@" 520 | } 521 | } 522 | } 523 | }, 524 | "Last Updated: Never" : { 525 | "localizations" : { 526 | "zh-Hans" : { 527 | "stringUnit" : { 528 | "state" : "translated", 529 | "value" : "上次更新: 从未" 530 | } 531 | } 532 | } 533 | }, 534 | "Launch app on login" : { 535 | "localizations" : { 536 | "zh-Hans" : { 537 | "stringUnit" : { 538 | "state" : "translated", 539 | "value" : "在登录时启动应用" 540 | } 541 | } 542 | } 543 | }, 544 | "Manage \"Login Items\"..." : { 545 | "localizations" : { 546 | "zh-Hans" : { 547 | "stringUnit" : { 548 | "state" : "translated", 549 | "value" : "管理\"登录项\"..." 550 | } 551 | } 552 | } 553 | }, 554 | "Manually managing this directory is not recommended." : { 555 | "localizations" : { 556 | "zh-Hans" : { 557 | "stringUnit" : { 558 | "state" : "translated", 559 | "value" : "不推荐手动管理该目录" 560 | } 561 | } 562 | } 563 | }, 564 | "Menu Bar" : { 565 | "localizations" : { 566 | "zh-Hans" : { 567 | "stringUnit" : { 568 | "state" : "translated", 569 | "value" : "菜单栏" 570 | } 571 | } 572 | } 573 | }, 574 | "Move to Trash" : { 575 | "extractionState" : "manual", 576 | "localizations" : { 577 | "zh-Hans" : { 578 | "stringUnit" : { 579 | "state" : "translated", 580 | "value" : "移到废纸篓" 581 | } 582 | } 583 | } 584 | }, 585 | "Never" : { 586 | "localizations" : { 587 | "zh-Hans" : { 588 | "stringUnit" : { 589 | "state" : "translated", 590 | "value" : "从未" 591 | } 592 | } 593 | } 594 | }, 595 | "Never Booted" : { 596 | "localizations" : { 597 | "zh-Hans" : { 598 | "stringUnit" : { 599 | "state" : "translated", 600 | "value" : "从未启动" 601 | } 602 | } 603 | } 604 | }, 605 | "Open App..." : { 606 | "localizations" : { 607 | "zh-Hans" : { 608 | "stringUnit" : { 609 | "state" : "translated", 610 | "value" : "打开应用..." 611 | } 612 | } 613 | } 614 | }, 615 | "Open at Login" : { 616 | "localizations" : { 617 | "zh-Hans" : { 618 | "stringUnit" : { 619 | "state" : "translated", 620 | "value" : "登录时启动" 621 | } 622 | } 623 | } 624 | }, 625 | "Permanently Delete" : { 626 | "extractionState" : "manual", 627 | "localizations" : { 628 | "zh-Hans" : { 629 | "stringUnit" : { 630 | "state" : "translated", 631 | "value" : "永久删除" 632 | } 633 | } 634 | } 635 | }, 636 | "Previously opened windows will not be restored on launch." : { 637 | "localizations" : { 638 | "zh-Hans" : { 639 | "stringUnit" : { 640 | "state" : "translated", 641 | "value" : "先前打开的窗口将不会在启动后恢复" 642 | } 643 | } 644 | } 645 | }, 646 | "Recommended: Manage Toolchains using Xcode's built-in tool (Xcode > Toolchains > Manage Toolchains...)." : { 647 | "localizations" : { 648 | "zh-Hans" : { 649 | "stringUnit" : { 650 | "state" : "translated", 651 | "value" : "推荐: 使用 Xcode 内置工具来管理 Toolchains (Xcode > Toolchains > Manage Toolchains...)" 652 | } 653 | } 654 | } 655 | }, 656 | "Reset" : { 657 | "localizations" : { 658 | "zh-Hans" : { 659 | "stringUnit" : { 660 | "state" : "translated", 661 | "value" : "重置" 662 | } 663 | } 664 | } 665 | }, 666 | "Reset Storage Data..." : { 667 | "localizations" : { 668 | "zh-Hans" : { 669 | "stringUnit" : { 670 | "state" : "translated", 671 | "value" : "重置储存数据..." 672 | } 673 | } 674 | } 675 | }, 676 | "Select a directory" : { 677 | "extractionState" : "manual", 678 | "localizations" : { 679 | "zh-Hans" : { 680 | "stringUnit" : { 681 | "state" : "translated", 682 | "value" : "选择目录" 683 | } 684 | } 685 | } 686 | }, 687 | "Show in Finder" : { 688 | "extractionState" : "manual", 689 | "localizations" : { 690 | "zh-Hans" : { 691 | "stringUnit" : { 692 | "state" : "translated", 693 | "value" : "在访达中显示" 694 | } 695 | } 696 | } 697 | }, 698 | "Show in Menu Bar (compact view)" : { 699 | "localizations" : { 700 | "zh-Hans" : { 701 | "stringUnit" : { 702 | "state" : "translated", 703 | "value" : "在菜单栏显示 (紧凑视图)" 704 | } 705 | } 706 | } 707 | }, 708 | "Size" : { 709 | "localizations" : { 710 | "zh-Hans" : { 711 | "stringUnit" : { 712 | "state" : "translated", 713 | "value" : "大小" 714 | } 715 | } 716 | } 717 | }, 718 | "Temporary files associated with any simulators are stored here. This directory doesn't appear to contain anything of much permanent interest." : { 719 | "extractionState" : "manual", 720 | "localizations" : { 721 | "zh-Hans" : { 722 | "stringUnit" : { 723 | "state" : "translated", 724 | "value" : "和所有 Simulator 相关联的临时文件都在这里储存,这个目录似乎不包含太多永久储存的文件" 725 | } 726 | } 727 | } 728 | }, 729 | "This includes disk usage statistics that may take some time to calculate." : { 730 | "localizations" : { 731 | "zh-Hans" : { 732 | "stringUnit" : { 733 | "state" : "translated", 734 | "value" : "这包括需要一些时间计算的磁盘使用数据" 735 | } 736 | } 737 | } 738 | }, 739 | "This is where all the simulator devices that have been downloaded are stored, and typically consumes the most storage space." : { 740 | "extractionState" : "manual", 741 | "localizations" : { 742 | "zh-Hans" : { 743 | "stringUnit" : { 744 | "state" : "translated", 745 | "value" : "这是所有下载的 Simulator 被储存的位置,而且一般占最多储存空间" 746 | } 747 | } 748 | } 749 | }, 750 | "This is where simulator images are stored when downloaded via Xcode." : { 751 | "localizations" : { 752 | "zh-Hans" : { 753 | "stringUnit" : { 754 | "state" : "translated", 755 | "value" : "Xcode 下载的 Simulator 镜像会保存在这里" 756 | } 757 | } 758 | } 759 | }, 760 | "This is where the Dynamic Linker for various simulator runtimes are stored (e.g. iOS, watchOS, tvOS)." : { 761 | "extractionState" : "manual", 762 | "localizations" : { 763 | "zh-Hans" : { 764 | "stringUnit" : { 765 | "state" : "translated", 766 | "value" : "这是储存各种 Simulator 运行环境 Dynamic Linker 的位置 (例如: iOS、watchOS、tvOS)" 767 | } 768 | } 769 | } 770 | }, 771 | "This operation cannot be reversed.\n\nYou may wish to backup test data associated with this device before proceeding." : { 772 | "localizations" : { 773 | "zh-Hans" : { 774 | "stringUnit" : { 775 | "state" : "translated", 776 | "value" : "这个操作将无法撤销\n\n你可能希望在继续前备份和该设备关联的测试数据" 777 | } 778 | } 779 | } 780 | }, 781 | "Tip" : { 782 | "localizations" : { 783 | "zh-Hans" : { 784 | "stringUnit" : { 785 | "state" : "translated", 786 | "value" : "提示" 787 | } 788 | } 789 | } 790 | }, 791 | "Warning: Recovery is not possible with this option. Deleted items are permanently removed from file system." : { 792 | "extractionState" : "manual", 793 | "localizations" : { 794 | "zh-Hans" : { 795 | "stringUnit" : { 796 | "state" : "translated", 797 | "value" : "警告: 该选项无法恢复,删除的项目将永久从文件系统上移除" 798 | } 799 | } 800 | } 801 | }, 802 | "Xcode" : { 803 | "localizations" : { 804 | "zh-Hans" : { 805 | "stringUnit" : { 806 | "state" : "translated", 807 | "value" : "Xcode" 808 | } 809 | } 810 | } 811 | }, 812 | "Xcode Playground Devices (XCPGDevices)" : { 813 | "localizations" : { 814 | "zh-Hans" : { 815 | "stringUnit" : { 816 | "state" : "translated", 817 | "value" : "Xcode Playground 设备 (XCPGDevices)" 818 | } 819 | } 820 | } 821 | }, 822 | "Xcode Playground Devices." : { 823 | "localizations" : { 824 | "zh-Hans" : { 825 | "stringUnit" : { 826 | "state" : "translated", 827 | "value" : "Xcode Playground 设备" 828 | } 829 | } 830 | } 831 | }, 832 | "Xcode Test Devices." : { 833 | "localizations" : { 834 | "zh-Hans" : { 835 | "stringUnit" : { 836 | "state" : "translated", 837 | "value" : "Xcode 测试设备" 838 | } 839 | } 840 | } 841 | }, 842 | "Xcode.app related directories." : { 843 | "localizations" : { 844 | "zh-Hans" : { 845 | "stringUnit" : { 846 | "state" : "translated", 847 | "value" : "Xcode.app 相关目录" 848 | } 849 | } 850 | } 851 | } 852 | }, 853 | "version" : "1.0" 854 | } -------------------------------------------------------------------------------- /Chinotto/LoginItemBehaviour.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LoginItemBehaviour.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-12-04. 6 | // 7 | 8 | import Foundation 9 | import AppKit 10 | 11 | #if os(macOS) 12 | struct LoginItemBehaviour { 13 | private static var openAtLogin: Bool { 14 | UserDefaults.standard.bool(forKey: "openAtLogin") 15 | } 16 | 17 | private static var hideWindowsOnLaunch: Bool { 18 | UserDefaults.standard.bool(forKey: "hideWindowsOnLaunch") 19 | } 20 | 21 | static func hideWindowsOnDidFinishLaunching(_ windows: [NSWindow], _ notification: Notification) { 22 | for window in windows { 23 | if openAtLogin == true, 24 | hideWindowsOnLaunch == true, 25 | let isDefaultLaunch = notification.userInfo?[NSApplication.launchIsDefaultUserInfoKey] as? Bool, 26 | isDefaultLaunch == false { 27 | /// Menu bar app window and menu bar item window aren't restorable. 28 | if window.isRestorable { 29 | window.close() 30 | } 31 | } 32 | } 33 | } 34 | } 35 | #endif 36 | -------------------------------------------------------------------------------- /Chinotto/Preferences/AppPreferencesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppPreferencesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-14. 6 | // 7 | 8 | import SwiftUI 9 | 10 | /// App Preferences (Settigns). 11 | struct AppPreferencesView: View { 12 | 13 | private enum Tabs: Hashable { 14 | case general, advanced 15 | } 16 | 17 | @State private var selectedTab: Tabs = .general 18 | 19 | var body: some View { 20 | TabView(selection: $selectedTab) { 21 | GeneralPreferencesView() 22 | .tabItem { 23 | Label("General", systemImage: "gear") 24 | } 25 | .tag(Tabs.general) 26 | } 27 | .frame(minWidth: 480, minHeight: 320) 28 | } 29 | } 30 | 31 | #Preview { 32 | AppPreferencesView() 33 | } 34 | -------------------------------------------------------------------------------- /Chinotto/Preferences/GeneralPreferencesView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // GeneralPreferencesView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-21. 6 | // 7 | 8 | import SwiftUI 9 | import DestructiveActions 10 | import ServiceManagement 11 | 12 | struct GeneralPreferencesView: View { 13 | 14 | @AppStorage("openAtLogin") private var openAtLogin = false 15 | @AppStorage("hideWindowsOnLaunch") private var hideWindowsOnLaunch = false 16 | @AppStorage("showMenuBarExtra") private var showMenuBarExtra = true 17 | @AppStorage("preferences.general.deletionBehaviour") var deletionBehaviour: DeletionBehaviour = .moveToTrash 18 | 19 | @State private var openAtLoginError: Error? 20 | @State private var isPresentingResetStorageDataAlert = false 21 | 22 | var body: some View { 23 | List { 24 | Form { 25 | Section { 26 | LabeledContent("Menu Bar") { 27 | Toggle("Show in Menu Bar (compact view)", isOn: $showMenuBarExtra) 28 | } 29 | 30 | LabeledContent("Open at Login") { 31 | Toggle("Launch app on login", isOn: $openAtLogin) 32 | } 33 | .onChange(of: openAtLogin) { 34 | if openAtLogin { 35 | do { 36 | try SMAppService.mainApp.register() 37 | } catch { 38 | openAtLogin = false 39 | openAtLoginError = error 40 | } 41 | } else { 42 | SMAppService.mainApp.unregister { error in 43 | openAtLogin = false 44 | openAtLoginError = error 45 | } 46 | } 47 | } 48 | Toggle("Hide windows when app launches on login", isOn: $hideWindowsOnLaunch) 49 | .disabled(openAtLogin == false) 50 | 51 | if hideWindowsOnLaunch, openAtLogin { 52 | GroupBox { 53 | HStack { 54 | Image(systemName: "exclamationmark.triangle") 55 | .foregroundStyle(.red) 56 | .fontWeight(.bold) 57 | Text("Previously opened windows will not be restored on launch.") 58 | .lineLimit(nil) 59 | } 60 | } 61 | .frame(maxWidth: 320) 62 | } 63 | 64 | Button("Manage \"Login Items\"...") { 65 | SMAppService.openSystemSettingsLoginItems() 66 | } 67 | } 68 | 69 | Spacer(minLength: 24) 70 | .frame(height: 24) 71 | 72 | Section { 73 | Picker("Deletion Behavior:", selection: $deletionBehaviour) { 74 | ForEach(DeletionBehaviour.allCases) { value in 75 | Text(value.description).tag(value) 76 | } 77 | } 78 | .pickerStyle(.inline) 79 | 80 | GroupBox { 81 | HStack { 82 | Image(systemName: deletionBehaviour.systemImage) 83 | .foregroundStyle(deletionBehaviour.accentColor) 84 | .fontWeight(.bold) 85 | Text(deletionBehaviour.behaviourDescription) 86 | .lineLimit(nil) 87 | } 88 | } 89 | .frame(maxWidth: 320) 90 | } 91 | 92 | Spacer(minLength: 24) 93 | .frame(height: 24) 94 | 95 | Section { 96 | Button("Reset Storage Data...") { 97 | isPresentingResetStorageDataAlert = true 98 | } 99 | GroupBox { 100 | HStack { 101 | Image(systemName: "exclamationmark.triangle") 102 | .foregroundStyle(.red) 103 | .fontWeight(.bold) 104 | Text("This includes disk usage statistics that may take some time to calculate.") 105 | } 106 | } 107 | .frame(maxWidth: 320) 108 | } 109 | } 110 | } 111 | .alert("Error", isPresented: .init(get: { 112 | openAtLoginError != nil 113 | }, set: { _ in 114 | // no-op 115 | }), presenting: openAtLoginError, actions: { error in 116 | Button("Dismiss", role: .cancel) { } 117 | }) 118 | .alert("Are you sure you want to reset storage data?", isPresented: $isPresentingResetStorageDataAlert) { 119 | Button("Cancel", role: .cancel) { } 120 | Button("Reset", role: .destructive) { 121 | Directories.allCases 122 | .map { StorageViewModel(directory: $0).appStorageKeys } 123 | .flatMap { $0 } 124 | .forEach { UserDefaults.standard.setValue(nil, forKey: $0) } 125 | } 126 | } 127 | } 128 | } 129 | 130 | #Preview { 131 | GeneralPreferencesView() 132 | .frame(width: 480, height: 600) 133 | } 134 | -------------------------------------------------------------------------------- /Chinotto/Preview Content/Preview Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Chinotto/StorageView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // StorageView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-12. 6 | // 7 | 8 | import SwiftUI 9 | import Charts 10 | 11 | @Observable 12 | final class StorageViewModel: Identifiable { 13 | 14 | let directory: Directories 15 | init(directory: Directories) { 16 | self.directory = directory 17 | self.volumeTotalCapacity = URL(filePath: directory.userPath, directoryHint: .isDirectory).volumeTotalCapacity() 18 | } 19 | 20 | private enum AppStorageKeys: CaseIterable { 21 | case lastUpdated 22 | case dirFileCount, dirSize 23 | 24 | func key(_ directory: Directories) -> String { 25 | switch self { 26 | case .lastUpdated: 27 | "\(directory.dirName).dirSize.lastUpdated.appStorage.key" 28 | case .dirFileCount: 29 | "\(directory.dirName).dirFileCount.appStorage.key" 30 | case .dirSize: 31 | "\(directory.dirName).dirSize.appStorage.key" 32 | } 33 | } 34 | } 35 | 36 | var appStorageKeys: [String] { 37 | AppStorageKeys.allCases.map { $0.key(directory) } 38 | } 39 | 40 | /// timeIntervalSinceReferenceDate 41 | var lastUpdated: TimeInterval { 42 | get { 43 | access(keyPath: \.lastUpdated) 44 | let value = UserDefaults.standard.double(forKey: AppStorageKeys.lastUpdated.key(directory)) 45 | return value == 0 ? Date.distantPast.timeIntervalSinceReferenceDate : value 46 | } 47 | set { 48 | withMutation(keyPath: \.lastUpdated) { 49 | UserDefaults.standard.setValue(newValue, forKey: AppStorageKeys.lastUpdated.key(directory)) 50 | } 51 | } 52 | } 53 | 54 | @ObservationIgnored 55 | private var performedInitialLoad = false 56 | var isCalculating = false 57 | 58 | var volumeTotalCapacity: Int? 59 | var dirFileCount: Int { 60 | get { 61 | access(keyPath: \.dirFileCount) 62 | return UserDefaults.standard.integer(forKey: AppStorageKeys.dirFileCount.key(directory)) 63 | } 64 | set { 65 | withMutation(keyPath: \.dirFileCount) { 66 | UserDefaults.standard.setValue(newValue, forKey: AppStorageKeys.dirFileCount.key(directory)) 67 | } 68 | } 69 | } 70 | var dirSize: Int { 71 | get { 72 | access(keyPath: \.dirSize) 73 | return UserDefaults.standard.integer(forKey: AppStorageKeys.dirSize.key(directory)) 74 | } 75 | set { 76 | withMutation(keyPath: \.dirSize) { 77 | UserDefaults.standard.setValue(newValue, forKey: AppStorageKeys.dirSize.key(directory)) 78 | } 79 | } 80 | } 81 | 82 | var axisValues: [Int64] { 83 | let maxValue = volumeTotalCapacity ?? dirSize 84 | let values = [ 85 | Int64(0), 86 | Int64(((maxValue/2)/2)), 87 | Int64((maxValue/2)), 88 | Int64((Double(maxValue/2)*1.5)), 89 | Int64(maxValue) 90 | ] 91 | return values 92 | } 93 | 94 | func beginCalculating() { 95 | isCalculating = true 96 | } 97 | 98 | func endCalculating() { 99 | isCalculating = false 100 | } 101 | 102 | private(set) var dirMetadata: [URL: Int] = [:] 103 | private(set) var fileMetadata: [URL: Int] = [:] 104 | private(set) var dirSizeMetadata: [SizeMetadata] = [] 105 | private(set) var fileSizeMetadata: [SizeMetadata] = [] 106 | 107 | /// - Parameter initial: If `true`, only calculates size if not yet calculated. 108 | @MainActor 109 | func calculateSize(initial: Bool, recalculate: Bool, shallowMetadata: Bool = false) async { 110 | defer { performedInitialLoad = true } 111 | 112 | if initial, performedInitialLoad == true { 113 | return 114 | } 115 | 116 | if !recalculate, dirSize != 0 { 117 | return 118 | } 119 | 120 | isCalculating = true 121 | 122 | #if CALCULATE_STORAGE_METADATA 123 | let count = URL.directoryContentsCount(url: .init(filePath: directory.userPath, directoryHint: .isDirectory)) 124 | self.dirFileCount = count 125 | var dirMetadata: [URL: Int] = [:] 126 | var fileMetadata: [URL: Int] = [:] 127 | let size = URL.directorySize(url: .init(filePath: directory.userPath, directoryHint: .isDirectory), dirMetadata: &dirMetadata, fileMetadata: &fileMetadata) 128 | self.dirMetadata = dirMetadata 129 | self.fileMetadata = fileMetadata 130 | self.dirSizeMetadata = dirMetadata 131 | .sorted(by: { lhs, rhs in lhs.value > rhs.value }) 132 | .map { 133 | SizeMetadata( 134 | key: $0.key, 135 | value: ByteCountFormatter.string( 136 | fromByteCount: Int64($0.value), 137 | countStyle: .file 138 | ) 139 | ) 140 | } 141 | self.fileSizeMetadata = fileMetadata 142 | .sorted(by: { lhs, rhs in lhs.value > rhs.value }) 143 | .map { 144 | SizeMetadata( 145 | key: $0.key, 146 | value: ByteCountFormatter.string( 147 | fromByteCount: Int64($0.value), 148 | countStyle: .file 149 | ) 150 | ) 151 | } 152 | #else 153 | self.dirSize = await URL.directorySize( 154 | url: .init(filePath: directory.userPath, directoryHint: .isDirectory) 155 | ) 156 | #endif 157 | 158 | isCalculating = false 159 | 160 | lastUpdated = Date().timeIntervalSinceReferenceDate 161 | } 162 | 163 | private let byteCountFormatter = ByteCountFormatter() 164 | var dirSizeFormattedString: String { 165 | byteCountFormatter 166 | .string(fromByteCount: Int64(dirSize)) 167 | } 168 | var volumeTotalCapacityFormattedString: String { 169 | byteCountFormatter 170 | .string(fromByteCount: Int64(volumeTotalCapacity ?? 0)) 171 | } 172 | } 173 | 174 | struct StorageView: View { 175 | 176 | @Environment(\.horizontalSizeClass) var horizontalSizeClass 177 | @Bindable var viewModel: StorageViewModel 178 | 179 | private var sizeClass: UserInterfaceSizeClass { 180 | horizontalSizeClass ?? .regular 181 | } 182 | 183 | var body: some View { 184 | Group { 185 | HStack { 186 | Spacer() 187 | if sizeClass == .regular { 188 | lastUpdated() 189 | } 190 | } 191 | // .offset(y: 8) 192 | GroupBox { 193 | VStack { 194 | HStack { 195 | Text("\(viewModel.directory.dirName)") 196 | Spacer() 197 | Text("\(viewModel.dirSizeFormattedString) of \(viewModel.volumeTotalCapacityFormattedString)") 198 | 199 | Button { 200 | reload() 201 | } label: { 202 | HStack { 203 | if viewModel.isCalculating { 204 | if sizeClass == .regular { 205 | Text("Calculating...") 206 | } 207 | ProgressView() 208 | .controlSize(.small) 209 | } else { 210 | if sizeClass == .regular { 211 | Text("Calculate") 212 | } else { 213 | lastUpdated() 214 | } 215 | Image(systemName: "arrow.clockwise") 216 | } 217 | } 218 | } 219 | .disabled(viewModel.isCalculating) 220 | } 221 | 222 | chartView() 223 | } 224 | } 225 | } 226 | } 227 | 228 | private func reload() { 229 | Task(priority: .userInitiated) { 230 | await viewModel.calculateSize(initial: false, recalculate: true) 231 | } 232 | } 233 | 234 | @ViewBuilder 235 | private func chartView() -> some View { 236 | switch sizeClass { 237 | case .compact: 238 | compactChartView() 239 | case .regular: 240 | regularChartView() 241 | @unknown default: 242 | regularChartView() 243 | } 244 | } 245 | 246 | @ViewBuilder 247 | private func regularChartView() -> some View { 248 | Chart { 249 | Plot { 250 | BarMark( 251 | x: .value("Directory Size", viewModel.dirSize) 252 | ) 253 | .foregroundStyle(viewModel.directory.accentColor) 254 | /// Use by(.value) to automatically vary foreground style (colour) based on data. 255 | // .foregroundStyle(by: .value("Data Category", viewModel.directory.dirName)) 256 | // .annotation(position: .overlay) { 257 | // Text("\(viewModel.annotationText)") 258 | // .fontWeight(.bold) 259 | // .background(.regularMaterial) 260 | // } 261 | } 262 | .accessibilityLabel(viewModel.directory.dirName) 263 | .accessibilityValue("\(viewModel.dirSize, specifier: "%.1f") GB") 264 | } 265 | .chartPlotStyle { plotArea in 266 | plotArea 267 | #if os(macOS) 268 | .background(viewModel.directory.accentColor.opacity(0.2)) 269 | // .background(Color.gray.opacity(0.2)) 270 | #else 271 | .background(viewModel.directory.accentColor.opacity(0.2)) 272 | // .background(Color(.systemFill)) 273 | #endif 274 | .cornerRadius(8) 275 | } 276 | // .accessibilityChartDescriptor(self) 277 | // .chartXAxis(.hidden) 278 | // .chartXScale(domain: 0...128) 279 | .chartXAxis { 280 | AxisMarks( 281 | format: .byteCount(style: .memory, allowedUnits: .all, spellsOutZero: true, includesActualByteCount: false), 282 | values: viewModel.axisValues 283 | ) 284 | } 285 | .chartXScale(domain: [0, viewModel.volumeTotalCapacity ?? viewModel.dirSize]) 286 | .chartXAxisLabel(position: .top) { 287 | Text("Disk Space Used") 288 | } 289 | .chartYAxis(.hidden) 290 | // .chartYScale(range: .plotDimension(endPadding: -8)) 291 | // .chartLegend(position: .top, spacing: 8) 292 | .chartLegend(.hidden) 293 | .frame(height: 64) 294 | } 295 | 296 | @ViewBuilder 297 | private func compactChartView() -> some View { 298 | Chart { 299 | Plot { 300 | BarMark( 301 | x: .value("Directory Size", viewModel.dirSize) 302 | ) 303 | .foregroundStyle(viewModel.directory.accentColor) 304 | } 305 | .accessibilityLabel(viewModel.directory.dirName) 306 | .accessibilityValue("\(viewModel.dirSize, specifier: "%.1f") GB") 307 | } 308 | .chartPlotStyle { plotArea in 309 | plotArea 310 | #if os(macOS) 311 | .background(viewModel.directory.accentColor.opacity(0.2)) 312 | #else 313 | .background(viewModel.directory.accentColor.opacity(0.2)) 314 | #endif 315 | .cornerRadius(8) 316 | } 317 | .chartXAxis { 318 | AxisMarks( 319 | format: .byteCount(style: .memory, allowedUnits: .all, spellsOutZero: true, includesActualByteCount: false), 320 | values: viewModel.axisValues 321 | ) 322 | } 323 | .chartXScale(domain: [0, viewModel.volumeTotalCapacity ?? viewModel.dirSize]) 324 | .chartXAxisLabel(position: .top) { 325 | switch sizeClass { 326 | case .compact: 327 | EmptyView() 328 | case .regular: 329 | Text("Disk Space Used") 330 | @unknown default: 331 | Text("Disk Space Used") 332 | } 333 | } 334 | .chartYAxis(.hidden) 335 | .chartLegend(.hidden) 336 | .frame(height: 40) 337 | } 338 | 339 | @ViewBuilder 340 | private func lastUpdated() -> some View { 341 | switch sizeClass { 342 | case .compact: 343 | if Date(timeIntervalSinceReferenceDate: viewModel.lastUpdated) == .distantPast { 344 | Text("Never") 345 | .font(.headline) 346 | .fontWeight(.regular) 347 | } else { 348 | Text("\(Date(timeIntervalSinceReferenceDate: viewModel.lastUpdated), style: .relative) ago") 349 | .font(.headline) 350 | .fontWeight(.regular) 351 | } 352 | case .regular: 353 | if Date(timeIntervalSinceReferenceDate: viewModel.lastUpdated) == .distantPast { 354 | Text("Last Updated: Never") 355 | .font(.headline) 356 | .fontWeight(.regular) 357 | .foregroundStyle(.secondary) 358 | } else { 359 | Text("Last Updated: \(Date(timeIntervalSinceReferenceDate: viewModel.lastUpdated), style: .relative)") 360 | .font(.headline) 361 | .fontWeight(.regular) 362 | .foregroundStyle(.secondary) 363 | } 364 | @unknown default: 365 | if Date(timeIntervalSinceReferenceDate: viewModel.lastUpdated) == .distantPast { 366 | Text("Never") 367 | .font(.headline) 368 | .fontWeight(.regular) 369 | .foregroundStyle(.secondary) 370 | } else { 371 | Text("\(Date(timeIntervalSinceReferenceDate: viewModel.lastUpdated), style: .relative)") 372 | .font(.headline) 373 | .fontWeight(.regular) 374 | .foregroundStyle(.secondary) 375 | } 376 | } 377 | } 378 | } 379 | 380 | #Preview { 381 | StorageView(viewModel: .init(directory: .developerDiskImages)) 382 | } 383 | -------------------------------------------------------------------------------- /Chinotto/UnifiedStorageView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // UnifiedStorageView.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-13. 6 | // 7 | 8 | import SwiftUI 9 | import Charts 10 | 11 | /// Shows storage consumed for all directories in a unified view. 12 | struct UnifiedStorageView: View { 13 | @Environment(\.horizontalSizeClass) var horizontalSizeClass 14 | @Binding var viewModels: [StorageViewModel] 15 | @State private var isReloading = false 16 | 17 | private var sizeClass: UserInterfaceSizeClass { 18 | horizontalSizeClass ?? .regular 19 | } 20 | 21 | var body: some View { 22 | GroupBox { 23 | VStack { 24 | HStack { 25 | Text("All Directories") 26 | Spacer() 27 | let storage = viewModels.reduce(0) { $0 + $1.dirSize } 28 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(storage), countStyle: .decimal)) of \(ByteCountFormatter.string(fromByteCount: Int64(viewModels.first?.volumeTotalCapacity ?? 0), countStyle: .decimal))") 29 | 30 | Button { 31 | reload() 32 | } label: { 33 | HStack { 34 | if isReloading { 35 | Text("Calculating...") 36 | ProgressView() 37 | .controlSize(.small) 38 | } else { 39 | Text("Calculate") 40 | Image(systemName: "arrow.clockwise") 41 | } 42 | } 43 | } 44 | .disabled(isReloading) 45 | } 46 | 47 | chartView() 48 | .contextMenu { 49 | Button("Show in Finder") { 50 | let url = URL(filePath: Directories.userBasePath, directoryHint: .isDirectory) 51 | NSWorkspace.shared.activateFileViewerSelecting([url]) 52 | } 53 | } 54 | } 55 | } 56 | } 57 | 58 | private func reload() { 59 | isReloading = true 60 | viewModels.forEach { $0.beginCalculating() } 61 | 62 | Task { 63 | await withTaskGroup(of: Void.self, returning: Void.self) { taskGroup in 64 | viewModels.forEach { viewModel in 65 | taskGroup.addTask(priority: .userInitiated) { 66 | await viewModel.calculateSize(initial: false, recalculate: true) 67 | } 68 | } 69 | } 70 | Task { @MainActor in 71 | viewModels.forEach { $0.endCalculating() } 72 | isReloading = false 73 | } 74 | } 75 | } 76 | 77 | @ViewBuilder 78 | private func chartView() -> some View { 79 | Chart(viewModels) { value in 80 | Plot { 81 | BarMark( 82 | x: .value("Directory Size", value.dirSize) 83 | ) 84 | // .foregroundStyle(value.directory.accentColor) 85 | .foregroundStyle(by: .value("Data Category", value.directory.dirName)) 86 | } 87 | /// This causes crash on scroll, why? [2023.11] 88 | // .accessibilityLabel(value.directory.dirName) 89 | } 90 | .chartForegroundStyleScale( 91 | domain: Directories.allCases, 92 | range: Directories.allCases.compactMap { $0.accentColor } 93 | ) 94 | .chartXScale(domain: [0, viewModels.first?.volumeTotalCapacity ?? 0]) 95 | .chartXAxis { 96 | AxisMarks( 97 | format: .byteCount(style: .memory, allowedUnits: .all, spellsOutZero: true, includesActualByteCount: false), 98 | values: viewModels.first?.axisValues ?? [] 99 | ) 100 | } 101 | .chartXAxisLabel(position: .top) { 102 | switch sizeClass { 103 | case .compact: 104 | EmptyView() 105 | case .regular: 106 | Text("Disk Space Used") 107 | @unknown default: 108 | Text("Disk Space Used") 109 | } 110 | } 111 | .chartPlotStyle { plotArea in 112 | plotArea 113 | #if os(macOS) 114 | .background(Color.gray.opacity(0.2)) 115 | #else 116 | .background(Color(.systemFill)) 117 | #endif 118 | .cornerRadius(8) 119 | } 120 | .chartLegend(chartLegendVisibility) 121 | .frame(height: sizeClass == .compact ? 40 : 80) 122 | } 123 | 124 | private var chartLegendVisibility: Visibility { 125 | switch sizeClass { 126 | case .compact: 127 | .hidden 128 | case .regular: 129 | .visible 130 | @unknown default: 131 | .visible 132 | } 133 | } 134 | } 135 | 136 | #Preview { 137 | UnifiedStorageView(viewModels: .constant([.init(directory: .developerDiskImages)])) 138 | } 139 | -------------------------------------------------------------------------------- /Chinotto/XcodeVersion.swift: -------------------------------------------------------------------------------- 1 | // 2 | // XcodeVersion.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-17. 6 | // 7 | 8 | import Foundation 9 | 10 | enum XcodeVersion: String, CaseIterable, CustomStringConvertible, Identifiable { 11 | case v15 12 | 13 | var description: String { 14 | switch self { 15 | case .v15: 16 | "Xcode 15" 17 | } 18 | } 19 | 20 | var id: Self { 21 | self 22 | } 23 | 24 | /// The default version for any given year. 25 | static var `default`: XcodeVersion { 26 | .v15 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ChinottoTests/ChinottoTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ChinottoTests.swift 3 | // ChinottoTests 4 | // 5 | // Created by Bosco Ho on 2023-11-12. 6 | // 7 | 8 | import XCTest 9 | @testable import Chinotto 10 | 11 | final class ChinottoTests: XCTestCase { 12 | 13 | override func setUpWithError() throws { 14 | // Put setup code here. This method is called before the invocation of each test method in the class. 15 | } 16 | 17 | override func tearDownWithError() throws { 18 | // Put teardown code here. This method is called after the invocation of each test method in the class. 19 | } 20 | 21 | func testExample() throws { 22 | // This is an example of a functional test case. 23 | // Use XCTAssert and related functions to verify your tests produce the correct results. 24 | // Any test you write for XCTest can be annotated as throws and async. 25 | // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. 26 | // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. 27 | } 28 | 29 | func testPerformanceExample() throws { 30 | // This is an example of a performance test case. 31 | self.measure { 32 | // Put the code you want to measure the time of here. 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /ChinottoUITests/ChinottoUITests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ChinottoUITests.swift 3 | // ChinottoUITests 4 | // 5 | // Created by Bosco Ho on 2023-11-12. 6 | // 7 | 8 | import XCTest 9 | 10 | final class ChinottoUITests: XCTestCase { 11 | 12 | override func setUpWithError() throws { 13 | // Put setup code here. This method is called before the invocation of each test method in the class. 14 | 15 | // In UI tests it is usually best to stop immediately when a failure occurs. 16 | continueAfterFailure = false 17 | 18 | // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. 19 | } 20 | 21 | override func tearDownWithError() throws { 22 | // Put teardown code here. This method is called after the invocation of each test method in the class. 23 | } 24 | 25 | func testExample() throws { 26 | // UI tests must launch the application that they test. 27 | let app = XCUIApplication() 28 | app.launch() 29 | 30 | // Use XCTAssert and related functions to verify your tests produce the correct results. 31 | } 32 | 33 | func testLaunchPerformance() throws { 34 | if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { 35 | // This measures how long it takes to launch your application. 36 | measure(metrics: [XCTApplicationLaunchMetric()]) { 37 | XCUIApplication().launch() 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /ChinottoUITests/ChinottoUITestsLaunchTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ChinottoUITestsLaunchTests.swift 3 | // ChinottoUITests 4 | // 5 | // Created by Bosco Ho on 2023-11-12. 6 | // 7 | 8 | import XCTest 9 | 10 | final class ChinottoUITestsLaunchTests: XCTestCase { 11 | 12 | override class var runsForEachTargetApplicationUIConfiguration: Bool { 13 | true 14 | } 15 | 16 | override func setUpWithError() throws { 17 | continueAfterFailure = false 18 | } 19 | 20 | func testLaunch() throws { 21 | let app = XCUIApplication() 22 | app.launch() 23 | 24 | // Insert steps here to perform after app launch but before taking a screenshot, 25 | // such as logging into a test account or navigating somewhere in the app 26 | 27 | let attachment = XCTAttachment(screenshot: app.screenshot()) 28 | attachment.name = "Launch Screen" 29 | attachment.lifetime = .keepAlways 30 | add(attachment) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorTools/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorTools/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "CoreSimulatorTools", 8 | platforms: [.macOS(.v14)], 9 | products: [ 10 | // Products define the executables and libraries a package produces, making them visible to other packages. 11 | .library( 12 | name: "CoreSimulatorTools", 13 | targets: ["CoreSimulatorTools"]), 14 | ], 15 | targets: [ 16 | // Targets are the basic building blocks of a package, defining a module or a test suite. 17 | // Targets can depend on other targets in this package and products from dependencies. 18 | .target( 19 | name: "CoreSimulatorTools"), 20 | .testTarget( 21 | name: "CoreSimulatorToolsTests", 22 | dependencies: ["CoreSimulatorTools"]), 23 | ] 24 | ) 25 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorTools/Sources/CoreSimulatorTools/CoreSimDevice.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CoreSimDevice.swift 3 | // 4 | // 5 | // Created by Bosco Ho on 2023-11-15. 6 | // 7 | 8 | import Foundation 9 | 10 | public struct DevicePlist: Codable, Identifiable { 11 | public let UDID: String 12 | public let deviceType: String 13 | public var isDeleted: Bool 14 | public let isEphemeral: Bool 15 | public let lastBootedAt: Date? 16 | public let name: String 17 | public let runtime: String 18 | public let runtimePolicy: String 19 | public let state: Int 20 | 21 | public var id: String { UDID } 22 | } 23 | 24 | extension DevicePlist { 25 | var userInterfaceIdiom: DeviceIdiom { 26 | .idiom(for: self) 27 | } 28 | } 29 | 30 | @Observable 31 | public final class CoreSimulatorDevice: Identifiable, Codable, Hashable { 32 | public static func == (lhs: CoreSimulatorDevice, rhs: CoreSimulatorDevice) -> Bool { 33 | lhs.uuid == rhs.uuid 34 | } 35 | 36 | public func hash(into hasher: inout Hasher) { 37 | hasher.combine(uuid) 38 | } 39 | 40 | public let root: URL 41 | public let uuid: UUID 42 | public let plist: URL 43 | public let data: URL 44 | 45 | public init(root: URL, uuid: UUID, plist: URL, data: URL) { 46 | self.root = root 47 | self.uuid = uuid 48 | self.plist = plist 49 | self.data = data 50 | 51 | if let values = try? data.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey]), let creationDate = values.creationDate, let contentModified = values.contentModificationDate { 52 | dateAdded = creationDate 53 | lastModified = contentModified 54 | } 55 | 56 | Task { 57 | await decodePlist() 58 | await loadDataContents() 59 | } 60 | } 61 | 62 | /// `.creationDateKey` 63 | public private(set) var dateAdded: Date? 64 | /// `.contentModificationDateKey` 65 | public private(set) var lastModified: Date? 66 | 67 | public var devicePlist: DevicePlist? 68 | 69 | private func decodePlist() async { 70 | guard let plistData = FileManager.default.contents(atPath: plist.path()) else { 71 | return 72 | } 73 | 74 | do { 75 | let value = try PropertyListDecoder().decode(DevicePlist.self, from: plistData) 76 | Task { @MainActor in 77 | devicePlist = value 78 | } 79 | } catch { 80 | print(error) 81 | } 82 | } 83 | 84 | /// Use this key path for APIs that require a non-optional value (e.g. `SwiftUI.TableColumn`). 85 | public var name: String { devicePlist?.name ?? uuid.uuidString } 86 | /// Use this key path for APIs that require a non-optional value (e.g. `SwiftUI.TableColumn`). 87 | public var totalSize: Int { size ?? -1 } 88 | public var creationDate: Date { 89 | dateAdded ?? .distantPast 90 | } 91 | public var contentModificationDate: Date { 92 | lastModified ?? .distantPast 93 | } 94 | public var deviceKind: DeviceIdiom { 95 | devicePlist?.userInterfaceIdiom ?? .unspecified 96 | } 97 | public var lastBootedAt: Date { 98 | devicePlist?.lastBootedAt ?? .distantPast 99 | } 100 | public var isDeleted: Bool { 101 | devicePlist?.isDeleted ?? false 102 | } 103 | 104 | public private(set) var size: Int? 105 | public var isLoadingDataContents = false 106 | public var dataContents: DataDir? 107 | public func loadDataContents(recalculate: Bool = true) { 108 | defer { 109 | Task { @MainActor in 110 | isLoadingDataContents = false 111 | } 112 | } 113 | 114 | if recalculate == false, (dataContents != nil || size != nil) { 115 | return 116 | } 117 | 118 | Task { @MainActor in 119 | isLoadingDataContents = true 120 | } 121 | 122 | Task { 123 | let contents: [URL] 124 | do { 125 | contents = try FileManager.default.contentsOfDirectory( 126 | at: data, 127 | includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey, .creationDateKey, .contentModificationDateKey], 128 | options: [.skipsPackageDescendants, .skipsHiddenFiles] 129 | ) 130 | 131 | let metadata = contents.compactMap { 132 | let values = try? $0.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey]) 133 | let size = URL.directorySize(url: $0) 134 | return Metadata( 135 | url: $0, 136 | size: size, 137 | dateAdded: values?.creationDate, 138 | lastModified: values?.contentModificationDate 139 | ) 140 | } 141 | Task { @MainActor in 142 | dataContents = .init(contents: contents, metadata: metadata) 143 | size = metadata.reduce(0) { $0 + $1.size } 144 | } 145 | } catch { 146 | print(error) 147 | } 148 | } 149 | } 150 | 151 | @ObservationIgnored 152 | public var dirsMetadata: [URL: Int] = [:] 153 | 154 | @ObservationIgnored 155 | public var filesMetadata: [URL: Int] = [:] 156 | } 157 | 158 | public struct Metadata: Codable, Identifiable, Hashable { 159 | public let url: URL 160 | public let size: Int 161 | /// `.creationDateKey` 162 | public let dateAdded: Date? 163 | /// `.contentModificationDateKey` 164 | public let lastModified: Date? 165 | 166 | public var id: String { url.lastPathComponent } 167 | 168 | public var key: String { 169 | url.lastPathComponent 170 | } 171 | 172 | public var lastPathComponent: String { 173 | url.lastPathComponent 174 | } 175 | public var contentModificationDate: Date { 176 | lastModified ?? .distantPast 177 | } 178 | 179 | public func hash(into hasher: inout Hasher) { 180 | hasher.combine(url) 181 | } 182 | } 183 | 184 | public final class DataDir: Codable { 185 | public var contents: [URL] = [] 186 | public var metadata: [Metadata] = [] 187 | 188 | init(contents: [URL], metadata: [Metadata]) { 189 | self.contents = contents 190 | self.metadata = metadata 191 | } 192 | } 193 | 194 | extension URL { 195 | /// This is way faster and uses less memory than using FileManager's enumerator. 196 | static func directorySize(url: URL, dirMetadata: inout [URL: Int], fileMetadata: inout [URL: Int]) -> Int { 197 | let contents: [URL] 198 | do { 199 | contents = try FileManager.default.contentsOfDirectory( 200 | at: url, 201 | includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey], 202 | options: .skipsPackageDescendants /// Not sure if `.skipsPackageDescendants` is wise here. 203 | ) 204 | } catch { 205 | return 0 206 | } 207 | 208 | var size: Int = 0 209 | 210 | autoreleasepool { 211 | for url in contents { 212 | if url.hasDirectoryPath { 213 | let s = directorySize(url: url, dirMetadata: &dirMetadata, fileMetadata: &fileMetadata) 214 | if s != 0 { 215 | dirMetadata[url] = s 216 | } 217 | size += s 218 | } else { 219 | let fileSizeResourceValue: URLResourceValues 220 | do { 221 | fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey]) 222 | } catch { 223 | continue 224 | } 225 | 226 | let s = fileSizeResourceValue.fileSize ?? 0 227 | if s != 0 { 228 | fileMetadata[url] = s 229 | } 230 | size += s 231 | } 232 | } 233 | } 234 | 235 | return size 236 | } 237 | 238 | static func directorySize(url: URL) -> Int { 239 | let contents: [URL] 240 | do { 241 | contents = try FileManager.default.contentsOfDirectory( 242 | at: url, 243 | includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey], 244 | options: .skipsPackageDescendants /// Not sure if `.skipsPackageDescendants` is wise here. 245 | ) 246 | } catch { 247 | return 0 248 | } 249 | 250 | var size: Int = 0 251 | 252 | autoreleasepool { 253 | for url in contents { 254 | if url.hasDirectoryPath { 255 | size += directorySize(url: url) 256 | } else { 257 | let fileSizeResourceValue: URLResourceValues 258 | do { 259 | fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey]) 260 | } catch { 261 | continue 262 | } 263 | 264 | size += fileSizeResourceValue.fileSize ?? 0 265 | } 266 | } 267 | } 268 | 269 | return size 270 | } 271 | 272 | } 273 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorTools/Sources/CoreSimulatorTools/DeviceIdiom.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DeviceIdiom.swift 3 | // 4 | // 5 | // Created by Bosco Ho on 2023-11-17. 6 | // 7 | 8 | import Foundation 9 | 10 | /// Same as `UIUserInterfaceIdiom`. 11 | public enum DeviceIdiom: Int, Sendable, CustomStringConvertible, Comparable { 12 | public static func < (lhs: DeviceIdiom, rhs: DeviceIdiom) -> Bool { 13 | lhs.rawValue < rhs.rawValue 14 | } 15 | 16 | case unspecified 17 | case phone 18 | case pad 19 | case watch 20 | case tv 21 | case carPlay 22 | case mac 23 | case vision 24 | 25 | public var id: Int { rawValue } 26 | 27 | public var description: String { 28 | switch self { 29 | case .unspecified: 30 | "Unspecified" 31 | case .phone: 32 | "Phone" 33 | case .pad: 34 | "Pad" 35 | case .watch: 36 | "Watch" 37 | case .tv: 38 | "TV" 39 | case .carPlay: 40 | "CarPlay" 41 | case .mac: 42 | "Mac" 43 | case .vision: 44 | "Vision" 45 | } 46 | } 47 | 48 | public var systemImage: String { 49 | switch self { 50 | case .unspecified: 51 | "questionmark.app" 52 | case .phone: 53 | "apps.iphone" 54 | case .pad: 55 | "apps.ipad.landscape" 56 | case .watch: 57 | "applewatch" 58 | case .tv: 59 | "tv" 60 | case .carPlay: 61 | "car" 62 | case .mac: 63 | "macbook" 64 | case .vision: 65 | "visionpro" 66 | } 67 | } 68 | } 69 | 70 | extension DeviceIdiom { 71 | static func idiom(for device: DevicePlist) -> Self { 72 | let deviceName = device.name 73 | if deviceName.localizedCaseInsensitiveContains("phone") || deviceName.localizedCaseInsensitiveContains("pod") { 74 | return .phone 75 | } else if deviceName.localizedCaseInsensitiveContains("pad") { 76 | return .pad 77 | } else if deviceName.localizedCaseInsensitiveContains("watch") { 78 | return .watch 79 | } else if deviceName.localizedCaseInsensitiveContains("tv") { 80 | return .tv 81 | } else if deviceName.localizedCaseInsensitiveContains("carplay") { 82 | return .carPlay 83 | } else if deviceName.localizedCaseInsensitiveContains("mac") { 84 | return .mac 85 | } else if deviceName.localizedCaseInsensitiveContains("vision") { 86 | return .vision 87 | } else { 88 | return .unspecified 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorTools/Tests/CoreSimulatorToolsTests/CoreSimulatorToolsTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import CoreSimulatorTools 3 | 4 | final class CoreSimulatorToolsTests: XCTestCase { 5 | func testExample() throws { 6 | // XCTest Documentation 7 | // https://developer.apple.com/documentation/xctest 8 | 9 | // Defining Test Cases and Test Methods 10 | // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorUI/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorUI/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "CoreSimulatorUI", 8 | platforms: [.macOS(.v14)], 9 | products: [ 10 | // Products define the executables and libraries a package produces, making them visible to other packages. 11 | .library( 12 | name: "CoreSimulatorUI", 13 | targets: ["CoreSimulatorUI"]), 14 | ], 15 | dependencies: [ 16 | .package(name: "CoreSimulatorTools", path: "../CoreSimulatorTools"), 17 | .package(name: "DestructiveActions", path: "../DestructiveActions"), 18 | .package(name: "FileSystemUI", path: "../FileSystemUI"), 19 | ], 20 | targets: [ 21 | // Targets are the basic building blocks of a package, defining a module or a test suite. 22 | // Targets can depend on other targets in this package and products from dependencies. 23 | .target( 24 | name: "CoreSimulatorUI", 25 | dependencies: [ 26 | .product( 27 | name: "CoreSimulatorTools", 28 | package: "CoreSimulatorTools" 29 | ), 30 | .product( 31 | name: "DestructiveActions", 32 | package: "DestructiveActions" 33 | ), 34 | .product( 35 | name: "FileSystemUI", 36 | package: "FileSystemUI" 37 | ), 38 | ] 39 | ), 40 | .testTarget( 41 | name: "CoreSimulatorUITests", 42 | dependencies: ["CoreSimulatorUI"]), 43 | ] 44 | ) 45 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorUI/Sources/CoreSimulatorUI/CoreSimDeviceInspectView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CoreSimDeviceInspectView.swift 3 | // 4 | // 5 | // Created by Bosco Ho on 2023-11-19. 6 | // 7 | 8 | import SwiftUI 9 | import CoreSimulatorTools 10 | import FileSystemUI 11 | 12 | @Observable 13 | public final class CoreSimDeviceInspectViewModel { 14 | public var device: CoreSimulatorDevice? 15 | 16 | public init(device: CoreSimulatorDevice? = nil) { 17 | self.device = device 18 | } 19 | } 20 | 21 | public struct CoreSimDeviceInspectView: View { 22 | 23 | @Binding var device: CoreSimulatorDevice? 24 | 25 | @State private var viewModel: CoreSimDeviceInspectViewModel 26 | @State private var selection: Metadata? 27 | 28 | public init(device: Binding) { 29 | _device = device 30 | _viewModel = .init(wrappedValue: .init(device: _device.wrappedValue)) 31 | } 32 | 33 | public var body: some View { 34 | NavigationSplitView { 35 | if let dataContents = device?.dataContents { 36 | List( 37 | dataContents.metadata, 38 | id: \.self, 39 | selection: $selection 40 | ) { value in 41 | HStack { 42 | VStack { 43 | Image(systemName: "folder") 44 | } 45 | VStack(alignment: .leading) { 46 | Text("\(value.key)") 47 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(value.size), countStyle: .file))") 48 | } 49 | } 50 | } 51 | .onChange(of: selection) { oldValue, newValue in 52 | print("selection changed: \(oldValue?.key ?? "_") -> \(newValue?.key ?? "_")") 53 | } 54 | } else { 55 | ProgressView() 56 | } 57 | } detail: { 58 | NavigationStack { 59 | if let selection { 60 | AnyDirectoryView(dirUrl: selection.url) 61 | .id(selection.url.absoluteString) 62 | } else { 63 | GroupBox { 64 | Text("Select a directory") 65 | } 66 | } 67 | } 68 | } 69 | .navigationTitle("\(device?.name ?? "")") 70 | } 71 | 72 | @ViewBuilder 73 | private func makeView() -> some View { 74 | HSplitView { 75 | if let dataContents = device?.dataContents { 76 | GeometryReader { geometry in 77 | List( 78 | dataContents.metadata, 79 | id: \.key, 80 | selection: $selection 81 | ) { value in 82 | // Text("\(value.key)") 83 | HStack { 84 | // RoundedRectangle(cornerRadius: 12, style: .continuous) 85 | // .aspectRatio(1, contentMode: .fit) 86 | // .frame(width: 120) 87 | // .foregroundStyle(.teal) 88 | 89 | VStack(alignment: .leading) { 90 | Text("\(value.key)") 91 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(value.size), countStyle: .file))") 92 | } 93 | } 94 | .background(.teal) 95 | } 96 | .frame(width: geometry.size.width) 97 | } 98 | } else { 99 | ProgressView() 100 | } 101 | 102 | // List { 103 | // Section("Directory Name") { 104 | // Text("Selected Directory: \(selection?.key ?? "n/a")") 105 | // } 106 | // } 107 | // .frame(minWidth: 360) 108 | } 109 | } 110 | } 111 | 112 | #Preview { 113 | CoreSimDeviceInspectView(device: .constant(nil)) 114 | } 115 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorUI/Sources/CoreSimulatorUI/CoreSimDeviceView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CoreSimDeviceView.swift 3 | // 4 | // 5 | // Created by Bosco Ho on 2023-11-15. 6 | // 7 | 8 | import SwiftUI 9 | import CoreSimulatorTools 10 | import DestructiveActions 11 | 12 | public struct CoreSimDeviceView: View { 13 | 14 | @AppStorage("preferences.general.deletionBehaviour") var deletionBehaviour: DeletionBehaviour = .moveToTrash 15 | 16 | @Environment(\.openWindow) var openWindow 17 | 18 | @Binding var device: CoreSimulatorDevice? 19 | 20 | @State private var tableSelection: Set = .init() 21 | @State private var tableSortOrder = [KeyPathComparator(\Metadata.size)] 22 | 23 | @State private var isPresentingDeleteDeviceAlert = false 24 | 25 | @State private var isPresentingDeleteErrorAlert = false 26 | @State private var deleteError: DestructiveActionError? 27 | 28 | @State private var isPresentingDeviceInspector = false 29 | 30 | private let dateTimeFormatter = RelativeDateTimeFormatter() 31 | 32 | public init(device: Binding) { 33 | _device = device 34 | } 35 | 36 | public var body: some View { 37 | Group { 38 | if let device, let devicePlist = device.devicePlist { 39 | listView(device: device, devicePlist: devicePlist) 40 | } else { 41 | ProgressView() 42 | } 43 | } 44 | .onAppear { 45 | device?.loadDataContents(recalculate: false) 46 | } 47 | } 48 | 49 | @ViewBuilder 50 | private func listView(device: CoreSimulatorDevice, devicePlist: DevicePlist) -> some View { 51 | let mirror = Mirror(reflecting: devicePlist) 52 | let children = Array(mirror.children) 53 | List { 54 | Section { 55 | GroupBox { 56 | HStack { 57 | Text("\(devicePlist.name)") 58 | .font(.title2) 59 | Spacer() 60 | Button("Delete Device...") { 61 | isPresentingDeleteDeviceAlert = true 62 | } 63 | .buttonStyle(.borderedProminent) 64 | .tint(.red) 65 | } 66 | } 67 | } 68 | 69 | Section("Metadata") { 70 | ForEach(children, id: \.label) { child in 71 | if let l = child.label { 72 | let label = "\(l)" 73 | let value = "\(child.value)" 74 | LabeledContent(label, value: value) 75 | } 76 | } 77 | } 78 | 79 | Section("Access") { 80 | if let dateAdded = device.dateAdded { 81 | LabeledContent( 82 | "Date Added", 83 | value: dateTimeFormatter.localizedString( 84 | for: dateAdded, 85 | relativeTo: Date() 86 | ) 87 | ) 88 | } 89 | if let lastModified = device.lastModified { 90 | LabeledContent("Last Modified", value: dateTimeFormatter.localizedString( 91 | for: lastModified, 92 | relativeTo: Date() 93 | )) 94 | } 95 | } 96 | 97 | Section { 98 | if device.isLoadingDataContents { 99 | ProgressView() 100 | } else { 101 | GroupBox { 102 | if let contents = device.dataContents { 103 | dataContentsTableView(contents: contents) 104 | } else { 105 | ContentUnavailableView { 106 | Text("Failed to load device contents.") 107 | } 108 | } 109 | } 110 | } 111 | } header: { 112 | HStack { 113 | Text("Data") 114 | Spacer() 115 | Button("Inspect Device...") { 116 | openWindow(id: "CoreSimInspectDevice", value: device) 117 | } 118 | .buttonStyle(.borderedProminent) 119 | } 120 | } 121 | } 122 | .toolbar { 123 | ToolbarItem(placement: .automatic) { 124 | Button { 125 | NSWorkspace.shared.activateFileViewerSelecting([device.root]) 126 | } label: { 127 | Text("Show in Finder") 128 | } 129 | } 130 | } 131 | .alert(isPresented: $isPresentingDeleteErrorAlert, error: deleteError) { _ in 132 | Button("Dismiss", role: .cancel) { 133 | 134 | } 135 | } message: { _ in 136 | Text("Dismiss") 137 | } 138 | .alert("Are you sure you wish to permanently delete\n\"\(devicePlist.name)\"?", isPresented: $isPresentingDeleteDeviceAlert) { 139 | Button("Cancel", role: .cancel) { 140 | 141 | } 142 | Button("Delete", role: .destructive) { 143 | do { 144 | try FileManager.default.delete(coreSimDevice: device, moveToTrash: deletionBehaviour == .moveToTrash) 145 | self.device = nil 146 | } catch { 147 | if let error = error as? DestructiveActionError { 148 | isPresentingDeleteErrorAlert = true 149 | deleteError = error 150 | } 151 | } 152 | } 153 | } message: { 154 | Text("This operation cannot be reversed.\n\nYou may wish to backup test data associated with this device before proceeding.") 155 | } 156 | } 157 | 158 | @ViewBuilder 159 | private func dataContentsTableView(contents: DataDir) -> some View { 160 | Table( 161 | contents.metadata, 162 | selection: $tableSelection, 163 | sortOrder: $tableSortOrder 164 | ) { 165 | TableColumn("Directory", value: \.lastPathComponent) { value in 166 | Text("\(value.url.lastPathComponent)") 167 | } 168 | 169 | TableColumn("Last Modified", value: \.contentModificationDate) { value in 170 | if let date = value.lastModified { 171 | Text("\(dateTimeFormatter.localizedString(for: date, relativeTo: Date()))") 172 | } else { 173 | Text("Never") 174 | } 175 | } 176 | 177 | TableColumn("Size", value: \.size) { value in 178 | HStack { 179 | Spacer() 180 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(value.size), countStyle: .file))") 181 | .fontWeight(.medium) 182 | } 183 | } 184 | } 185 | .frame(height: 280) 186 | .onChange(of: tableSortOrder) { _, sortOrder in 187 | contents.metadata.sort(using: sortOrder) 188 | } 189 | 190 | GroupBox { 191 | let total = contents.metadata.reduce(0) { $0 + $1.size } 192 | LabeledContent("Total Data Used", value: ByteCountFormatter.string(fromByteCount: Int64(total), countStyle: .file)) 193 | .fontWeight(.heavy) 194 | .font(.title3) 195 | .padding(.horizontal, 4) 196 | } 197 | } 198 | } 199 | 200 | #Preview { 201 | CoreSimDeviceView(device: .constant(nil)) 202 | } 203 | -------------------------------------------------------------------------------- /Packages/CoreSimulatorUI/Tests/CoreSimulatorUITests/CoreSimulatorUITests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import CoreSimulatorUI 3 | 4 | final class CoreSimulatorUITests: XCTestCase { 5 | func testExample() throws { 6 | // XCTest Documentation 7 | // https://developer.apple.com/documentation/xctest 8 | 9 | // Defining Test Cases and Test Methods 10 | // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Packages/DestructiveActions/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /Packages/DestructiveActions/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "DestructiveActions", 8 | platforms: [.macOS(.v14)], 9 | products: [ 10 | // Products define the executables and libraries a package produces, making them visible to other packages. 11 | .library( 12 | name: "DestructiveActions", 13 | targets: ["DestructiveActions"]), 14 | ], 15 | dependencies: [ 16 | .package(name: "CoreSimulatorTools", path: "../CoreSimulatorTools"), 17 | ], 18 | targets: [ 19 | // Targets are the basic building blocks of a package, defining a module or a test suite. 20 | // Targets can depend on other targets in this package and products from dependencies. 21 | .target( 22 | name: "DestructiveActions", 23 | dependencies: [ 24 | .product( 25 | name: "CoreSimulatorTools", 26 | package: "CoreSimulatorTools" 27 | ), 28 | ] 29 | ), 30 | .testTarget( 31 | name: "DestructiveActionsTests", 32 | dependencies: ["DestructiveActions"]), 33 | ] 34 | ) 35 | -------------------------------------------------------------------------------- /Packages/DestructiveActions/README.md: -------------------------------------------------------------------------------- 1 | # DestructiveActions 2 | 3 | This package contains logic that performs deletion (or similar) actions, especially irreversible ones. 4 | -------------------------------------------------------------------------------- /Packages/DestructiveActions/Sources/DestructiveActions/DeletionBehaviour.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DeletionBehaviour.swift 3 | // 4 | // 5 | // Created by Bosco Ho on 2023-11-21. 6 | // 7 | 8 | import Foundation 9 | import SwiftUI 10 | 11 | public enum DeletionBehaviour: Int, CaseIterable, CustomStringConvertible, Identifiable { 12 | case moveToTrash 13 | case permanent 14 | 15 | public var description: String { 16 | switch self { 17 | case .moveToTrash: 18 | "Move to Trash" 19 | case .permanent: 20 | "Permanently Delete" 21 | } 22 | } 23 | 24 | public var behaviourDescription: String { 25 | switch self { 26 | case .moveToTrash: 27 | "Deleted items are moved to Trash, where you may recover items, if needed." 28 | case .permanent: 29 | "Warning: Recovery is not possible with this option. Deleted items are permanently removed from file system." 30 | } 31 | } 32 | 33 | public var systemImage: String { 34 | switch self { 35 | case .moveToTrash: 36 | "trash" 37 | case .permanent: 38 | "exclamationmark.circle" 39 | } 40 | } 41 | 42 | public var accentColor: Color { 43 | switch self { 44 | case .moveToTrash: 45 | Color.orange 46 | case .permanent: 47 | Color.red 48 | } 49 | } 50 | 51 | public var id: Int { rawValue } 52 | } 53 | -------------------------------------------------------------------------------- /Packages/DestructiveActions/Sources/DestructiveActions/DestructiveActions.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import CoreSimulatorTools 3 | import os 4 | 5 | struct Log { 6 | static let logger: Logger = .init() 7 | } 8 | 9 | public enum DestructiveActionError: LocalizedError { 10 | case deleteCoreSimDevice(Error) 11 | 12 | public var errorDescription: String? { 13 | switch self { 14 | case .deleteCoreSimDevice(let error): 15 | error.localizedDescription 16 | } 17 | } 18 | } 19 | 20 | public extension FileManager { 21 | 22 | /// - Parameter moveToTrash: If `true` moves device to system Trash bin, otherwise permanently removes device with no recovery options. 23 | func delete(coreSimDevice: CoreSimulatorDevice, moveToTrash: Bool = true) throws { 24 | Log.logger.info("⌫ deleting core sim device: [\(coreSimDevice.name)](\(coreSimDevice.root)), uuid: \(coreSimDevice.uuid.uuidString)") 25 | let rootDirUrl = coreSimDevice.root 26 | do { 27 | if moveToTrash { 28 | try self.trashItem(at: rootDirUrl, resultingItemURL: nil) 29 | } else { 30 | try self.removeItem(at: rootDirUrl) 31 | } 32 | coreSimDevice.devicePlist?.isDeleted = true 33 | } catch { 34 | throw DestructiveActionError.deleteCoreSimDevice(error) 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Packages/DestructiveActions/Tests/DestructiveActionsTests/DestructiveActionsTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import DestructiveActions 3 | 4 | final class DestructiveActionsTests: XCTestCase { 5 | func testExample() throws { 6 | // XCTest Documentation 7 | // https://developer.apple.com/documentation/xctest 8 | 9 | // Defining Test Cases and Test Methods 10 | // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Packages/FileSystem/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /Packages/FileSystem/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "FileSystem", 8 | platforms: [.macOS(.v14)], 9 | products: [ 10 | // Products define the executables and libraries a package produces, making them visible to other packages. 11 | .library( 12 | name: "FileSystem", 13 | targets: ["FileSystem"]), 14 | ], 15 | targets: [ 16 | // Targets are the basic building blocks of a package, defining a module or a test suite. 17 | // Targets can depend on other targets in this package and products from dependencies. 18 | .target( 19 | name: "FileSystem"), 20 | .testTarget( 21 | name: "FileSystemTests", 22 | dependencies: ["FileSystem"]), 23 | ] 24 | ) 25 | -------------------------------------------------------------------------------- /Packages/FileSystem/Sources/FileSystem/FileSystem.swift: -------------------------------------------------------------------------------- 1 | // The Swift Programming Language 2 | // https://docs.swift.org/swift-book 3 | 4 | import Foundation 5 | 6 | public extension URL { 7 | /// check if the URL is a directory and if it is reachable 8 | func isDirectoryAndReachable() throws -> Bool { 9 | guard try resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true else { 10 | return false 11 | } 12 | return try checkResourceIsReachable() 13 | } 14 | 15 | /// returns total allocated size of a the directory including its subFolders or not 16 | func directoryTotalAllocatedSize(includingSubfolders: Bool = false) throws -> Int? { 17 | guard try isDirectoryAndReachable() else { return nil } 18 | if includingSubfolders { 19 | guard 20 | let urls = FileManager.default.enumerator(at: self, includingPropertiesForKeys: nil)?.allObjects as? [URL] else { return nil } 21 | return try urls.lazy.reduce(0) { 22 | (try $1.resourceValues(forKeys: [.totalFileAllocatedSizeKey]).totalFileAllocatedSize ?? 0) + $0 23 | } 24 | } 25 | return try FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil).lazy.reduce(0) { 26 | (try $1.resourceValues(forKeys: [.totalFileAllocatedSizeKey]) 27 | .totalFileAllocatedSize ?? 0) + $0 28 | } 29 | } 30 | 31 | /// returns the directory total size on disk 32 | func sizeOnDisk() throws -> String? { 33 | guard let size = try directoryTotalAllocatedSize(includingSubfolders: true) else { return nil } 34 | URL.byteCountFormatter.countStyle = .file 35 | guard let byteCount = URL.byteCountFormatter.string(for: size) else { return nil} 36 | return byteCount + " on disk" 37 | } 38 | private static let byteCountFormatter = ByteCountFormatter() 39 | 40 | func volumeTotalCapacity() -> Int? { 41 | let value = try? self.resourceValues(forKeys: [.volumeTotalCapacityKey]) 42 | return value?.volumeTotalCapacity 43 | } 44 | } 45 | 46 | public extension URL { 47 | 48 | /// Counts the number of files at this path, including files in all sub-directories. 49 | static func directoryContentsCount(url: URL) -> Int { 50 | let contents: [URL] 51 | do { 52 | contents = try FileManager.default.contentsOfDirectory( 53 | at: url, 54 | includingPropertiesForKeys: [.isRegularFileKey, .isDirectoryKey], 55 | options: .skipsPackageDescendants /// Not sure if `.skipsPackageDescendants` is wise here. 56 | ) 57 | } catch { 58 | return 0 59 | } 60 | 61 | var count = 0 62 | 63 | autoreleasepool { 64 | for url in contents { 65 | count += url.hasDirectoryPath ? directoryContentsCount(url: url) : 1 66 | } 67 | } 68 | 69 | return count 70 | } 71 | 72 | /// This is way faster and uses less memory than using FileManager's enumerator. 73 | static func directorySize(url: URL, dirMetadata: inout [URL: Int], fileMetadata: inout [URL: Int]) -> Int { 74 | let contents: [URL] 75 | do { 76 | contents = try FileManager.default.contentsOfDirectory( 77 | at: url, 78 | includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey], 79 | options: .skipsPackageDescendants /// Not sure if `.skipsPackageDescendants` is wise here. 80 | ) 81 | } catch { 82 | return 0 83 | } 84 | 85 | var size: Int = 0 86 | 87 | autoreleasepool { 88 | for url in contents { 89 | if url.hasDirectoryPath { 90 | let s = directorySize(url: url, dirMetadata: &dirMetadata, fileMetadata: &fileMetadata) 91 | if s != 0 { 92 | dirMetadata[url] = s 93 | } 94 | size += s 95 | } else { 96 | let fileSizeResourceValue: URLResourceValues 97 | do { 98 | fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey]) 99 | } catch { 100 | continue 101 | } 102 | 103 | let s = fileSizeResourceValue.fileSize ?? 0 104 | if s != 0 { 105 | fileMetadata[url] = s 106 | } 107 | size += s 108 | } 109 | } 110 | } 111 | 112 | return size 113 | } 114 | 115 | static func directorySize(url: URL) -> Int { 116 | let contents: [URL] 117 | do { 118 | contents = try FileManager.default.contentsOfDirectory( 119 | at: url, 120 | includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey], 121 | options: .skipsPackageDescendants /// Not sure if `.skipsPackageDescendants` is wise here. 122 | ) 123 | } catch { 124 | return 0 125 | } 126 | 127 | var size: Int = 0 128 | 129 | autoreleasepool { 130 | for url in contents { 131 | if url.hasDirectoryPath { 132 | size += directorySize(url: url) 133 | } else { 134 | let fileSizeResourceValue: URLResourceValues 135 | do { 136 | fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey]) 137 | } catch { 138 | continue 139 | } 140 | 141 | size += fileSizeResourceValue.fileSize ?? 0 142 | } 143 | } 144 | } 145 | 146 | return size 147 | } 148 | 149 | static func directorySize(url: URL) async -> Int { 150 | await withCheckedContinuation { continuation in 151 | Task(priority: .userInitiated) { 152 | let dirSize = directorySize(url: url) 153 | continuation.resume(returning: dirSize) 154 | } 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /Packages/FileSystem/Tests/FileSystemTests/FileSystemTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import FileSystem 3 | 4 | final class FileSystemTests: XCTestCase { 5 | func testExample() throws { 6 | // XCTest Documentation 7 | // https://developer.apple.com/documentation/xctest 8 | 9 | // Defining Test Cases and Test Methods 10 | // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Packages/FileSystemUI/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /Packages/FileSystemUI/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "FileSystemUI", 8 | platforms: [.macOS(.v14)], 9 | products: [ 10 | // Products define the executables and libraries a package produces, making them visible to other packages. 11 | .library( 12 | name: "FileSystemUI", 13 | targets: ["FileSystemUI"]), 14 | ], 15 | dependencies: [ 16 | .package(name: "FileSystem", path: "../FileSystem"), 17 | ], 18 | targets: [ 19 | // Targets are the basic building blocks of a package, defining a module or a test suite. 20 | // Targets can depend on other targets in this package and products from dependencies. 21 | .target( 22 | name: "FileSystemUI", 23 | dependencies: [ 24 | .product( 25 | name: "FileSystem", 26 | package: "FileSystem" 27 | ), 28 | ] 29 | ), 30 | .testTarget( 31 | name: "FileSystemUITests", 32 | dependencies: ["FileSystemUI"]), 33 | ] 34 | ) 35 | -------------------------------------------------------------------------------- /Packages/FileSystemUI/Sources/FileSystemUI/AnyDirectory.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AnyDirectory.swift 3 | // Chinotto 4 | // 5 | // Created by Bosco Ho on 2023-11-20. 6 | // 7 | 8 | import SwiftUI 9 | import FileSystem 10 | 11 | public struct AnyDirectory { 12 | let root: URL 13 | let contents: [URL] 14 | let contentSizes: [URL: Int] 15 | } 16 | 17 | @Observable 18 | public final class AnyDirectoryViewModel { 19 | public let url: URL 20 | public init(url: URL) { 21 | self.url = url 22 | } 23 | 24 | public var isLoading = false 25 | public var directory: AnyDirectory? 26 | 27 | public func loadContents() throws { 28 | defer { 29 | Task { @MainActor in 30 | isLoading = false 31 | } 32 | } 33 | let contents = try FileManager.default.contentsOfDirectory( 34 | at: url, 35 | includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey, .creationDateKey, .contentModificationDateKey], 36 | options: [.skipsPackageDescendants, .skipsHiddenFiles] 37 | ) 38 | 39 | let sizes = contents.compactMap { 40 | if $0.hasDirectoryPath { 41 | return ($0, URL.directorySize(url: $0)) 42 | } else { 43 | if let values = try? $0.resourceValues(forKeys: [.fileSizeKey]) { 44 | let size = values.fileSize ?? 0 45 | return ($0, size) 46 | } else { 47 | return ($0, 0) 48 | } 49 | } 50 | } 51 | let grouped = Dictionary(grouping: sizes, by: { $0.0 }) 52 | .compactMapValues { e in e.reduce(0) { $0 + $1.1 } } 53 | 54 | Task { @MainActor in 55 | self.directory = .init(root: url, contents: contents, contentSizes: grouped) 56 | self.isLoading = false 57 | } 58 | } 59 | } 60 | 61 | public struct AnyDirectoryView: View { 62 | 63 | public init(dirUrl: URL) { 64 | _viewModel = .init(wrappedValue: .init(url: dirUrl)) 65 | } 66 | 67 | @State private var viewModel: AnyDirectoryViewModel 68 | 69 | public var body: some View { 70 | List { 71 | if let directory = viewModel.directory { 72 | if directory.contents.isEmpty { 73 | GroupBox { 74 | Text("Empty Directory") 75 | } 76 | } else { 77 | ForEach(directory.contents, id: \.self) { value in 78 | if value.hasDirectoryPath { 79 | NavigationLink { 80 | AnyDirectoryView(dirUrl: value) 81 | } label: { 82 | HStack { 83 | Text("\(value.lastPathComponent)") 84 | if let size = directory.contentSizes[value] { 85 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file))") 86 | } 87 | } 88 | } 89 | } else { 90 | HStack { 91 | Text("\(value.lastPathComponent)") 92 | if let size = directory.contentSizes[value] { 93 | Text("\(ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file))") 94 | } 95 | } 96 | } 97 | } 98 | } 99 | } else { 100 | ProgressView() 101 | } 102 | } 103 | .task { 104 | try? viewModel.loadContents() 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /Packages/FileSystemUI/Tests/FileSystemUITests/FileSystemUITests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import FileSystemUI 3 | 4 | final class FileSystemUITests: XCTestCase { 5 | func testExample() throws { 6 | // XCTest Documentation 7 | // https://developer.apple.com/documentation/xctest 8 | 9 | // Defining Test Cases and Test Methods 10 | // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **Warning** 2 | - *Chinotto is currently in active development (alpha build, not feature-complete).* 3 | - *Chinotto currently does not run in an App Sandbox.* 4 | - *Built for Xcode 15, may not work as expected for older Xcode versions* 5 | - *Use at your own risk =)* 6 | 7 | **Notes** 8 | - *Most of the functionality is currently in `CoreSimulator/Devices`, where you can inspect individual devices.* 9 | 10 | # Chinotto 11 | A sweet little tool for managing the bitter taste of Xcode using up your Mac's storage space. 12 | 13 | Screenshot 2023-11-13 at 5 13 08 PM 14 | 15 | ## Instructions 16 | 1. Checkout latest commit on `/main` branch. 17 | 2. Go to the project's `Chinotto.xcconfig` (DEBUG configuration) file, and replace placeholder values with your own Team ID and bundle id prefix for code-signing. 18 | 3. Build and run via Xcode 15 on macOS 14.0 (or higher). 19 | 4. Click the "Calculate" button on "All Directories" or on an individual directory. 20 | 5. That's it! 21 | 6. You can use Spotlight and search for "Chinotto" for subsequent launches, if you wish to bypass Xcode. 22 | 23 | ## Screenshots 24 | ### Main Window 25 | 26 | Screenshot 2023-11-28 at 6 53 43 PM 27 | 28 | ### Menu Bar extra app 29 | 30 | Screenshot 2023-11-28 at 6 53 46 PM 31 | 32 | ### Settings/Preferences 33 | 34 | Screenshot 2023-11-28 at 6 53 51 PM 35 | 36 | ## Contribute! 37 | Feel free to suggest new features, file bug reports, or provide feedback in the issues tracker 😀 38 | - Remember: Go to the project's `Chinotto.xcconfig` (DEBUG configuration) file, and replace placeholder values with your own Team ID and bundle id prefix for code-signing. 39 | 40 | ## Why? 41 | One of the pain points of using macOS is seeing half of your Mac's storage consumed by some unknown force called "System Data". Apple does provide some tools in System Settings to help manage this issue, but it could be much better, especially for Xcode users. 42 | 43 | Screenshot 2023-11-13 at 4 57 07 PM 44 | 45 | This is where Chinotto can help. 46 | 47 | ## See it in action 48 | 49 | System Settings (System Preferences) does not accurately report Xcode's actual disk space usage. For example, on my MacBook Air M1 (256 GB/8 GB) running Sonoma, Storage reports `Developer` uses 23.7 GB of disk space, but if we run Chinotto, we find that the actual usage is at 97.45 GB, which is more than 4x the system's reported value. 50 | 51 | System Settings: 52 | 53 | Screenshot 2023-11-13 at 4 49 50 PM 54 | 55 | Chinotto: 56 | 57 | Screenshot 2023-11-13 at 4 51 25 PM 58 | 59 | Finder: 60 | - Finder reports the same values as Chinotto. 61 | Screenshot 2023-11-13 at 5 24 03 PM 62 | 63 | ## I made this because 64 | So who cares, as long as you still have storage left at the end of the day? Well, if you are using a base model Apple Silicon Mac with 256 GB storage and 8 GB RAM, your applications will most likely be heavily relying on memory swap. This is quite fine, until your Mac only has about 10-20% of its full storage capacity left, then for whatever reason, Apple Silicon starts to drain your Mac's battery faster than an Intel Mac. This is not great, and to be honest, unacceptable, given Apple's claims that base model Macs are "efficient" [see claim here] (https://www.macrumors.com/2023/11/08/8gb-ram-m3-macbook-pro-like-16-gb-pc/). 65 | 66 | ## Prior Art 67 | Here’s some prior art (non-exhaustive list), check them out if Chinotto doesn’t meet your needs! 🥹 68 | - Xcode Trash Remover https://github.com/FrankKair/xcode-trash-remover 69 | - Xcode Dev Cleaner https://github.com/vashpan/xcode-dev-cleaner 70 | - Cleaner for Xcode https://github.com/waylybaye/XcodeCleaner-SwiftUI 71 | --------------------------------------------------------------------------------