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. NSPoint position = [[view window] mouseLocationOutsideOfEventStream];
  29. NSTimeInterval eventTime = [[NSApp currentEvent] timestamp];
  30. NSEvent* dragEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
  31. location:position
  32. modifierFlags:NSLeftMouseDraggedMask
  33. timestamp:eventTime
  34. windowNumber:[[view window] windowNumber]
  35. context:nil
  36. eventNumber:0
  37. clickCount:1
  38. pressure:1.0];
  39. // Run the drag operation.
  40. [[view window] dragImage:icon.ToNSImage()
  41. at:position
  42. offset:NSZeroSize
  43. event:dragEvent
  44. pasteboard:pasteboard
  45. source:view
  46. slideBack:YES];
  47. }
  48. } // namespace atom