clipboard_win.cc 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "remoting/host/clipboard.h"
  5. #include <windows.h>
  6. #include <memory>
  7. #include <string>
  8. #include "base/bind.h"
  9. #include "base/logging.h"
  10. #include "base/memory/ptr_util.h"
  11. #include "base/strings/string_util.h"
  12. #include "base/strings/utf_string_conversions.h"
  13. #include "base/threading/platform_thread.h"
  14. #include "base/win/message_window.h"
  15. #include "base/win/scoped_hglobal.h"
  16. #include "remoting/base/constants.h"
  17. #include "remoting/base/util.h"
  18. #include "remoting/proto/event.pb.h"
  19. #include "remoting/protocol/clipboard_stub.h"
  20. namespace {
  21. // A scoper class that opens and closes the clipboard.
  22. // This class was adapted from the ScopedClipboard class in
  23. // ui/base/clipboard/clipboard_win.cc.
  24. class ScopedClipboard {
  25. public:
  26. ScopedClipboard() : opened_(false) {
  27. }
  28. ~ScopedClipboard() {
  29. if (opened_) {
  30. // CloseClipboard() must be called with anonymous access token. See
  31. // crbug.com/441834 .
  32. BOOL result = ::ImpersonateAnonymousToken(::GetCurrentThread());
  33. CHECK(result);
  34. ::CloseClipboard();
  35. result = ::RevertToSelf();
  36. CHECK(result);
  37. }
  38. }
  39. bool Init(HWND owner) {
  40. const int kMaxAttemptsToOpenClipboard = 5;
  41. const base::TimeDelta kSleepTimeBetweenAttempts = base::Milliseconds(5);
  42. if (opened_) {
  43. NOTREACHED();
  44. return true;
  45. }
  46. // This code runs on the UI thread, so we can block only very briefly.
  47. for (int attempt = 0; attempt < kMaxAttemptsToOpenClipboard; ++attempt) {
  48. if (attempt > 0) {
  49. base::PlatformThread::Sleep(kSleepTimeBetweenAttempts);
  50. }
  51. if (::OpenClipboard(owner)) {
  52. opened_ = true;
  53. return true;
  54. }
  55. }
  56. return false;
  57. }
  58. BOOL Empty() {
  59. if (!opened_) {
  60. NOTREACHED();
  61. return false;
  62. }
  63. return ::EmptyClipboard();
  64. }
  65. void SetData(UINT uFormat, HANDLE hMem) {
  66. if (!opened_) {
  67. NOTREACHED();
  68. return;
  69. }
  70. // The caller must not close the handle that ::SetClipboardData returns.
  71. ::SetClipboardData(uFormat, hMem);
  72. }
  73. // The caller must not free the handle. The caller should lock the handle,
  74. // copy the clipboard data, and unlock the handle. All this must be done
  75. // before this ScopedClipboard is destroyed.
  76. HANDLE GetData(UINT format) {
  77. if (!opened_) {
  78. NOTREACHED();
  79. return nullptr;
  80. }
  81. return ::GetClipboardData(format);
  82. }
  83. private:
  84. bool opened_;
  85. };
  86. } // namespace
  87. namespace remoting {
  88. class ClipboardWin : public Clipboard {
  89. public:
  90. ClipboardWin();
  91. ClipboardWin(const ClipboardWin&) = delete;
  92. ClipboardWin& operator=(const ClipboardWin&) = delete;
  93. ~ClipboardWin() override;
  94. void Start(
  95. std::unique_ptr<protocol::ClipboardStub> client_clipboard) override;
  96. void InjectClipboardEvent(
  97. const protocol::ClipboardEvent& event) override;
  98. private:
  99. void OnClipboardUpdate();
  100. // Handles messages received by |window_|.
  101. bool HandleMessage(UINT message,
  102. WPARAM wparam,
  103. LPARAM lparam,
  104. LRESULT* result);
  105. std::unique_ptr<protocol::ClipboardStub> client_clipboard_;
  106. // Used to subscribe to WM_CLIPBOARDUPDATE messages.
  107. std::unique_ptr<base::win::MessageWindow> window_;
  108. };
  109. ClipboardWin::ClipboardWin() {}
  110. ClipboardWin::~ClipboardWin() {
  111. if (window_)
  112. ::RemoveClipboardFormatListener(window_->hwnd());
  113. }
  114. void ClipboardWin::Start(
  115. std::unique_ptr<protocol::ClipboardStub> client_clipboard) {
  116. DCHECK(!window_);
  117. client_clipboard_.swap(client_clipboard);
  118. window_ = std::make_unique<base::win::MessageWindow>();
  119. if (!window_->Create(base::BindRepeating(&ClipboardWin::HandleMessage,
  120. base::Unretained(this)))) {
  121. LOG(ERROR) << "Couldn't create clipboard window.";
  122. window_.reset();
  123. return;
  124. }
  125. if (!::AddClipboardFormatListener(window_->hwnd())) {
  126. LOG(WARNING) << "AddClipboardFormatListener() failed: " << GetLastError();
  127. }
  128. }
  129. void ClipboardWin::InjectClipboardEvent(
  130. const protocol::ClipboardEvent& event) {
  131. if (!window_)
  132. return;
  133. // Currently we only handle UTF-8 text.
  134. if (event.mime_type().compare(kMimeTypeTextUtf8) != 0)
  135. return;
  136. if (!base::IsStringUTF8AllowingNoncharacters(event.data())) {
  137. LOG(ERROR) << "ClipboardEvent: data is not UTF-8 encoded.";
  138. return;
  139. }
  140. std::u16string text = base::UTF8ToUTF16(ReplaceLfByCrLf(event.data()));
  141. ScopedClipboard clipboard;
  142. if (!clipboard.Init(window_->hwnd())) {
  143. LOG(WARNING) << "Couldn't open the clipboard.";
  144. return;
  145. }
  146. clipboard.Empty();
  147. HGLOBAL text_global =
  148. ::GlobalAlloc(GMEM_MOVEABLE, (text.size() + 1) * sizeof(WCHAR));
  149. if (!text_global) {
  150. LOG(WARNING) << "Couldn't allocate global memory.";
  151. return;
  152. }
  153. LPWSTR text_global_locked =
  154. reinterpret_cast<LPWSTR>(::GlobalLock(text_global));
  155. memcpy(text_global_locked, text.data(), text.size() * sizeof(WCHAR));
  156. text_global_locked[text.size()] = (WCHAR)0;
  157. ::GlobalUnlock(text_global);
  158. clipboard.SetData(CF_UNICODETEXT, text_global);
  159. }
  160. void ClipboardWin::OnClipboardUpdate() {
  161. DCHECK(window_);
  162. if (::IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  163. std::wstring text;
  164. // Add a scope, so that we keep the clipboard open for as short a time as
  165. // possible.
  166. {
  167. ScopedClipboard clipboard;
  168. if (!clipboard.Init(window_->hwnd())) {
  169. LOG(WARNING) << "Couldn't open the clipboard." << GetLastError();
  170. return;
  171. }
  172. HGLOBAL text_global = clipboard.GetData(CF_UNICODETEXT);
  173. if (!text_global) {
  174. LOG(WARNING) << "Couldn't get data from the clipboard: "
  175. << GetLastError();
  176. return;
  177. }
  178. base::win::ScopedHGlobal<WCHAR*> text_lock(text_global);
  179. if (!text_lock.get()) {
  180. LOG(WARNING) << "Couldn't lock clipboard data: " << GetLastError();
  181. return;
  182. }
  183. text.assign(text_lock.get());
  184. }
  185. protocol::ClipboardEvent event;
  186. event.set_mime_type(kMimeTypeTextUtf8);
  187. event.set_data(ReplaceCrLfByLf(base::WideToUTF8(text)));
  188. if (client_clipboard_.get()) {
  189. client_clipboard_->InjectClipboardEvent(event);
  190. }
  191. }
  192. }
  193. bool ClipboardWin::HandleMessage(
  194. UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result) {
  195. if (message == WM_CLIPBOARDUPDATE) {
  196. OnClipboardUpdate();
  197. *result = 0;
  198. return true;
  199. }
  200. return false;
  201. }
  202. std::unique_ptr<Clipboard> Clipboard::Create() {
  203. return base::WrapUnique(new ClipboardWin());
  204. }
  205. } // namespace remoting