Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / remoting / host / clipboard_win.cc
blob956cb3f53e327c718b7721bb40c7a822df3dbb26
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.
5 #include "remoting/host/clipboard.h"
7 #include <windows.h>
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/logging.h"
12 #include "base/strings/string16.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/threading/platform_thread.h"
15 #include "base/win/message_window.h"
16 #include "base/win/scoped_hglobal.h"
17 #include "base/win/windows_version.h"
18 #include "remoting/base/constants.h"
19 #include "remoting/base/util.h"
20 #include "remoting/proto/event.pb.h"
21 #include "remoting/protocol/clipboard_stub.h"
23 namespace {
25 // A scoper class that opens and closes the clipboard.
26 // This class was adapted from the ScopedClipboard class in
27 // ui/base/clipboard/clipboard_win.cc.
28 class ScopedClipboard {
29 public:
30 ScopedClipboard() : opened_(false) {
33 ~ScopedClipboard() {
34 if (opened_) {
35 // CloseClipboard() must be called with anonymous access token. See
36 // crbug.com/441834 .
37 BOOL result = ::ImpersonateAnonymousToken(::GetCurrentThread());
38 CHECK(result);
39 ::CloseClipboard();
40 result = ::RevertToSelf();
41 CHECK(result);
45 bool Init(HWND owner) {
46 const int kMaxAttemptsToOpenClipboard = 5;
47 const base::TimeDelta kSleepTimeBetweenAttempts =
48 base::TimeDelta::FromMilliseconds(5);
50 if (opened_) {
51 NOTREACHED();
52 return true;
55 // This code runs on the UI thread, so we can block only very briefly.
56 for (int attempt = 0; attempt < kMaxAttemptsToOpenClipboard; ++attempt) {
57 if (attempt > 0) {
58 base::PlatformThread::Sleep(kSleepTimeBetweenAttempts);
60 if (::OpenClipboard(owner)) {
61 opened_ = true;
62 return true;
65 return false;
68 BOOL Empty() {
69 if (!opened_) {
70 NOTREACHED();
71 return false;
73 return ::EmptyClipboard();
76 void SetData(UINT uFormat, HANDLE hMem) {
77 if (!opened_) {
78 NOTREACHED();
79 return;
81 // The caller must not close the handle that ::SetClipboardData returns.
82 ::SetClipboardData(uFormat, hMem);
85 // The caller must not free the handle. The caller should lock the handle,
86 // copy the clipboard data, and unlock the handle. All this must be done
87 // before this ScopedClipboard is destroyed.
88 HANDLE GetData(UINT format) {
89 if (!opened_) {
90 NOTREACHED();
91 return nullptr;
93 return ::GetClipboardData(format);
96 private:
97 bool opened_;
100 typedef BOOL (WINAPI AddClipboardFormatListenerFn)(HWND);
101 typedef BOOL (WINAPI RemoveClipboardFormatListenerFn)(HWND);
103 } // namespace
105 namespace remoting {
107 class ClipboardWin : public Clipboard {
108 public:
109 ClipboardWin();
110 ~ClipboardWin() override;
112 void Start(
113 scoped_ptr<protocol::ClipboardStub> client_clipboard) override;
114 void InjectClipboardEvent(
115 const protocol::ClipboardEvent& event) override;
117 private:
118 void OnClipboardUpdate();
120 // Handles messages received by |window_|.
121 bool HandleMessage(UINT message,
122 WPARAM wparam,
123 LPARAM lparam,
124 LRESULT* result);
126 scoped_ptr<protocol::ClipboardStub> client_clipboard_;
127 AddClipboardFormatListenerFn* add_clipboard_format_listener_;
128 RemoveClipboardFormatListenerFn* remove_clipboard_format_listener_;
130 // Used to subscribe to WM_CLIPBOARDUPDATE messages.
131 scoped_ptr<base::win::MessageWindow> window_;
133 DISALLOW_COPY_AND_ASSIGN(ClipboardWin);
136 ClipboardWin::ClipboardWin()
137 : add_clipboard_format_listener_(nullptr),
138 remove_clipboard_format_listener_(nullptr) {
141 ClipboardWin::~ClipboardWin() {
142 if (window_ && remove_clipboard_format_listener_)
143 (*remove_clipboard_format_listener_)(window_->hwnd());
146 void ClipboardWin::Start(
147 scoped_ptr<protocol::ClipboardStub> client_clipboard) {
148 DCHECK(!add_clipboard_format_listener_);
149 DCHECK(!remove_clipboard_format_listener_);
150 DCHECK(!window_);
152 client_clipboard_.swap(client_clipboard);
154 // user32.dll is statically linked.
155 HMODULE user32 = GetModuleHandle(L"user32.dll");
156 CHECK(user32);
158 add_clipboard_format_listener_ =
159 reinterpret_cast<AddClipboardFormatListenerFn*>(
160 GetProcAddress(user32, "AddClipboardFormatListener"));
161 if (add_clipboard_format_listener_) {
162 remove_clipboard_format_listener_ =
163 reinterpret_cast<RemoveClipboardFormatListenerFn*>(
164 GetProcAddress(user32, "RemoveClipboardFormatListener"));
165 // If AddClipboardFormatListener() present, RemoveClipboardFormatListener()
166 // should be available too.
167 CHECK(remove_clipboard_format_listener_);
168 } else {
169 LOG(WARNING) << "AddClipboardFormatListener() is not available.";
172 window_.reset(new base::win::MessageWindow());
173 if (!window_->Create(base::Bind(&ClipboardWin::HandleMessage,
174 base::Unretained(this)))) {
175 LOG(ERROR) << "Couldn't create clipboard window.";
176 window_.reset();
177 return;
180 if (add_clipboard_format_listener_) {
181 if (!(*add_clipboard_format_listener_)(window_->hwnd())) {
182 LOG(WARNING) << "AddClipboardFormatListener() failed: " << GetLastError();
187 void ClipboardWin::InjectClipboardEvent(
188 const protocol::ClipboardEvent& event) {
189 if (!window_)
190 return;
192 // Currently we only handle UTF-8 text.
193 if (event.mime_type().compare(kMimeTypeTextUtf8) != 0)
194 return;
195 if (!StringIsUtf8(event.data().c_str(), event.data().length())) {
196 LOG(ERROR) << "ClipboardEvent: data is not UTF-8 encoded.";
197 return;
200 base::string16 text = base::UTF8ToUTF16(ReplaceLfByCrLf(event.data()));
202 ScopedClipboard clipboard;
203 if (!clipboard.Init(window_->hwnd())) {
204 LOG(WARNING) << "Couldn't open the clipboard.";
205 return;
208 clipboard.Empty();
210 HGLOBAL text_global =
211 ::GlobalAlloc(GMEM_MOVEABLE, (text.size() + 1) * sizeof(WCHAR));
212 if (!text_global) {
213 LOG(WARNING) << "Couldn't allocate global memory.";
214 return;
217 LPWSTR text_global_locked =
218 reinterpret_cast<LPWSTR>(::GlobalLock(text_global));
219 memcpy(text_global_locked, text.data(), text.size() * sizeof(WCHAR));
220 text_global_locked[text.size()] = (WCHAR)0;
221 ::GlobalUnlock(text_global);
223 clipboard.SetData(CF_UNICODETEXT, text_global);
226 void ClipboardWin::OnClipboardUpdate() {
227 DCHECK(window_);
229 if (::IsClipboardFormatAvailable(CF_UNICODETEXT)) {
230 base::string16 text;
231 // Add a scope, so that we keep the clipboard open for as short a time as
232 // possible.
234 ScopedClipboard clipboard;
235 if (!clipboard.Init(window_->hwnd())) {
236 LOG(WARNING) << "Couldn't open the clipboard." << GetLastError();
237 return;
240 HGLOBAL text_global = clipboard.GetData(CF_UNICODETEXT);
241 if (!text_global) {
242 LOG(WARNING) << "Couldn't get data from the clipboard: "
243 << GetLastError();
244 return;
247 base::win::ScopedHGlobal<WCHAR*> text_lock(text_global);
248 if (!text_lock.get()) {
249 LOG(WARNING) << "Couldn't lock clipboard data: " << GetLastError();
250 return;
252 text.assign(text_lock.get());
255 protocol::ClipboardEvent event;
256 event.set_mime_type(kMimeTypeTextUtf8);
257 event.set_data(ReplaceCrLfByLf(base::UTF16ToUTF8(text)));
259 if (client_clipboard_.get()) {
260 client_clipboard_->InjectClipboardEvent(event);
265 bool ClipboardWin::HandleMessage(
266 UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result) {
267 if (message == WM_CLIPBOARDUPDATE) {
268 OnClipboardUpdate();
269 *result = 0;
270 return true;
273 return false;
276 scoped_ptr<Clipboard> Clipboard::Create() {
277 return make_scoped_ptr(new ClipboardWin());
280 } // namespace remoting