summaryrefslogtreecommitdiffstats
path: root/chrome/browser/sync/glue/preference_change_processor.cc
blob: c04997fa92f7e46eb0cb09a95113fbdcb395e7b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/sync/glue/preference_change_processor.h"

#include <set>
#include <string>

#include "base/auto_reset.h"
#include "base/json/json_reader.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/glue/preference_model_associator.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/protocol/preference_specifics.pb.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/pref_names.h"
#include "content/browser/browser_thread.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"

namespace browser_sync {

PreferenceChangeProcessor::PreferenceChangeProcessor(
    PreferenceModelAssociator* model_associator,
    UnrecoverableErrorHandler* error_handler)
    : ChangeProcessor(error_handler),
      pref_service_(NULL),
      model_associator_(model_associator),
      processing_pref_change_(false) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(model_associator);
  DCHECK(error_handler);
}

PreferenceChangeProcessor::~PreferenceChangeProcessor() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

void PreferenceChangeProcessor::Observe(NotificationType type,
                                        const NotificationSource& source,
                                        const NotificationDetails& details) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(running());
  DCHECK(NotificationType::PREF_CHANGED == type);
  DCHECK_EQ(pref_service_, Source<PrefService>(source).ptr());

  // Avoid recursion.
  if (processing_pref_change_)
    return;

  AutoReset<bool> guard(&processing_pref_change_, true);
  std::string* name = Details<std::string>(details).ptr();
  const PrefService::Preference* preference =
      pref_service_->FindPreference((*name).c_str());
  DCHECK(preference);
  int64 sync_id = model_associator_->GetSyncIdFromChromeId(*name);
  bool user_modifiable = preference->IsUserModifiable();
  if (!user_modifiable) {
    // We do not track preferences the user cannot change.
    model_associator_->Disassociate(sync_id);
    return;
  }

  sync_api::WriteTransaction trans(share_handle());
  sync_api::WriteNode node(&trans);

  // Since we don't create sync nodes for preferences that are not under control
  // of the user or still have their default value, this changed preference may
  // not have a sync node yet. If so, we create a node. Similarly, a preference
  // may become user-modifiable (e.g. due to laxer policy configuration), in
  // which case we also need to create a sync node and associate it.
  if (sync_api::kInvalidId == sync_id) {
    sync_api::ReadNode root(&trans);
    if (!root.InitByTagLookup(browser_sync::kPreferencesTag)) {
      error_handler()->OnUnrecoverableError(FROM_HERE, "Can't find root.");
      return;
    }

    // InitPrefNodeAndAssociate takes care of writing the value to the sync
    // node if appropriate.
    if (!model_associator_->InitPrefNodeAndAssociate(&trans,
                                                     root,
                                                     preference)) {
      error_handler()->OnUnrecoverableError(FROM_HERE,
                                            "Can't create sync node.");
    }
    return;
  }

  if (!node.InitByIdLookup(sync_id)) {
    error_handler()->OnUnrecoverableError(FROM_HERE,
                                          "Preference node lookup failed.");
    return;
  }

  if (!PreferenceModelAssociator::WritePreferenceToNode(
          preference->name(),
          *preference->GetValue(),
          &node)) {
    error_handler()->OnUnrecoverableError(FROM_HERE,
                                          "Failed to update preference node.");
    return;
  }
}

void PreferenceChangeProcessor::ApplyChangesFromSyncModel(
    const sync_api::BaseTransaction* trans,
    const sync_api::SyncManager::ChangeRecord* changes,
    int change_count) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!running())
    return;
  StopObserving();

  for (int i = 0; i < change_count; ++i) {
    sync_api::ReadNode node(trans);
    // TODO(ncarter): Can't look up the name for deletions: lookup of
    // deleted items fails at the syncapi layer.  However, the node should
    // generally still exist in the syncable database; we just need to
    // plumb the syncapi so that it succeeds.
    if (sync_api::SyncManager::ChangeRecord::ACTION_DELETE ==
        changes[i].action) {
      // Until the above is fixed, we have no choice but to ignore deletions.
      LOG(ERROR) << "No way to handle pref deletion";
      continue;
    }

    if (!node.InitByIdLookup(changes[i].id)) {
      error_handler()->OnUnrecoverableError(FROM_HERE,
                                            "Preference node lookup failed.");
      return;
    }
    DCHECK(syncable::PREFERENCES == node.GetModelType());

    std::string name;
    scoped_ptr<Value> value(ReadPreference(&node, &name));
    // Skip values we can't deserialize.
    if (!value.get())
      continue;

    // It is possible that we may receive a change to a preference we
    // do not want to sync.  For example if the user is syncing a Mac
    // client and a Windows client, the Windows client does not
    // support kShowPageOptionsButtons.  Ignore updates from these
    // preferences.
    const char* pref_name = name.c_str();
    if (model_associator_->synced_preferences().count(pref_name) == 0)
      continue;

    // Don't try to overwrite preferences not controllable by the user.
    const PrefService::Preference* pref =
        pref_service_->FindPreference(pref_name);
    DCHECK(pref);
    if (!pref->IsUserModifiable())
      continue;

    if (sync_api::SyncManager::ChangeRecord::ACTION_DELETE ==
        changes[i].action) {
      pref_service_->ClearPref(pref_name);
    } else {
      pref_service_->Set(pref_name, *value);

      // If this is a newly added node, associate.
      if (sync_api::SyncManager::ChangeRecord::ACTION_ADD ==
          changes[i].action) {
        const PrefService::Preference* preference =
            pref_service_->FindPreference(name.c_str());
        model_associator_->Associate(preference, changes[i].id);
      }

      model_associator_->AfterUpdateOperations(name);
    }
  }
  StartObserving();
}

Value* PreferenceChangeProcessor::ReadPreference(
    sync_api::ReadNode* node,
    std::string* name) {
  const sync_pb::PreferenceSpecifics& preference(
      node->GetPreferenceSpecifics());
  base::JSONReader reader;
  scoped_ptr<Value> value(reader.JsonToValue(preference.value(), false, false));
  if (!value.get()) {
    std::string err = "Failed to deserialize preference value: " +
        reader.GetErrorMessage();
    error_handler()->OnUnrecoverableError(FROM_HERE, err);
    return NULL;
  }
  *name = preference.name();
  return value.release();
}

void PreferenceChangeProcessor::StartImpl(Profile* profile) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  pref_service_ = profile->GetPrefs();
  registrar_.Init(pref_service_);
  StartObserving();
}

void PreferenceChangeProcessor::StopImpl() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  StopObserving();
  pref_service_ = NULL;
}


void PreferenceChangeProcessor::StartObserving() {
  DCHECK(pref_service_);
  for (std::set<std::string>::const_iterator it =
      model_associator_->synced_preferences().begin();
      it != model_associator_->synced_preferences().end(); ++it) {
    registrar_.Add((*it).c_str(), this);
  }
}

void PreferenceChangeProcessor::StopObserving() {
  DCHECK(pref_service_);
  for (std::set<std::string>::const_iterator it =
      model_associator_->synced_preferences().begin();
      it != model_associator_->synced_preferences().end(); ++it) {
    registrar_.Remove((*it).c_str(), this);
  }
}

}  // namespace browser_sync