browser_action_drag_data.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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#include "chrome/browser/ui/views/extensions/browser_action_drag_data.h"
6
7#include "base/logging.h"
8#include "base/pickle.h"
9#include "base/strings/string_util.h"
10#include "chrome/browser/profiles/profile.h"
11#include "ui/base/clipboard/clipboard.h"
12
13const char* BrowserActionDragData::kClipboardFormatString =
14    "chromium/x-browser-actions";
15
16BrowserActionDragData::BrowserActionDragData()
17    : profile_(NULL), index_(static_cast<size_t>(-1)) {
18}
19
20BrowserActionDragData::BrowserActionDragData(
21    const std::string& id, int index)
22    : profile_(NULL), id_(id), index_(index) {
23}
24
25bool BrowserActionDragData::IsFromProfile(Profile* profile) const {
26  return profile_ == profile;
27}
28
29#if defined(TOOLKIT_VIEWS)
30void BrowserActionDragData::Write(
31    Profile* profile, ui::OSExchangeData* data) const {
32  DCHECK(data);
33  Pickle data_pickle;
34  WriteToPickle(profile, &data_pickle);
35  data->SetPickledData(GetBrowserActionCustomFormat(), data_pickle);
36}
37
38bool BrowserActionDragData::Read(const ui::OSExchangeData& data) {
39  if (!data.HasCustomFormat(GetBrowserActionCustomFormat()))
40    return false;
41
42  Pickle drag_data_pickle;
43  if (!data.GetPickledData(GetBrowserActionCustomFormat(), &drag_data_pickle))
44    return false;
45
46  if (!ReadFromPickle(&drag_data_pickle))
47    return false;
48
49  return true;
50}
51
52// static
53const ui::OSExchangeData::CustomFormat&
54BrowserActionDragData::GetBrowserActionCustomFormat() {
55  CR_DEFINE_STATIC_LOCAL(
56      ui::OSExchangeData::CustomFormat,
57      format,
58      (ui::Clipboard::GetFormatType(kClipboardFormatString)));
59
60  return format;
61}
62#endif
63
64void BrowserActionDragData::WriteToPickle(
65    Profile* profile, Pickle* pickle) const {
66  pickle->WriteBytes(&profile, sizeof(profile));
67  pickle->WriteString(id_);
68  pickle->WriteUInt64(index_);
69}
70
71bool BrowserActionDragData::ReadFromPickle(Pickle* pickle) {
72  PickleIterator data_iterator(*pickle);
73
74  const char* tmp;
75  if (!pickle->ReadBytes(&data_iterator, &tmp, sizeof(profile_)))
76    return false;
77  memcpy(&profile_, tmp, sizeof(profile_));
78
79  if (!pickle->ReadString(&data_iterator, &id_))
80    return false;
81
82  uint64 index;
83  if (!pickle->ReadUInt64(&data_iterator, &index))
84    return false;
85  index_ = static_cast<size_t>(index);
86
87  return true;
88}
89