legacy.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright 2017 Virgil Dupras
  2. # This software is licensed under the "BSD" License as described in the "LICENSE" file,
  3. # which should be included with this package. The terms are also available at
  4. # http://www.hardcoded.net/licenses/bsd_license
  5. from __future__ import unicode_literals
  6. from ctypes import cdll, byref, Structure, c_char, c_char_p
  7. from ctypes.util import find_library
  8. from send2trash.util import preprocess_paths
  9. Foundation = cdll.LoadLibrary(find_library("Foundation"))
  10. CoreServices = cdll.LoadLibrary(find_library("CoreServices"))
  11. GetMacOSStatusCommentString = Foundation.GetMacOSStatusCommentString
  12. GetMacOSStatusCommentString.restype = c_char_p
  13. FSPathMakeRefWithOptions = CoreServices.FSPathMakeRefWithOptions
  14. FSMoveObjectToTrashSync = CoreServices.FSMoveObjectToTrashSync
  15. kFSPathMakeRefDefaultOptions = 0
  16. kFSPathMakeRefDoNotFollowLeafSymlink = 0x01
  17. kFSFileOperationDefaultOptions = 0
  18. kFSFileOperationOverwrite = 0x01
  19. kFSFileOperationSkipSourcePermissionErrors = 0x02
  20. kFSFileOperationDoNotMoveAcrossVolumes = 0x04
  21. kFSFileOperationSkipPreflight = 0x08
  22. class FSRef(Structure):
  23. _fields_ = [("hidden", c_char * 80)]
  24. def check_op_result(op_result):
  25. if op_result:
  26. msg = GetMacOSStatusCommentString(op_result).decode("utf-8")
  27. raise OSError(msg)
  28. def send2trash(paths):
  29. paths = preprocess_paths(paths)
  30. paths = [path.encode("utf-8") if not isinstance(path, bytes) else path for path in paths]
  31. for path in paths:
  32. fp = FSRef()
  33. opts = kFSPathMakeRefDoNotFollowLeafSymlink
  34. op_result = FSPathMakeRefWithOptions(path, opts, byref(fp), None)
  35. check_op_result(op_result)
  36. opts = kFSFileOperationDefaultOptions
  37. op_result = FSMoveObjectToTrashSync(byref(fp), None, opts)
  38. check_op_result(op_result)