FreeRDP
Loading...
Searching...
No Matches
client_cliprdr_file_apple.m
1
19
20#include <stdlib.h>
21#include <string.h>
22#include <unistd.h>
23#include <os/lock.h>
24
25#import <AppKit/AppKit.h>
26#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
27
28#include "client_cliprdr_file_apple.h"
29
30static const char s_mime_uri_list[] = "text/uri-list";
31static const char s_mime_text_utf8[] = "text/plain;charset=utf-8";
32
33static NSArray<NSURL *> *get_file_urls(void)
34{
35 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
36 NSDictionary *options = @{NSPasteboardURLReadingFileURLsOnlyKey: @YES};
37 return [pasteboard readObjectsForClasses:@[[NSURL class]] options:options];
38}
39
40char *cliprdr_file_apple_get_uri_list(size_t *size)
41{
42 @autoreleasepool
43 {
44 NSMutableString *list = [NSMutableString string];
45
46 for (NSURL *url in get_file_urls())
47 {
48 /* Finder puts file reference URLs (file:///.file/id=...) on the pasteboard */
49 NSURL *path_url = [url filePathURL];
50 if (!path_url)
51 continue;
52 [list appendFormat:@"%@\r\n", [path_url absoluteString]];
53 }
54
55 if ([list length] == 0)
56 return NULL;
57
58 char *data = strdup([list UTF8String]);
59 if (data && size)
60 *size = strlen(data);
61 return data;
62 }
63}
64
65/* The offers are replaced on the main thread and detached on the channel thread */
66static os_unfair_lock s_lock = OS_UNFAIR_LOCK_INIT;
67static cliprdr_file_context_data_fkt s_data_fkt = NULL;
68static void *s_data_userdata = NULL;
69static NSUInteger s_generation = 0;
70static unsigned s_download_serial = 0;
71
72/* All file presenters share this serial queue: one download at a time, off the main thread */
73static NSOperationQueue *download_queue(void)
74{
75 static NSOperationQueue *queue = nil;
76 static dispatch_once_t once;
77 dispatch_once(&once, ^{
78 queue = [NSOperationQueue new];
79 queue.maxConcurrentOperationCount = 1;
80 queue.name = @"com.freerdp.client.cliprdr.file";
81 });
82 return queue;
83}
84
85/* Remove downloaded files as a coordinated writer: it waits for an application that still
86 * reads them, e.g. the Finder copying a file that was just downloaded. */
87static void remove_path(NSString *path)
88{
89 NSURL *url = [NSURL fileURLWithPath:path isDirectory:YES];
90 NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
91 __block BOOL removed = NO;
92 [coordinator coordinateWritingItemAtURL:url
93 options:NSFileCoordinatorWritingForDeleting
94 error:nil
95 byAccessor:^(NSURL *newURL) {
96 [[NSFileManager defaultManager] removeItemAtURL:newURL
97 error:nil];
98 removed = YES;
99 }];
100 if (!removed)
101 [[NSFileManager defaultManager] removeItemAtURL:url error:nil];
102}
103
104/* The placeholders of one server copy and what downloads them */
105@interface CliprdrFileOffer : NSObject
106@property(nonatomic) cliprdr_file_apple_download_fkt downloadFkt;
107@property(nonatomic) cliprdr_file_apple_release_fkt releaseFkt;
108@property(nonatomic) void *userdata;
109@property(nonatomic, copy) NSString *directory;
110@property(nonatomic, strong) NSMutableArray *presenters;
111- (void)invalidate;
112@end
113
114static CliprdrFileOffer *s_offer = nil;
115static CliprdrFileOffer *s_previous_offer = nil;
116
117@implementation CliprdrFileOffer
118
119/* Stop watching the placeholders. Not on the download queue: it delivers their messages. */
120- (void)invalidate
121{
122 for (id<NSFilePresenter> presenter in self.presenters)
123 [NSFileCoordinator removeFilePresenter:presenter];
124 [self.presenters removeAllObjects];
125}
126
127- (void)dealloc
128{
129 /* The last reference might be the one of a download, on the download queue */
130 NSArray *presenters = [_presenters copy];
131 NSString *directory = _directory;
132 cliprdr_file_apple_release_fkt releaseFkt = _releaseFkt;
133 void *userdata = _userdata;
134
135 dispatch_async(dispatch_get_main_queue(), ^{
136 for (id<NSFilePresenter> presenter in presenters)
137 [NSFileCoordinator removeFilePresenter:presenter];
138 if (releaseFkt)
139 releaseFkt(userdata);
140 if (directory)
141 {
142 dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
143 remove_path(directory);
144 });
145 }
146 });
147}
148
149@end
150
151/* Watches one placeholder. An application that reads a file with file coordination, like
152 * the Finder does to copy it, has to wait until its presenter lets it: this is where the
153 * contents are downloaded. The application waits in its own copy operation only, and the
154 * message arrives on the download queue, so neither it nor this process is blocked. */
155@interface CliprdrFilePresenter : NSObject <NSFilePresenter>
156@property(nonatomic, weak) CliprdrFileOffer *offer;
157@property(nonatomic) size_t index;
158@property(nonatomic, strong) NSURL *url;
159@end
160
161@implementation CliprdrFilePresenter
162
163- (NSURL *)presentedItemURL
164{
165 return self.url;
166}
167
168- (NSOperationQueue *)presentedItemOperationQueue
169{
170 return download_queue();
171}
172
173- (void)relinquishPresentedItemToReader:(void (^)(void (^_Nullable reacquirer)(void)))reader
174{
175 /* This reference keeps the offer and its files until the download returned */
176 CliprdrFileOffer *offer = self.offer;
177
178 /* Better no file than an empty one: the download removes what it could not complete,
179 * and without an offer there is nothing to download from any more */
180 if (offer && offer.downloadFkt)
181 (void)offer.downloadFkt(offer.userdata, self.index);
182 else
183 [[NSFileManager defaultManager] removeItemAtURL:self.url error:nil];
184 reader(nil);
185}
186
187@end
188
189/* Provides the other formats of a server copy (e.g. its text) when they are pasted */
190@interface CliprdrDataProvider : NSObject <NSPasteboardItemDataProvider>
191@property(nonatomic) NSUInteger generation;
192/* pasteboard type -> MIME type the data is requested with */
193@property(nonatomic, strong) NSDictionary<NSPasteboardType, NSString *> *mimeTypes;
194@end
195
196static CliprdrDataProvider *s_provider = nil;
197
198@implementation CliprdrDataProvider
199
200- (void)pasteboard:(NSPasteboard *)pasteboard
201 item:(NSPasteboardItem *)item
202 provideDataForType:(NSPasteboardType)type
203{
204 if (self.generation != s_generation)
205 return;
206
207 NSString *mime = self.mimeTypes[type];
208 if (!mime || !s_data_fkt)
209 return;
210
211 size_t size = 0;
212 const void *data = s_data_fkt(s_data_userdata, [mime UTF8String], &size);
213 if (!data)
214 return;
215
216 if ([type isEqualToString:NSPasteboardTypeString])
217 {
218 /* Applications that paste text get the text of the copy, e.g. the paths */
219 NSString *text = [[NSString alloc] initWithBytes:data
220 length:size
221 encoding:NSUTF8StringEncoding];
222 if (text)
223 [item setString:text forType:type];
224 }
225 else
226 [item setData:[NSData dataWithBytes:data length:size] forType:type];
227}
228
229@end
230
231/* Text becomes the native string, text/uri-list the file items. Everything else keeps its
232 * own type, so the caller still recognises the copy as its own (e.g. by a private type)
233 * when the pasteboard change comes back to it. */
234API_AVAILABLE(macos(11.0))
235static NSDictionary<NSPasteboardType, NSString *> *get_item_types(const char **mime_types,
236 size_t mime_count)
237{
238 NSMutableDictionary<NSPasteboardType, NSString *> *types = [NSMutableDictionary dictionary];
239
240 for (size_t i = 0; i < mime_count; i++)
241 {
242 const char *mime = mime_types[i];
243 if (!mime || (strcmp(mime, s_mime_uri_list) == 0))
244 continue;
245
246 if (strncmp(mime, "text/", 5) == 0)
247 {
248 types[NSPasteboardTypeString] = @(s_mime_text_utf8);
249 continue;
250 }
251
252 NSString *mime_type = [NSString stringWithUTF8String:mime];
253 UTType *uttype = mime_type ? [UTType typeWithMIMEType:mime_type] : nil;
254 if (uttype && !types[uttype.identifier])
255 types[uttype.identifier] = mime_type;
256 }
257 return types;
258}
259
260static NSURL *path_url(const char *path)
261{
262 NSString *str =
263 [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path
264 length:strlen(path)];
265 /* Looks at the placeholder to tell a directory from a file */
266 return str ? [NSURL fileURLWithPath:str] : nil;
267}
268
269BOOL cliprdr_file_apple_offer(const char *directory, const char **paths, const BOOL *present,
270 size_t count, const size_t *top_level, size_t top_level_count,
271 cliprdr_file_apple_download_fkt download_fkt,
272 cliprdr_file_apple_release_fkt release_fkt, void *offer_userdata,
273 const char **mime_types, size_t mime_count,
274 cliprdr_file_context_data_fkt data_fkt, void *data_userdata)
275{
276 if (@available(macOS 11.0, *))
277 {
278 @autoreleasepool
279 {
280 /* From here on the offer frees offer_userdata and the directory, also when
281 * this function fails */
282 CliprdrFileOffer *offer = [CliprdrFileOffer new];
283 offer.downloadFkt = download_fkt;
284 offer.releaseFkt = release_fkt;
285 offer.userdata = offer_userdata;
286 offer.directory = [[NSFileManager defaultManager]
287 stringWithFileSystemRepresentation:directory
288 length:strlen(directory)];
289 offer.presenters = [NSMutableArray array];
290
291 for (size_t i = 0; i < count; i++)
292 {
293 if (!paths[i] || !present[i])
294 continue;
295
296 CliprdrFilePresenter *presenter = [CliprdrFilePresenter new];
297 presenter.offer = offer;
298 presenter.index = i;
299 presenter.url = path_url(paths[i]);
300 if (!presenter.url)
301 return FALSE;
302
303 [offer.presenters addObject:presenter];
304 [NSFileCoordinator addFilePresenter:presenter];
305 }
306
307 CliprdrDataProvider *provider = nil;
308 NSDictionary<NSPasteboardType, NSString *> *mimeTypes =
309 get_item_types(mime_types, mime_count);
310
311 NSMutableArray *items = [NSMutableArray array];
312 for (size_t i = 0; i < top_level_count; i++)
313 {
314 /* A real file URL: an application gets it right away, and waits for the
315 * contents only when it reads the file */
316 NSURL *url = path_url(paths[top_level[i]]);
317 NSPasteboardItem *item = [NSPasteboardItem new];
318 if (!url || ![item setString:[url absoluteString] forType:NSPasteboardTypeFileURL])
319 return FALSE;
320
321 if ((i == 0) && ([mimeTypes count] > 0))
322 {
323 /* NSPasteboardItem does not keep its data provider alive */
324 provider = [CliprdrDataProvider new];
325 provider.mimeTypes = mimeTypes;
326 if (![item setDataProvider:provider forTypes:[mimeTypes allKeys]])
327 return FALSE;
328 }
329 [items addObject:item];
330 }
331
332 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
333 /* Universal Clipboard reads new contents right away, which would download
334 * every copied file. Keep the files on this Mac until they are pasted. */
335 [pasteboard prepareForNewContentsWithOptions:NSPasteboardContentsCurrentHostOnly];
336 if (![pasteboard writeObjects:items])
337 return FALSE;
338
339 /* Keep the previous offer, Finder might still be copying from it */
340 os_unfair_lock_lock(&s_lock);
341 CliprdrFileOffer *oldest = s_previous_offer;
342 s_previous_offer = s_offer;
343 s_offer = offer;
344 s_data_fkt = data_fkt;
345 s_data_userdata = data_userdata;
346 provider.generation = ++s_generation;
347 s_provider = provider;
348 os_unfair_lock_unlock(&s_lock);
349 oldest = nil; /* released without the lock */
350 return TRUE;
351 }
352 }
353
354 if (release_fkt)
355 release_fkt(offer_userdata);
356 [[NSFileManager defaultManager] removeItemAtPath:@(directory) error:nil];
357 return FALSE;
358}
359
360static NSString *download_root(void)
361{
362 NSString *name = [NSString stringWithFormat:@"freerdp-clipboard-%d", getpid()];
363 return [NSTemporaryDirectory() stringByAppendingPathComponent:name];
364}
365
366char *cliprdr_file_apple_new_download_dir(void)
367{
368 @autoreleasepool
369 {
370 NSFileManager *fm = [NSFileManager defaultManager];
371 NSString *root = download_root();
372
373 NSString *name = [NSString stringWithFormat:@"%u", s_download_serial++];
374 NSString *dir = [root stringByAppendingPathComponent:name];
375 NSDictionary *attributes = @{NSFilePosixPermissions: @0700};
376 if (![fm createDirectoryAtPath:dir
377 withIntermediateDirectories:YES
378 attributes:attributes
379 error:nil])
380 return NULL;
381 return strdup([dir fileSystemRepresentation]);
382 }
383}
384
385void cliprdr_file_apple_detach(void)
386{
387 @autoreleasepool
388 {
389 os_unfair_lock_lock(&s_lock);
390 CliprdrFileOffer *offer = s_offer;
391 CliprdrFileOffer *previous = s_previous_offer;
392 s_offer = nil;
393 s_previous_offer = nil;
394 s_data_fkt = NULL;
395 s_data_userdata = NULL;
396 s_generation++;
397 s_provider = nil;
398 os_unfair_lock_unlock(&s_lock);
399
400 [offer invalidate];
401 [previous invalidate];
402 offer = nil;
403 previous = nil;
404
405 /* The caller cancelled its downloads: wait until the last one returned, it uses
406 * the caller's context. Later messages find no offer any more. */
407 [download_queue() waitUntilAllOperationsAreFinished];
408
409 /* Not as a coordinated writer: that would wait for an application that still
410 * copies a downloaded file, for as long as its copy takes */
411 [[NSFileManager defaultManager] removeItemAtPath:download_root() error:nil];
412 }
413}