drag_util_mac.mm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright (c) 2016 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #import <Cocoa/Cocoa.h>
  5. #include "atom/browser/ui/drag_util.h"
  6. #include "base/files/file_path.h"
  7. #include "base/strings/sys_string_conversions.h"
  8. namespace atom {
  9. namespace {
  10. // Write information about the file being dragged to the pasteboard.
  11. void AddFilesToPasteboard(NSPasteboard* pasteboard,
  12. const std::vector<base::FilePath>& files) {
  13. NSMutableArray* fileList = [NSMutableArray array];
  14. for (const base::FilePath& file : files)
  15. [fileList addObject:base::SysUTF8ToNSString(file.value())];
  16. [pasteboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType]
  17. owner:nil];
  18. [pasteboard setPropertyList:fileList forType:NSFilenamesPboardType];
  19. }
  20. } // namespace
  21. void DragFileItems(const std::vector<base::FilePath>& files,
  22. const gfx::Image& icon,
  23. gfx::NativeView view) {
  24. NSPasteboard* pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
  25. AddFilesToPasteboard(pasteboard, files);
  26. // Synthesize a drag event, since we don't have access to the actual event
  27. // that initiated a drag (possibly consumed by the Web UI, for example).
  28. NSWindow* window = [view.GetNativeNSView() window];
  29. NSPoint position = [window mouseLocationOutsideOfEventStream];
  30. NSTimeInterval eventTime = [[NSApp currentEvent] timestamp];
  31. NSEvent* dragEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
  32. location:position
  33. modifierFlags:NSLeftMouseDraggedMask
  34. timestamp:eventTime
  35. windowNumber:[window windowNumber]
  36. context:nil
  37. eventNumber:0
  38. clickCount:1
  39. pressure:1.0];
  40. // Run the drag operation.
  41. [window dragImage:icon.ToNSImage()
  42. at:position
  43. offset:NSZeroSize
  44. event:dragEvent
  45. pasteboard:pasteboard
  46. source:view.GetNativeNSView()
  47. slideBack:YES];
  48. }
  49. } // namespace atom