1
0

Clipboard.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Clipboard.h
  3. * -----------
  4. * Purpose: RAII wrapper around operating system clipboard
  5. * Notes : (currently none)
  6. * Authors: OpenMPT Devs
  7. * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
  8. */
  9. #pragma once
  10. #include "openmpt/all/BuildSettings.hpp"
  11. class Clipboard
  12. {
  13. public:
  14. // Open clipboard for writing (size > 0) or reading (size == 0).
  15. Clipboard(UINT clipFormat, size_t size = 0)
  16. : m_clipFormat(clipFormat)
  17. {
  18. m_opened = theApp.GetMainWnd()->OpenClipboard() != FALSE;
  19. if(size > 0)
  20. {
  21. if(m_opened && (m_hCpy = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, size)) != nullptr)
  22. {
  23. ::EmptyClipboard();
  24. m_data = mpt::as_span(static_cast<std::byte *>(::GlobalLock(m_hCpy)), size);
  25. }
  26. } else
  27. {
  28. HGLOBAL hCpy = ::GetClipboardData(m_clipFormat);
  29. void *p = nullptr;
  30. if(hCpy != nullptr && (p = ::GlobalLock(hCpy)) != nullptr)
  31. {
  32. m_data = mpt::as_span(mpt::void_cast<std::byte *>(p), ::GlobalSize(hCpy));
  33. }
  34. }
  35. }
  36. bool IsValid() const
  37. {
  38. return m_opened && m_hCpy && m_data.data();
  39. }
  40. template<typename T>
  41. T *As()
  42. {
  43. return mpt::byte_cast<T*>(m_data.data());
  44. }
  45. mpt::byte_span Get()
  46. {
  47. return m_data;
  48. }
  49. std::string_view GetString() const
  50. {
  51. if(m_data.data())
  52. return { mpt::byte_cast<const char *>(m_data.data()), m_data.size() };
  53. else
  54. return {};
  55. }
  56. Clipboard operator =(mpt::const_byte_span data)
  57. {
  58. MPT_ASSERT(m_data.size() >= data.size());
  59. std::copy(data.begin(), data.end(), m_data.begin());
  60. return *this;
  61. }
  62. template <typename T>
  63. Clipboard operator =(const T &v)
  64. {
  65. mpt::const_byte_span data = mpt::as_raw_memory(v);
  66. MPT_ASSERT(m_data.size() >= data.size());
  67. std::copy(data.begin(), data.end(), m_data.begin());
  68. return *this;
  69. }
  70. void Close()
  71. {
  72. if(m_hCpy)
  73. {
  74. ::GlobalUnlock(m_hCpy);
  75. ::SetClipboardData(m_clipFormat, static_cast<HANDLE>(m_hCpy));
  76. m_hCpy = nullptr;
  77. }
  78. if(m_opened)
  79. {
  80. ::CloseClipboard();
  81. m_opened = false;
  82. }
  83. }
  84. ~Clipboard()
  85. {
  86. Close();
  87. }
  88. protected:
  89. HGLOBAL m_hCpy = nullptr;
  90. mpt::byte_span m_data;
  91. UINT m_clipFormat;
  92. bool m_opened = false;
  93. };