drag_util_mac.mm 2.3 KB

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