• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
5 #ifndef UI_BASE_CLIPBOARD_CLIPBOARD_H_
6 #define UI_BASE_CLIPBOARD_CLIPBOARD_H_
7 
8 #include <map>
9 #include <string>
10 #include <vector>
11 
12 #include "base/compiler_specific.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/shared_memory.h"
16 #include "base/process/process.h"
17 #include "base/strings/string16.h"
18 #include "base/threading/platform_thread.h"
19 #include "base/threading/thread_checker.h"
20 #include "ui/base/clipboard/clipboard_types.h"
21 #include "ui/base/ui_export.h"
22 
23 #if defined(TOOLKIT_GTK)
24 #include <gdk/gdk.h>
25 #endif
26 
27 #if defined(OS_WIN)
28 #include <objidl.h>
29 #elif defined(OS_ANDROID)
30 #include <jni.h>
31 
32 #include "base/android/jni_android.h"
33 #include "base/android/scoped_java_ref.h"
34 #endif
35 
36 #if defined(USE_AURA) && defined(USE_X11)
37 #include "base/memory/scoped_ptr.h"
38 #endif
39 
40 namespace base {
41 class FilePath;
42 
43 namespace win {
44 class MessageWindow;
45 }  // namespace win
46 }  // namespace base
47 
48 namespace gfx {
49 class Size;
50 }
51 
52 class SkBitmap;
53 
54 #if defined(TOOLKIT_GTK)
55 typedef struct _GtkClipboard GtkClipboard;
56 #endif
57 
58 #ifdef __OBJC__
59 @class NSString;
60 #else
61 class NSString;
62 #endif
63 
64 namespace ui {
65 class ClipboardTest;
66 
NON_EXPORTED_BASE(public base::ThreadChecker)67 class UI_EXPORT Clipboard : NON_EXPORTED_BASE(public base::ThreadChecker) {
68  public:
69   // MIME type constants.
70   static const char kMimeTypeText[];
71   static const char kMimeTypeURIList[];
72   static const char kMimeTypeDownloadURL[];
73   static const char kMimeTypeHTML[];
74   static const char kMimeTypeRTF[];
75   static const char kMimeTypePNG[];
76 
77   // Platform neutral holder for native data representation of a clipboard type.
78   struct UI_EXPORT FormatType {
79     FormatType();
80     ~FormatType();
81 
82     // Serializes and deserializes a FormatType for use in IPC messages.
83     std::string Serialize() const;
84     static FormatType Deserialize(const std::string& serialization);
85 
86 #if defined(OS_WIN) || defined(USE_AURA)
87     // FormatType can be used in a set on some platforms.
88     bool operator<(const FormatType& other) const;
89 #endif
90 
91 #if defined(OS_WIN)
92     const FORMATETC& ToFormatEtc() const { return data_; }
93 #elif defined(OS_MACOSX)
94     // Custom copy and assignment constructor to handle NSString.
95     FormatType(const FormatType& other);
96     FormatType& operator=(const FormatType& other);
97 #elif defined(USE_AURA)
98     const std::string& ToString() const { return data_; }
99 #endif
100 
101    private:
102     friend class Clipboard;
103 
104     bool Equals(const FormatType& other) const;
105 
106     // Platform-specific glue used internally by the Clipboard class. Each
107     // plaform should define,at least one of each of the following:
108     // 1. A constructor that wraps that native clipboard format descriptor.
109     // 2. An accessor to retrieve the wrapped descriptor.
110     // 3. A data member to hold the wrapped descriptor.
111     //
112     // Note that in some cases, the accessor for the wrapped descriptor may be
113     // public, as these format types can be used by drag and drop code as well.
114 #if defined(OS_WIN)
115     explicit FormatType(UINT native_format);
116     FormatType(UINT native_format, LONG index);
117     UINT ToUINT() const { return data_.cfFormat; }
118     FORMATETC data_;
119 #elif defined(OS_MACOSX)
120     explicit FormatType(NSString* native_format);
121     NSString* ToNSString() const { return data_; }
122     NSString* data_;
123 #elif defined(USE_AURA)
124     explicit FormatType(const std::string& native_format);
125     std::string data_;
126 #elif defined(TOOLKIT_GTK)
127     explicit FormatType(const std::string& native_format);
128     explicit FormatType(const GdkAtom& native_format);
129     const GdkAtom& ToGdkAtom() const { return data_; }
130     GdkAtom data_;
131 #elif defined(OS_ANDROID)
132     explicit FormatType(const std::string& native_format);
133     const std::string& data() const { return data_; }
134     std::string data_;
135 #else
136 #error No FormatType definition.
137 #endif
138 
139     // Copyable and assignable, since this is essentially an opaque value type.
140   };
141 
142   // ObjectType designates the type of data to be stored in the clipboard. This
143   // designation is shared across all OSes. The system-specific designation
144   // is defined by FormatType. A single ObjectType might be represented by
145   // several system-specific FormatTypes. For example, on Linux the CBF_TEXT
146   // ObjectType maps to "text/plain", "STRING", and several other formats. On
147   // windows it maps to CF_UNICODETEXT.
148   enum ObjectType {
149     CBF_TEXT,
150     CBF_HTML,
151     CBF_RTF,
152     CBF_BOOKMARK,
153     CBF_WEBKIT,
154     CBF_SMBITMAP,  // Bitmap from shared memory.
155     CBF_DATA,  // Arbitrary block of bytes.
156   };
157 
158   // ObjectMap is a map from ObjectType to associated data.
159   // The data is organized differently for each ObjectType. The following
160   // table summarizes what kind of data is stored for each key.
161   // * indicates an optional argument.
162   //
163   // Key           Arguments    Type
164   // -------------------------------------
165   // CBF_TEXT      text         char array
166   // CBF_HTML      html         char array
167   //               url*         char array
168   // CBF_RTF       data         byte array
169   // CBF_BOOKMARK  html         char array
170   //               url          char array
171   // CBF_WEBKIT    none         empty vector
172   // CBF_SMBITMAP  shared_mem   A pointer to an unmapped base::SharedMemory
173   //                            object containing the bitmap data. The bitmap
174   //                            data should be premultiplied.
175   //               size         gfx::Size struct
176   // CBF_DATA      format       char array
177   //               data         byte array
178   typedef std::vector<char> ObjectMapParam;
179   typedef std::vector<ObjectMapParam> ObjectMapParams;
180   typedef std::map<int /* ObjectType */, ObjectMapParams> ObjectMap;
181 
182   static bool IsSupportedClipboardType(int32 type) {
183     switch (type) {
184       case CLIPBOARD_TYPE_COPY_PASTE:
185         return true;
186 #if defined(USE_X11) && !defined(OS_CHROMEOS)
187       case CLIPBOARD_TYPE_SELECTION:
188         return true;
189 #endif
190     }
191     return false;
192   }
193 
194   static ClipboardType FromInt(int32 type) {
195     return static_cast<ClipboardType>(type);
196   }
197 
198   // Sets the list of threads that are allowed to access the clipboard.
199   static void SetAllowedThreads(
200       const std::vector<base::PlatformThreadId>& allowed_threads);
201 
202   // Returns the clipboard object for the current thread.
203   //
204   // Most implementations will have at most one clipboard which will live on
205   // the main UI thread, but Windows has tricky semantics where there have to
206   // be two clipboards: one that lives on the UI thread and one that lives on
207   // the IO thread.
208   static Clipboard* GetForCurrentThread();
209 
210   // Destroys the clipboard for the current thread. Usually, this will clean up
211   // all clipboards, except on Windows. (Previous code leaks the IO thread
212   // clipboard, so it shouldn't be a problem.)
213   static void DestroyClipboardForCurrentThread();
214 
215   // Write a bunch of objects to the system clipboard. Copies are made of the
216   // contents of |objects|.
217   // Note: If you're thinking about calling this, you should probably be using
218   // ScopedClipboardWriter instead.
219   void WriteObjects(ClipboardType type, const ObjectMap& objects);
220 
221   // Returns a sequence number which uniquely identifies clipboard state.
222   // This can be used to version the data on the clipboard and determine
223   // whether it has changed.
224   uint64 GetSequenceNumber(ClipboardType type);
225 
226   // Tests whether the clipboard contains a certain format
227   bool IsFormatAvailable(const FormatType& format, ClipboardType type) const;
228 
229   // Clear the clipboard data.
230   void Clear(ClipboardType type);
231 
232   void ReadAvailableTypes(ClipboardType type,
233                           std::vector<base::string16>* types,
234                           bool* contains_filenames) const;
235 
236   // Reads UNICODE text from the clipboard, if available.
237   void ReadText(ClipboardType type, base::string16* result) const;
238 
239   // Reads ASCII text from the clipboard, if available.
240   void ReadAsciiText(ClipboardType type, std::string* result) const;
241 
242   // Reads HTML from the clipboard, if available. If the HTML fragment requires
243   // context to parse, |fragment_start| and |fragment_end| are indexes into
244   // markup indicating the beginning and end of the actual fragment. Otherwise,
245   // they will contain 0 and markup->size().
246   void ReadHTML(ClipboardType type,
247                 base::string16* markup,
248                 std::string* src_url,
249                 uint32* fragment_start,
250                 uint32* fragment_end) const;
251 
252   // Reads RTF from the clipboard, if available. Stores the result as a byte
253   // vector.
254   void ReadRTF(ClipboardType type, std::string* result) const;
255 
256   // Reads an image from the clipboard, if available.
257   SkBitmap ReadImage(ClipboardType type) const;
258 
259   void ReadCustomData(ClipboardType clipboard_type,
260                       const base::string16& type,
261                       base::string16* result) const;
262 
263   // Reads a bookmark from the clipboard, if available.
264   void ReadBookmark(base::string16* title, std::string* url) const;
265 
266   // Reads raw data from the clipboard with the given format type. Stores result
267   // as a byte vector.
268   void ReadData(const FormatType& format, std::string* result) const;
269 
270   // Gets the FormatType corresponding to an arbitrary format string,
271   // registering it with the system if needed. Due to Windows/Linux
272   // limitiations, |format_string| must never be controlled by the user.
273   static FormatType GetFormatType(const std::string& format_string);
274 
275   // Get format identifiers for various types.
276   static const FormatType& GetUrlFormatType();
277   static const FormatType& GetUrlWFormatType();
278   static const FormatType& GetMozUrlFormatType();
279   static const FormatType& GetPlainTextFormatType();
280   static const FormatType& GetPlainTextWFormatType();
281   static const FormatType& GetFilenameFormatType();
282   static const FormatType& GetFilenameWFormatType();
283   static const FormatType& GetWebKitSmartPasteFormatType();
284   // Win: MS HTML Format, Other: Generic HTML format
285   static const FormatType& GetHtmlFormatType();
286   static const FormatType& GetRtfFormatType();
287   static const FormatType& GetBitmapFormatType();
288   // TODO(raymes): Unify web custom data and pepper custom data:
289   // crbug.com/158399.
290   static const FormatType& GetWebCustomDataFormatType();
291   static const FormatType& GetPepperCustomDataFormatType();
292 
293   // Embeds a pointer to a SharedMemory object pointed to by |bitmap_handle|
294   // belonging to |process| into a shared bitmap [CBF_SMBITMAP] slot in
295   // |objects|.  The pointer is deleted by DispatchObjects().
296   //
297   // On non-Windows platforms, |process| is ignored.
298   static bool ReplaceSharedMemHandle(ObjectMap* objects,
299                                      base::SharedMemoryHandle bitmap_handle,
300                                      base::ProcessHandle process)
301       WARN_UNUSED_RESULT;
302 #if defined(OS_WIN)
303   // Firefox text/html
304   static const FormatType& GetTextHtmlFormatType();
305   static const FormatType& GetCFHDropFormatType();
306   static const FormatType& GetFileDescriptorFormatType();
307   static const FormatType& GetFileContentZeroFormatType();
308   static const FormatType& GetIDListFormatType();
309 #endif
310 
311  private:
312   FRIEND_TEST_ALL_PREFIXES(ClipboardTest, SharedBitmapTest);
313   FRIEND_TEST_ALL_PREFIXES(ClipboardTest, EmptyHTMLTest);
314   friend class ClipboardTest;
315 
316   Clipboard();
317   ~Clipboard();
318 
319   void DispatchObject(ObjectType type, const ObjectMapParams& params);
320 
321   void WriteText(const char* text_data, size_t text_len);
322 
323   void WriteHTML(const char* markup_data,
324                  size_t markup_len,
325                  const char* url_data,
326                  size_t url_len);
327 
328   void WriteRTF(const char* rtf_data, size_t data_len);
329 
330   void WriteBookmark(const char* title_data,
331                      size_t title_len,
332                      const char* url_data,
333                      size_t url_len);
334 
335   void WriteWebSmartPaste();
336 
337   void WriteBitmap(const SkBitmap& bitmap);
338 
339   void WriteData(const FormatType& format,
340                  const char* data_data,
341                  size_t data_len);
342 #if defined(OS_WIN)
343   void WriteBitmapFromHandle(HBITMAP source_hbitmap,
344                              const gfx::Size& size);
345 
346   // Safely write to system clipboard. Free |handle| on failure.
347   void WriteToClipboard(unsigned int format, HANDLE handle);
348 
349   static void ParseBookmarkClipboardFormat(const base::string16& bookmark,
350                                            base::string16* title,
351                                            std::string* url);
352 
353   // Free a handle depending on its type (as intuited from format)
354   static void FreeData(unsigned int format, HANDLE data);
355 
356   // Return the window that should be the clipboard owner, creating it
357   // if neccessary.  Marked const for lazily initialization by const methods.
358   HWND GetClipboardWindow() const;
359 
360   // Mark this as mutable so const methods can still do lazy initialization.
361   mutable scoped_ptr<base::win::MessageWindow> clipboard_owner_;
362 
363 #elif defined(TOOLKIT_GTK)
364   // The public API is via WriteObjects() which dispatches to multiple
365   // Write*() calls, but on GTK we must write all the clipboard types
366   // in a single GTK call.  To support this we store the current set
367   // of data we intend to put on the clipboard on clipboard_data_ as
368   // WriteObjects is running, and then at the end call SetGtkClipboard
369   // which replaces whatever is on the system clipboard with the
370   // contents of clipboard_data_.
371 
372  public:
373   typedef std::map<std::string, std::pair<char*, size_t> > TargetMap;
374 
375  private:
376   // Write changes to gtk clipboard.
377   void SetGtkClipboard(ClipboardType type);
378   // Insert a mapping into clipboard_data_.
379   void InsertMapping(const char* key, char* data, size_t data_len);
380 
381   // Find the gtk clipboard for the passed type enum.
382   GtkClipboard* LookupBackingClipboard(ClipboardType type) const;
383 
384   TargetMap* clipboard_data_;
385   GtkClipboard* clipboard_;
386   GtkClipboard* primary_selection_;
387 #elif defined(USE_CLIPBOARD_AURAX11)
388  private:
389   // We keep our implementation details private because otherwise we bring in
390   // the X11 headers and break chrome compile.
391   class AuraX11Details;
392   scoped_ptr<AuraX11Details> aurax11_details_;
393 #endif
394 
395   DISALLOW_COPY_AND_ASSIGN(Clipboard);
396 };
397 
398 }  // namespace ui
399 
400 #endif  // UI_BASE_CLIPBOARD_CLIPBOARD_H_
401