Skip to content

An open-source cross-platform alternative to AirDrop

feat(macos): add share extension (#1739)

Shlomob266ffe2f0cb
diff --git a/app/lib/config/init.dart b/app/lib/config/init.dart
index de3a5af4..6348f3a1 100644
--- a/app/lib/config/init.dart
+++ b/app/lib/config/init.dart
@@ -183,7 +183,7 @@ Future<void> postInit(BuildContext context, Ref ref, bool appStart) async {
if (appStart) {
if (defaultTargetPlatform == TargetPlatform.macOS) {
- final files = await getOpenedFiles();
+ final files = await getPendingFiles();
if (files.isNotEmpty) {
await ref.global.dispatchAsync(_HandleAppStartArgumentsAction(
args: files,
@@ -191,7 +191,7 @@ Future<void> postInit(BuildContext context, Ref ref, bool appStart) async {
}
// handle future dropped files
- getOpenedFilesStream().listen((files) {
+ getPendingFilesStream().listen((files) {
ref.global.dispatchAsync(_HandleAppStartArgumentsAction(
args: files,
));
diff --git a/app/lib/pages/debug/debug_page.dart b/app/lib/pages/debug/debug_page.dart
index 65babf64..84cff7db 100644
--- a/app/lib/pages/debug/debug_page.dart
+++ b/app/lib/pages/debug/debug_page.dart
@@ -58,7 +58,7 @@ class DebugPage extends StatelessWidget {
if (defaultTargetPlatform == TargetPlatform.macOS)
FutureBuilder(
// ignore: discarded_futures
- future: getOpenedFiles().onError((error, stackTrace) async {
+ future: getPendingFiles().onError((error, stackTrace) async {
return <String>[error.toString()];
}),
builder: (context, snapshot) {
diff --git a/app/lib/util/native/macos_channel.dart b/app/lib/util/native/macos_channel.dart
index 72bd3f81..fa30aab5 100644
--- a/app/lib/util/native/macos_channel.dart
+++ b/app/lib/util/native/macos_channel.dart
@@ -19,14 +19,16 @@ Future<void> setupStatusBar() async {
/// Returns a list of files the app was opened with.
/// This happens:
-/// - on macOS when files are dropped onto the app icon
+/// - on macOS when files are dropped onto the app Dock icon
+/// - on macOS when files are dropped onto the app menu bar icon
/// - on macOS when files are opened with the app via Finder
-Future<List<String>> getOpenedFiles() async {
+/// - on macOS when files are shared to the app using the share extension (i.e. the system share menu)
+Future<List<String>> getPendingFiles() async {
if (defaultTargetPlatform != TargetPlatform.macOS) {
return <String>[];
}
- final files = await _methodChannel.invokeMethod<List>('getFiles');
+ final files = await _methodChannel.invokeMethod<List>('getPendingFiles');
if (files == null) {
throw PlatformException(
code: 'UNKNOWN',
@@ -37,14 +39,14 @@ Future<List<String>> getOpenedFiles() async {
return files.cast<String>();
}
-Stream<List<String>> getOpenedFilesStream() {
+Stream<List<String>> getPendingFilesStream() {
if (defaultTargetPlatform != TargetPlatform.macOS) {
return Stream.value(<String>[]).asBroadcastStream();
}
final controller = StreamController<List<String>>();
_methodChannel.setMethodCallHandler((call) async {
- if (call.method == 'onFiles') {
+ if (call.method == 'onPendingFiles') {
controller.add((call.arguments as List).cast<String>());
}
});
diff --git a/app/macos/Podfile b/app/macos/Podfile
index 97c7d963..b061b616 100644
--- a/app/macos/Podfile
+++ b/app/macos/Podfile
@@ -31,6 +31,8 @@ target 'Runner' do
use_modular_headers!
flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__))
+
+ pod 'Defaults', '~> 4.2'
end
post_install do |installer|
diff --git a/app/macos/Podfile.lock b/app/macos/Podfile.lock
index 13230c47..0c62b72e 100644
--- a/app/macos/Podfile.lock
+++ b/app/macos/Podfile.lock
@@ -2,6 +2,7 @@ PODS:
- connectivity_plus (0.0.1):
- FlutterMacOS
- ReachabilitySwift
+ - Defaults (4.2.2)
- desktop_drop (0.0.1):
- FlutterMacOS
- device_info_plus (0.0.1):
@@ -51,6 +52,7 @@ PODS:
DEPENDENCIES:
- connectivity_plus (from `Flutter/ephemeral/.symlinks/plugins/connectivity_plus/macos`)
+ - Defaults (~> 4.2)
- desktop_drop (from `Flutter/ephemeral/.symlinks/plugins/desktop_drop/macos`)
- device_info_plus (from `Flutter/ephemeral/.symlinks/plugins/device_info_plus/macos`)
- dynamic_color (from `Flutter/ephemeral/.symlinks/plugins/dynamic_color/macos`)
@@ -74,6 +76,7 @@ DEPENDENCIES:
SPEC REPOS:
trunk:
+ - Defaults
- ReachabilitySwift
EXTERNAL SOURCES:
@@ -122,6 +125,7 @@ EXTERNAL SOURCES:
SPEC CHECKSUMS:
connectivity_plus: 18d3c32514c886e046de60e9c13895109866c747
+ Defaults: d785e56c0fb8890dc40351603f05c8e1df1bdd45
desktop_drop: 69eeff437544aa619c8db7f4481b3a65f7696898
device_info_plus: 5401765fde0b8d062a2f8eb65510fb17e77cf07f
dynamic_color: 2eaa27267de1ca20d879fbd6e01259773fb1670f
@@ -144,6 +148,6 @@ SPEC CHECKSUMS:
wakelock_plus: 4783562c9a43d209c458cb9b30692134af456269
window_manager: 3a1844359a6295ab1e47659b1a777e36773cd6e8
-PODFILE CHECKSUM: 52ce3598ba3a9d91a6b91c248849f83bab8bc598
+PODFILE CHECKSUM: 5c6550f5101fcba381ddb97e2135e4cacca4f31f
COCOAPODS: 1.15.2
diff --git a/app/macos/Runner.xcodeproj/project.pbxproj b/app/macos/Runner.xcodeproj/project.pbxproj
index 6b93de83..d0762229 100644
--- a/app/macos/Runner.xcodeproj/project.pbxproj
+++ b/app/macos/Runner.xcodeproj/project.pbxproj
@@ -21,6 +21,14 @@
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
+ 053DADDD2C8945EF00C3B4DE /* icon.icns in Resources */ = {isa = PBXBuildFile; fileRef = 053DADDC2C8945EF00C3B4DE /* icon.icns */; };
+ 053DADE72C8945EF00C3B4DE /* ShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 053DADDA2C8945EF00C3B4DE /* ShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
+ 053DADF32C8947A500C3B4DE /* Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 053DADF12C8947A500C3B4DE /* Utilities.swift */; };
+ 053DADF62C89486500C3B4DE /* ShareController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 053DADF42C89486500C3B4DE /* ShareController.swift */; };
+ 053DADFD2C89F83400C3B4DE /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 053DADFA2C89F25E00C3B4DE /* Shared.swift */; };
+ 053DADFE2C89F83500C3B4DE /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 053DADFA2C89F25E00C3B4DE /* Shared.swift */; };
+ 0543E87B2C8A93A9004AA8B7 /* FileDropView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0543E87A2C8A93A9004AA8B7 /* FileDropView.swift */; };
+ 05BAA8D02C8CE248003CFCF1 /* SecurityScopedResourceManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05BAA8CF2C8CE248003CFCF1 /* SecurityScopedResourceManager.swift */; };
0F663CE30FCD07225E44A808 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2F8CCFF0FAB783405F067709 /* Pods_Runner.framework */; };
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
@@ -30,6 +38,13 @@
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
+ 053DADE52C8945EF00C3B4DE /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = 053DADD92C8945EF00C3B4DE;
+ remoteInfo = ShareExtension;
+ };
33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
@@ -40,6 +55,17 @@
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
+ 053DADE82C8945EF00C3B4DE /* Embed Foundation Extensions */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 2147483647;
+ dstPath = "";
+ dstSubfolderSpec = 13;
+ files = (
+ 053DADE72C8945EF00C3B4DE /* ShareExtension.appex in Embed Foundation Extensions */,
+ );
+ name = "Embed Foundation Extensions";
+ runOnlyForDeploymentPostprocessing = 0;
+ };
33CC110E2044A8840003C045 /* Bundle Framework */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
@@ -53,6 +79,15 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
+ 053DADDA2C8945EF00C3B4DE /* ShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = ShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
+ 053DADDC2C8945EF00C3B4DE /* icon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = icon.icns; sourceTree = "<group>"; };
+ 053DADE32C8945EF00C3B4DE /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+ 053DADE42C8945EF00C3B4DE /* ShareExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = ShareExtension.entitlements; sourceTree = "<group>"; };
+ 053DADF12C8947A500C3B4DE /* Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Utilities.swift; sourceTree = "<group>"; };
+ 053DADF42C89486500C3B4DE /* ShareController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareController.swift; sourceTree = "<group>"; };
+ 053DADFA2C89F25E00C3B4DE /* Shared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared.swift; sourceTree = "<group>"; };
+ 0543E87A2C8A93A9004AA8B7 /* FileDropView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileDropView.swift; sourceTree = "<group>"; };
+ 05BAA8CF2C8CE248003CFCF1 /* SecurityScopedResourceManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecurityScopedResourceManager.swift; sourceTree = "<group>"; };
2F8CCFF0FAB783405F067709 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
@@ -76,6 +111,13 @@
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
+ 053DADD72C8945EF00C3B4DE /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
33CC10EA2044A3C60003C045 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@@ -87,6 +129,18 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
+ 053DADDB2C8945EF00C3B4DE /* ShareExtension */ = {
+ isa = PBXGroup;
+ children = (
+ 053DADDC2C8945EF00C3B4DE /* icon.icns */,
+ 053DADE32C8945EF00C3B4DE /* Info.plist */,
+ 053DADF42C89486500C3B4DE /* ShareController.swift */,
+ 053DADF12C8947A500C3B4DE /* Utilities.swift */,
+ 053DADE42C8945EF00C3B4DE /* ShareExtension.entitlements */,
+ );
+ path = ShareExtension;
+ sourceTree = "<group>";
+ };
33BA886A226E78AF003329D5 /* Configs */ = {
isa = PBXGroup;
children = (
@@ -103,6 +157,7 @@
children = (
33FAB671232836740065AC1E /* Runner */,
33CEB47122A05771004F2AC0 /* Flutter */,
+ 053DADDB2C8945EF00C3B4DE /* ShareExtension */,
33CC10EE2044A3C60003C045 /* Products */,
D73912EC22F37F3D000D13A0 /* Frameworks */,
D56CB2F58F756550B9F5851D /* Pods */,
@@ -113,6 +168,7 @@
isa = PBXGroup;
children = (
33CC10ED2044A3C60003C045 /* LocalSend.app */,
+ 053DADDA2C8945EF00C3B4DE /* ShareExtension.appex */,
);
name = Products;
sourceTree = "<group>";
@@ -143,7 +199,10 @@
isa = PBXGroup;
children = (
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
+ 0543E87A2C8A93A9004AA8B7 /* FileDropView.swift */,
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
+ 05BAA8CF2C8CE248003CFCF1 /* SecurityScopedResourceManager.swift */,
+ 053DADFA2C89F25E00C3B4DE /* Shared.swift */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
33CC11242044D66E0003C045 /* Resources */,
@@ -173,6 +232,25 @@
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
+ 053DADD92C8945EF00C3B4DE /* ShareExtension */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 053DADEC2C8945EF00C3B4DE /* Build configuration list for PBXNativeTarget "ShareExtension" */;
+ buildPhases = (
+ 053DADD62C8945EF00C3B4DE /* Sources */,
+ 053DADD72C8945EF00C3B4DE /* Frameworks */,
+ 053DADD82C8945EF00C3B4DE /* Resources */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = ShareExtension;
+ packageProductDependencies = (
+ );
+ productName = ShareExtension;
+ productReference = 053DADDA2C8945EF00C3B4DE /* ShareExtension.appex */;
+ productType = "com.apple.product-type.app-extension";
+ };
33CC10EC2044A3C60003C045 /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
@@ -184,13 +262,17 @@
33CC110E2044A8840003C045 /* Bundle Framework */,
3399D490228B24CF009A79C7 /* ShellScript */,
2DA7D291A0AEEC0A0C7CE5C0 /* [CP] Embed Pods Frameworks */,
+ 053DADE82C8945EF00C3B4DE /* Embed Foundation Extensions */,
);
buildRules = (
);
dependencies = (
33CC11202044C79F0003C045 /* PBXTargetDependency */,
+ 053DADE62C8945EF00C3B4DE /* PBXTargetDependency */,
);
name = Runner;
+ packageProductDependencies = (
+ );
productName = Runner;
productReference = 33CC10ED2044A3C60003C045 /* LocalSend.app */;
productType = "com.apple.product-type.application";
@@ -201,10 +283,14 @@
33CC10E52044A3C60003C045 /* Project object */ = {
isa = PBXProject;
attributes = {
- LastSwiftUpdateCheck = 0920;
+ LastSwiftUpdateCheck = 1540;
LastUpgradeCheck = 1430;
ORGANIZATIONNAME = "";
TargetAttributes = {
+ 053DADD92C8945EF00C3B4DE = {
+ CreatedOnToolsVersion = 15.4;
+ LastSwiftMigration = 1540;
+ };
33CC10EC2044A3C60003C045 = {
CreatedOnToolsVersion = 9.2;
LastSwiftMigration = 1100;
@@ -216,6 +302,7 @@
};
33CC111A2044C6BA0003C045 = {
CreatedOnToolsVersion = 9.2;
+ LastSwiftMigration = 1540;
ProvisioningStyle = Manual;
};
};
@@ -229,17 +316,28 @@
Base,
);
mainGroup = 33CC10E42044A3C60003C045;
+ packageReferences = (
+ );
productRefGroup = 33CC10EE2044A3C60003C045 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
33CC10EC2044A3C60003C045 /* Runner */,
33CC111A2044C6BA0003C045 /* Flutter Assemble */,
+ 053DADD92C8945EF00C3B4DE /* ShareExtension */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
+ 053DADD82C8945EF00C3B4DE /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 053DADDD2C8945EF00C3B4DE /* icon.icns in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
33CC10EB2044A3C60003C045 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@@ -332,11 +430,24 @@
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
+ 053DADD62C8945EF00C3B4DE /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 053DADF32C8947A500C3B4DE /* Utilities.swift in Sources */,
+ 053DADFE2C89F83500C3B4DE /* Shared.swift in Sources */,
+ 053DADF62C89486500C3B4DE /* ShareController.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
33CC10E92044A3C60003C045 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ 0543E87B2C8A93A9004AA8B7 /* FileDropView.swift in Sources */,
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
+ 053DADFD2C89F83400C3B4DE /* Shared.swift in Sources */,
+ 05BAA8D02C8CE248003CFCF1 /* SecurityScopedResourceManager.swift in Sources */,
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
);
@@ -345,6 +456,11 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
+ 053DADE62C8945EF00C3B4DE /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = 053DADD92C8945EF00C3B4DE /* ShareExtension */;
+ targetProxy = 053DADE52C8945EF00C3B4DE /* PBXContainerItemProxy */;
+ };
33CC11202044C79F0003C045 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */;
@@ -365,6 +481,150 @@
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
+ 053DADE92C8945EF00C3B4DE /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements;
+ CODE_SIGN_IDENTITY = "Apple Development";
+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
+ CODE_SIGN_STYLE = Automatic;
+ COMBINE_HIDPI_IMAGES = YES;
+ CURRENT_PROJECT_VERSION = 1;
+ DEVELOPMENT_TEAM = 3W7H4PYMCV;
+ ENABLE_HARDENED_RUNTIME = YES;
+ ENABLE_USER_SCRIPT_SANDBOXING = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu17;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = ShareExtension/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = LocalSend;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ "@executable_path/../../../../Frameworks",
+ );
+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
+ MACOSX_DEPLOYMENT_TARGET = 11.0;
+ MARKETING_VERSION = 1.0;
+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
+ MTL_FAST_MATH = YES;
+ PRODUCT_BUNDLE_IDENTIFIER = org.localsend.localsendApp.ShareExtension;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ PROVISIONING_PROFILE_SPECIFIER = "";
+ SKIP_INSTALL = YES;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
+ SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 5.0;
+ };
+ name = Debug;
+ };
+ 053DADEA2C8945EF00C3B4DE /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements;
+ CODE_SIGN_IDENTITY = "Apple Development";
+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
+ CODE_SIGN_STYLE = Automatic;
+ COMBINE_HIDPI_IMAGES = YES;
+ CURRENT_PROJECT_VERSION = 1;
+ DEVELOPMENT_TEAM = 3W7H4PYMCV;
+ ENABLE_HARDENED_RUNTIME = YES;
+ ENABLE_USER_SCRIPT_SANDBOXING = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu17;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = ShareExtension/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = LocalSend;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ "@executable_path/../../../../Frameworks",
+ );
+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
+ MACOSX_DEPLOYMENT_TARGET = 11.0;
+ MARKETING_VERSION = 1.0;
+ MTL_FAST_MATH = YES;
+ PRODUCT_BUNDLE_IDENTIFIER = org.localsend.localsendApp.ShareExtension;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ PROVISIONING_PROFILE_SPECIFIER = "";
+ SKIP_INSTALL = YES;
+ SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_VERSION = 5.0;
+ };
+ name = Release;
+ };
+ 053DADEB2C8945EF00C3B4DE /* Profile */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements;
+ CODE_SIGN_IDENTITY = "Apple Development";
+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
+ CODE_SIGN_STYLE = Automatic;
+ COMBINE_HIDPI_IMAGES = YES;
+ CURRENT_PROJECT_VERSION = 1;
+ DEVELOPMENT_TEAM = 3W7H4PYMCV;
+ ENABLE_HARDENED_RUNTIME = YES;
+ ENABLE_USER_SCRIPT_SANDBOXING = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu17;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = ShareExtension/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = LocalSend;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ "@executable_path/../../../../Frameworks",
+ );
+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
+ MACOSX_DEPLOYMENT_TARGET = 11.0;
+ MARKETING_VERSION = 1.0;
+ MTL_FAST_MATH = YES;
+ PRODUCT_BUNDLE_IDENTIFIER = org.localsend.localsendApp.ShareExtension;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ PROVISIONING_PROFILE_SPECIFIER = "";
+ SKIP_INSTALL = YES;
+ SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_VERSION = 5.0;
+ };
+ name = Profile;
+ };
338D0CE9231458BD00FA5F75 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
@@ -415,6 +675,7 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
@@ -437,8 +698,11 @@
338D0CEB231458BD00FA5F75 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Manual;
PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_OBJC_BRIDGING_HEADER = "ShareExtension/Flutter Assemble-Bridging-Header.h";
+ SWIFT_VERSION = 5.0;
};
name = Profile;
};
@@ -545,6 +809,7 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
@@ -569,6 +834,7 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
+ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements;
@@ -591,22 +857,39 @@
33CC111C2044C6BA0003C045 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Manual;
PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_OBJC_BRIDGING_HEADER = "ShareExtension/Flutter Assemble-Bridging-Header.h";
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 5.0;
};
name = Debug;
};
33CC111D2044C6BA0003C045 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
+ CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_OBJC_BRIDGING_HEADER = "ShareExtension/Flutter Assemble-Bridging-Header.h";
+ SWIFT_VERSION = 5.0;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
+ 053DADEC2C8945EF00C3B4DE /* Build configuration list for PBXNativeTarget "ShareExtension" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 053DADE92C8945EF00C3B4DE /* Debug */,
+ 053DADEA2C8945EF00C3B4DE /* Release */,
+ 053DADEB2C8945EF00C3B4DE /* Profile */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
diff --git a/app/macos/Runner.xcodeproj/xcshareddata/xcschemes/ShareExtension.xcscheme b/app/macos/Runner.xcodeproj/xcshareddata/xcschemes/ShareExtension.xcscheme
new file mode 100644
index 00000000..afecfaea
--- /dev/null
+++ b/app/macos/Runner.xcodeproj/xcshareddata/xcschemes/ShareExtension.xcscheme
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "1540"
+ wasCreatedForAppExtension = "YES"
+ version = "1.7">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES"
+ buildArchitectures = "Automatic">
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "053DADD92C8945EF00C3B4DE"
+ BuildableName = "ShareExtension.appex"
+ BlueprintName = "ShareExtension"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"
+ BuildableName = "LocalSend.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ shouldAutocreateTestPlan = "YES">
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ launchStyle = "0"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"
+ BuildableName = "LocalSend.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Release"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES"
+ askForAppToLaunch = "Yes"
+ launchAutomaticallySubstyle = "2">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"
+ BuildableName = "LocalSend.app"
+ BlueprintName = "Runner"
+ ReferencedContainer = "container:Runner.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/app/macos/Runner/AppDelegate.swift b/app/macos/Runner/AppDelegate.swift
index 3772af56..bbf71714 100644
--- a/app/macos/Runner/AppDelegate.swift
+++ b/app/macos/Runner/AppDelegate.swift
@@ -1,21 +1,32 @@
import Cocoa
import FlutterMacOS
+import Defaults
@main
class AppDelegate: FlutterAppDelegate {
+ private var statusItem: NSStatusItem?
+ private var channel: FlutterMethodChannel?
+ private var pendingFilesObservation: Defaults.Observation?
+
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
// LocalSend handles the close event manually
return false
}
- private var statusItem: NSStatusItem?
- private var channel: FlutterMethodChannel?
- private var cachedFiles: [String]? = []
-
override func applicationDidFinishLaunching(_ notification: Notification) {
let controller = mainFlutterWindow?.contentViewController as! FlutterViewController
channel = FlutterMethodChannel(name: "main-delegate-channel", binaryMessenger: controller.engine.binaryMessenger)
channel?.setMethodCallHandler(handle)
+
+ self.setupPendingItemsObservation()
+ }
+
+ private func setupPendingItemsObservation() {
+ self.pendingFilesObservation = Defaults.observe(.pendingFiles) { change in
+ let pendingFileBookmarks = Defaults[.pendingFiles]
+ guard !pendingFileBookmarks.isEmpty else { return }
+ self.sendPendingItemsToFlutter()
+ }
}
private func setupStatusBarItem(i18n: [String: String]) {
@@ -27,11 +38,11 @@ class AppDelegate: FlutterAppDelegate {
button.image = image
let menu = NSMenu()
-
+
let openString = i18n["open"]!
let openItem = NSMenuItem(title: openString, action: #selector(openApp), keyEquivalent: "o")
menu.addItem(openItem)
-
+
let quitString = i18n["quit"]!
let quitItem = NSMenuItem(title: quitString, action: #selector(quitApp), keyEquivalent: "q")
menu.addItem(quitItem)
@@ -39,7 +50,6 @@ class AppDelegate: FlutterAppDelegate {
statusItem?.menu = menu
let dragView = FileDropView(frame: button.bounds)
- dragView.appDelegate = self
button.addSubview(dragView)
dragView.translatesAutoresizingMaskIntoConstraints = false
@@ -61,17 +71,37 @@ class AppDelegate: FlutterAppDelegate {
NSApp.terminate(nil)
}
- func sendFilesToFlutter(_ filenames: [String]) {
- cachedFiles?.append(contentsOf: filenames)
- channel?.invokeMethod("onFiles", arguments: filenames)
+ func sendPendingItemsToFlutter() {
+ let pendingFileBookmarks = Defaults[.pendingFiles]
+ var filePaths: [String] = []
+
+ for bookmark in pendingFileBookmarks {
+ if let url = SecurityScopedResourceManager.shared.startAccessing(bookmark: bookmark) {
+ filePaths.append(url.path)
+ }
+ }
+
+ channel?.invokeMethod("onPendingFiles", arguments: filePaths)
+ Defaults[.pendingFiles] = []
+ openApp()
}
// START: handle opened files
private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
- case "getFiles":
- result(cachedFiles ?? [])
- cachedFiles = nil // files has been fetched, no need to cache anymore
+ case "getPendingFiles":
+ let pendingFileBookmarks = Defaults[.pendingFiles]
+ var filePaths: [String] = []
+
+ for bookmark in pendingFileBookmarks {
+ if let url = SecurityScopedResourceManager.shared.startAccessing(bookmark: bookmark) {
+ filePaths.append(url.path)
+ }
+ }
+
+ result(filePaths)
+ Defaults[.pendingFiles] = []
+ openApp()
case "setupStatusBar":
let i18n = call.arguments as! [String: String]
setupStatusBarItem(i18n: i18n)
@@ -82,47 +112,23 @@ class AppDelegate: FlutterAppDelegate {
}
override func application(_ sender: NSApplication, openFile filename: String) -> Bool {
- sendFilesToFlutter([filename])
+ /**
+ Although file URLs shared via the dock icon or the "open with" file menu item already contain access permission, we pass this through the bookmark mechanism for uniformity and readability of the code with URLs shared from the share extension.
+ - SeeAlso: [Enabling App Sandbox#Enabling User-Selected File Access](https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW6)
+ - SeeAlso: [``Shared/createBookmarkForFile(at:)``](x-source-tag://create-bookmark-func)
+ */
+ if let fileBookmark = createBookmarkForFile(at: URL(fileURLWithPath: filename)) {
+ Defaults[.pendingFiles].append(fileBookmark)
+ }
return true
}
override func application(_ sender: NSApplication, openFiles filenames: [String]) {
- sendFilesToFlutter(filenames)
- }
- // END: handle opened files
-}
-
-class FileDropView: NSView {
- weak var appDelegate: AppDelegate?
-
- override init(frame frameRect: NSRect) {
- super.init(frame: frameRect)
- setup()
- }
-
- required init?(coder: NSCoder) {
- super.init(coder: coder)
- setup()
- }
-
- private func setup() {
- registerForDraggedTypes([NSPasteboard.PasteboardType.fileURL])
- }
-
- override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
- return .copy
- }
-
- override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
- let pasteboard = sender.draggingPasteboard
-
- if let fileUrls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] {
- let filenames = fileUrls.map { $0.path }
- appDelegate?.sendFilesToFlutter(filenames)
- appDelegate?.openApp()
- return true
+ for filename in filenames {
+ if let fileBookmark = createBookmarkForFile(at: URL(fileURLWithPath: filename)) {
+ Defaults[.pendingFiles].append(fileBookmark)
+ }
}
-
- return false
}
+ // END: handle opened files
}
diff --git a/app/macos/Runner/DebugProfile.entitlements b/app/macos/Runner/DebugProfile.entitlements
index 91f41fb6..66485d8a 100644
--- a/app/macos/Runner/DebugProfile.entitlements
+++ b/app/macos/Runner/DebugProfile.entitlements
@@ -4,6 +4,10 @@
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>com.localsend.shared_group</string>
+ </array>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.files.downloads.read-write</key>
diff --git a/app/macos/Runner/FileDropView.swift b/app/macos/Runner/FileDropView.swift
new file mode 100644
index 00000000..3422b1ed
--- /dev/null
+++ b/app/macos/Runner/FileDropView.swift
@@ -0,0 +1,38 @@
+import Defaults
+
+class FileDropView: NSView {
+ override init(frame frameRect: NSRect) {
+ super.init(frame: frameRect)
+ setup()
+ }
+
+ required init?(coder: NSCoder) {
+ super.init(coder: coder)
+ setup()
+ }
+
+ private func setup() {
+ registerForDraggedTypes([NSPasteboard.PasteboardType.fileURL])
+ }
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
+ return .copy
+ }
+
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ let pasteboard = sender.draggingPasteboard
+
+ if let fileUrls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] {
+ /**
+ Although file URLs shared via dragging already contain access permission, we pass this through the bookmark mechanism for uniformity and readability of the code with URLs shared from the share extension.
+ - SeeAlso: [Enabling App Sandbox#Enabling User-Selected File Access](https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW6)
+ - SeeAlso: [``Shared/createBookmarkForFile(at:)``](x-source-tag://create-bookmark-func)
+ */
+ let bookmarks: [Data] = fileUrls.compactMap { createBookmarkForFile(at: $0) }
+ Defaults[.pendingFiles].append(contentsOf: bookmarks)
+ return true
+ }
+
+ return false
+ }
+}
diff --git a/app/macos/Runner/Release.entitlements b/app/macos/Runner/Release.entitlements
index 02ce7ecf..32c32845 100644
--- a/app/macos/Runner/Release.entitlements
+++ b/app/macos/Runner/Release.entitlements
@@ -4,6 +4,10 @@
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>com.localsend.shared_group</string>
+ </array>
<key>com.apple.security.files.downloads.read-write</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
diff --git a/app/macos/Runner/SecurityScopedResourceManager.swift b/app/macos/Runner/SecurityScopedResourceManager.swift
new file mode 100644
index 00000000..8c9b2a89
--- /dev/null
+++ b/app/macos/Runner/SecurityScopedResourceManager.swift
@@ -0,0 +1,34 @@
+import Foundation
+
+class SecurityScopedResourceManager {
+ static let shared = SecurityScopedResourceManager()
+ private var openResources: [URL: Data] = [:]
+
+ private init() {}
+
+ func startAccessing(bookmark: Data) -> URL? {
+ do {
+ var isStale = false
+ let url = try URL(resolvingBookmarkData: bookmark, options: .withoutUI, relativeTo: nil, bookmarkDataIsStale: &isStale)
+
+ if url.startAccessingSecurityScopedResource() {
+ openResources[url] = bookmark
+ return url
+ } else {
+ print("Failed to start accessing security-scoped resource: \(url)")
+ return nil
+ }
+ } catch {
+ print("Failed to resolve security-scoped bookmark: \(error)")
+ return nil
+ }
+ }
+
+ func stopAccessing(url: URL) {
+ // TODO: stop accessing when file is not needed anymore! See: https://developer.apple.com/documentation/foundation/url/1779698-startaccessingsecurityscopedreso#:~:text=resource%20in%20question.-,Warning,-If%20you%20fail
+ if openResources.keys.contains(url) {
+ url.stopAccessingSecurityScopedResource()
+ openResources.removeValue(forKey: url)
+ }
+ }
+}
diff --git a/app/macos/Runner/Shared.swift b/app/macos/Runner/Shared.swift
new file mode 100644
index 00000000..996a0f07
--- /dev/null
+++ b/app/macos/Runner/Shared.swift
@@ -0,0 +1,39 @@
+import Foundation
+import Defaults
+
+let sharedDefaults = UserDefaults(suiteName: "com.localsend.shared_group")!
+
+typealias BookmarkData = Data
+extension Defaults.Keys {
+ static let pendingFiles = Key<[BookmarkData]>("pendingFiles", default: [], suite: sharedDefaults)
+}
+
+/**
+ Creates a minimal bookmark for a given file URL.
+
+ That allows the main app to access the file as a "User Selected File" later. Otherwise, the file will be successfully selected but an attempt to send it (that is, actually read it) will fail.
+
+ - Important: We intentionally avoid creating a security-scoped bookmark (`.withSecurityScope` option) here, as security-scoped bookmarks cannot be transferred between apps or app extensions.
+ - See:
+ - - [Open Radar: Security scoped bookmarks don't work with app groups](https://openradar.appspot.com/43055392)
+ - - [Reply from Apple DTS in Apple Developer Forums: Share security scoped bookmark in app group? (Alternative Answer)](https://developer.apple.com/forums/thread/66259?answerId=336402022#336402022)
+ - - [Detailed instructions in Apple Developer Forums: Share security scoped bookmark in app group? (Alternative Answer)](https://developer.apple.com/forums/thread/66259?answerId=278355022#278355022)
+
+ - Note: The main app and the sharing plugin must have
+ The same level of "User Selected File" permission (Read Only or Read/Write)
+
+ - Tag: create-bookmark-func
+ */
+func createBookmarkForFile(at url: URL) -> BookmarkData? {
+ do {
+ let securityScopedBookmark = try (url as NSURL).bookmarkData(
+ options: .minimalBookmark,
+ includingResourceValuesForKeys: nil,
+ relativeTo: nil
+ )
+ return securityScopedBookmark
+ } catch {
+ print("Failed to create security-scoped bookmark for \(url): \(error)")
+ return nil
+ }
+}
diff --git a/app/macos/ShareExtension/Info.plist b/app/macos/ShareExtension/Info.plist
new file mode 100644
index 00000000..492fefca
--- /dev/null
+++ b/app/macos/ShareExtension/Info.plist
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleIconFile</key>
+ <string>icon</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionAttributes</key>
+ <dict>
+ <key>NSExtensionActivationRule</key>
+ <dict>
+ <key>NSExtensionActivationDictionaryVersion</key>
+ <integer>2</integer>
+ <key>NSExtensionActivationSupportsAttachmentsWithMaxCount</key>
+ <integer>1000</integer>
+ <key>NSExtensionActivationSupportsFileWithMaxCount</key>
+ <integer>1000</integer>
+ <key>NSExtensionActivationSupportsImageWithMaxCount</key>
+ <integer>1000</integer>
+ <key>NSExtensionActivationSupportsMovieWithMaxCount</key>
+ <integer>1000</integer>
+ <key>NSExtensionActivationSupportsText</key>
+ <false/>
+ <key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
+ <integer>0</integer>
+ </dict>
+ </dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.share-services</string>
+ <key>NSExtensionPrincipalClass</key>
+ <string>$(PRODUCT_MODULE_NAME).ShareController</string>
+ </dict>
+</dict>
+</plist>
diff --git a/app/macos/ShareExtension/ShareController.swift b/app/macos/ShareExtension/ShareController.swift
new file mode 100644
index 00000000..0d2f4229
--- /dev/null
+++ b/app/macos/ShareExtension/ShareController.swift
@@ -0,0 +1,41 @@
+import SwiftUI
+import Defaults
+
+final class ShareController: ExtensionController {
+ override func run(_ context: NSExtensionContext) async throws -> [NSExtensionItem] {
+ var urls: [URL] = []
+
+ for attachment in context.attachments {
+ if attachment.hasItemConforming(to: .url) {
+ do {
+ let url = try await attachment.loadItem(ofClass: NSURL.self) as URL
+ urls.append(url)
+ } catch {
+ print("Failed to load URL: \(error)")
+ }
+ }
+ }
+
+ if urls.isEmpty {
+ context.cancel()
+ return []
+ }
+
+ /// - SeeAlso: [``Shared/createBookmarkForFile(at:)``](x-source-tag://create-bookmark-func)
+ let bookmarks: [Data] = urls.compactMap { createBookmarkForFile(at: $0) }
+
+ // Save the file bookmarks to a shared UserDefaults
+ // This is Apple's recommended way to share data from App Extension to the Containing App
+ // See: https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW6
+ Defaults[.pendingFiles].append(contentsOf: bookmarks)
+
+ // Launch localsend app if it's not running
+ let localsendAppURL = getParentAppURL()
+ launchAppIfNeeded(appURL: localsendAppURL)
+
+ // Close the share extension
+ context.completeRequest(returningItems: [], completionHandler: nil)
+
+ return []
+ }
+}
diff --git a/app/macos/ShareExtension/ShareExtension.entitlements b/app/macos/ShareExtension/ShareExtension.entitlements
new file mode 100644
index 00000000..4acd7515
--- /dev/null
+++ b/app/macos/ShareExtension/ShareExtension.entitlements
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.app-sandbox</key>
+ <true/>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>com.localsend.shared_group</string>
+ </array>
+ <key>com.apple.security.files.user-selected.read-write</key>
+ <true/>
+</dict>
+</plist>
diff --git a/app/macos/ShareExtension/Utilities.swift b/app/macos/ShareExtension/Utilities.swift
new file mode 100644
index 00000000..61a0bfa8
--- /dev/null
+++ b/app/macos/ShareExtension/Utilities.swift
@@ -0,0 +1,113 @@
+import SwiftUI
+import UniformTypeIdentifiers
+
+
+extension Sequence where Element: Sequence {
+ func flatten() -> [Element.Element] {
+ // TODO: Make this `flatMap(\.self)` when https://github.com/apple/swift/issues/55343 is fixed.
+ flatMap { $0 }
+ }
+}
+
+
+extension NSExtensionContext {
+ var inputItemsTyped: [NSExtensionItem] { inputItems as! [NSExtensionItem] }
+
+ var attachments: [NSItemProvider] {
+ inputItemsTyped.compactMap(\.attachments).flatten()
+ }
+}
+
+
+// Strongly-typed versions of some of the methods.
+extension NSItemProvider {
+ func hasItemConforming(to contentType: UTType) -> Bool {
+ hasItemConformingToTypeIdentifier(contentType.identifier)
+ }
+}
+
+
+extension NSError {
+ static let userCancelled = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
+}
+
+
+extension NSExtensionContext {
+ func cancel() {
+ cancelRequest(withError: NSError.userCancelled)
+ }
+}
+
+
+extension NSItemProvider {
+ func loadItem<T>(ofClass cls: T.Type) async throws -> T where T: NSItemProviderReading {
+ try await withCheckedThrowingContinuation { continuation in
+ _ = self.loadObject(ofClass: cls) { (item, error) in
+ if let error = error {
+ continuation.resume(throwing: error)
+ } else if let item = item as? T {
+ continuation.resume(returning: item)
+ } else {
+ continuation.resume(throwing: NSError(domain: "ItemProviderError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to load item of expected type"]))
+ }
+ }
+ }
+ }
+}
+
+
+@MainActor
+class ExtensionController: NSViewController {
+ @MainActor
+ init() {
+ super.init(nibName: nil, bundle: nil)
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) {
+ fatalError()
+ }
+
+ override func loadView() {
+ Task { @MainActor in // Not sure if this is needed, but added just in case.
+ do {
+ extensionContext!.completeRequest(
+ returningItems: try await run(extensionContext!),
+ completionHandler: nil
+ )
+ } catch {
+ extensionContext!.cancelRequest(withError: error)
+ }
+ }
+ }
+
+ func run(_ context: NSExtensionContext) async throws -> [NSExtensionItem] { [] }
+}
+
+extension NSItemProvider: @unchecked Sendable {}
+
+fileprivate func isAppRunning(at url: URL) -> Bool {
+ NSWorkspace.shared.runningApplications.contains { $0.bundleURL == url }
+}
+
+func launchAppIfNeeded(appURL: URL) {
+ guard !isAppRunning(at: appURL) else { return }
+ NSWorkspace.shared.openApplication(at: appURL, configuration: NSWorkspace.OpenConfiguration()) { (app, error) in
+ if let error = error {
+ print("Error opening the application: \(error.localizedDescription)")
+ } else if let app = app {
+ print("Application opened successfully: \(app.bundleIdentifier ?? "")")
+ } else {
+ print("Failed to open the application for an unknown reason")
+ }
+ }
+}
+
+/// Peel off 3 directory levels to get the containing app URL from the app extension
+/// MY_APP.app/Contents/PlugIns/MY_APP_EXTENSION.appex
+func getParentAppURL() -> URL {
+ Bundle.main.bundleURL
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+}
diff --git a/app/macos/ShareExtension/icon.icns b/app/macos/ShareExtension/icon.icns
new file mode 100644
index 00000000..84ae85cd
Binary files /dev/null and b/app/macos/ShareExtension/icon.icns differ