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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
|
// Copyright 2013 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/profile_resetter/automatic_profile_resetter.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task_runner.h"
#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile_resetter/automatic_profile_resetter_delegate.h"
#include "chrome/browser/profile_resetter/jtl_interpreter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "components/variations/variations_associated_data.h"
#include "content/public/browser/browser_thread.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
// Helpers -------------------------------------------------------------------
namespace {
// Name constants for the field trial behind which we enable this feature.
const char kAutomaticProfileResetStudyName[] = "AutomaticProfileReset";
const char kAutomaticProfileResetStudyDryRunGroupName[] = "DryRun";
const char kAutomaticProfileResetStudyEnabledGroupName[] = "Enabled";
#if defined(GOOGLE_CHROME_BUILD)
const char kAutomaticProfileResetStudyProgramParameterName[] = "program";
const char kAutomaticProfileResetStudyHashSeedParameterName[] = "hash_seed";
#endif
// How long to wait after start-up before unleashing the evaluation flow.
const int64 kEvaluationFlowDelayInSeconds = 55;
// Keys used in the input dictionary of the program.
const char kDefaultSearchProviderKey[] = "default_search_provider";
const char kDefaultSearchProviderIsUserControlledKey[] =
"default_search_provider_iuc";
const char kLoadedModuleDigestsKey[] = "loaded_modules";
const char kLocalStateKey[] = "local_state";
const char kLocalStateIsUserControlledKey[] = "local_state_iuc";
const char kSearchProvidersKey[] = "search_providers";
const char kUserPreferencesKey[] = "preferences";
const char kUserPreferencesIsUserControlledKey[] = "preferences_iuc";
// Keys used in the output dictionary of the program.
const char kCombinedStatusMaskKeys[][26] = {
"combined_status_mask_bit1", "combined_status_mask_bit2",
"combined_status_mask_bit3", "combined_status_mask_bit4"};
const char kHadPromptedAlreadyKey[] = "had_prompted_already";
const char kSatisfiedCriteriaMaskKeys[][29] = {"satisfied_criteria_mask_bit1",
"satisfied_criteria_mask_bit2"};
// Keys used in both the input and output dictionary of the program.
const char kMementoValueInFileKey[] = "memento_value_in_file";
const char kMementoValueInLocalStateKey[] = "memento_value_in_local_state";
const char kMementoValueInPrefsKey[] = "memento_value_in_prefs";
// Number of bits, and maximum value (exclusive) for the mask whose bits
// indicate which of reset criteria were satisfied.
const size_t kSatisfiedCriteriaMaskNumberOfBits = 2u;
const uint32 kSatisfiedCriteriaMaskMaximumValue =
(1u << kSatisfiedCriteriaMaskNumberOfBits);
// Number of bits, and maximum value (exclusive) for the mask whose bits
// indicate if any of reset criteria were satisfied, and which of the mementos
// were already present.
const size_t kCombinedStatusMaskNumberOfBits = 4u;
const uint32 kCombinedStatusMaskMaximumValue =
(1u << kCombinedStatusMaskNumberOfBits);
COMPILE_ASSERT(
arraysize(kSatisfiedCriteriaMaskKeys) == kSatisfiedCriteriaMaskNumberOfBits,
satisfied_criteria_mask_bits_mismatch);
COMPILE_ASSERT(
arraysize(kCombinedStatusMaskKeys) == kCombinedStatusMaskNumberOfBits,
combined_status_mask_bits_mismatch);
// Enumeration of the possible outcomes of showing the profile reset prompt.
enum PromptResult {
// Prompt was not shown because only a dry-run was performed.
PROMPT_NOT_SHOWN,
PROMPT_ACTION_RESET,
PROMPT_ACTION_NO_RESET,
PROMPT_DISMISSED,
// Prompt was still shown (not dismissed by the user) when Chrome was closed.
PROMPT_IGNORED,
PROMPT_RESULT_MAX
};
// Returns whether or not a dry-run shall be performed.
bool ShouldPerformDryRun() {
return StartsWithASCII(
base::FieldTrialList::FindFullName(kAutomaticProfileResetStudyName),
kAutomaticProfileResetStudyDryRunGroupName, true);
}
// Returns whether or not a live-run shall be performed.
bool ShouldPerformLiveRun() {
return StartsWithASCII(
base::FieldTrialList::FindFullName(kAutomaticProfileResetStudyName),
kAutomaticProfileResetStudyEnabledGroupName, true);
}
// If the currently active experiment group prescribes a |program| and
// |hash_seed| to use instead of the baked-in ones, retrieves those and returns
// true. Otherwise, returns false.
bool GetProgramAndHashSeedOverridesFromExperiment(std::string* program,
std::string* hash_seed) {
DCHECK(program);
DCHECK(hash_seed);
#if defined(GOOGLE_CHROME_BUILD)
std::map<std::string, std::string> params;
chrome_variations::GetVariationParams(kAutomaticProfileResetStudyName,
¶ms);
if (params.count(kAutomaticProfileResetStudyProgramParameterName) &&
params.count(kAutomaticProfileResetStudyHashSeedParameterName)) {
program->swap(params[kAutomaticProfileResetStudyProgramParameterName]);
hash_seed->swap(params[kAutomaticProfileResetStudyHashSeedParameterName]);
return true;
}
#endif
return false;
}
// Takes |pref_name_to_value_map|, which shall be a deep-copy of all preferences
// in |source| without path expansion; and (1.) creates a sub-tree from it named
// |value_tree_key| in |target_dictionary| with path expansion, and (2.) also
// creates an isomorphic sub-tree under the key |is_user_controlled_tree_key|
// that contains only Boolean values indicating whether or not the corresponding
// preference is coming from the 'user' PrefStore.
void BuildSubTreesFromPreferences(
scoped_ptr<base::DictionaryValue> pref_name_to_value_map,
const PrefService* source,
const char* value_tree_key,
const char* is_user_controlled_tree_key,
base::DictionaryValue* target_dictionary) {
std::vector<std::string> pref_names;
pref_names.reserve(pref_name_to_value_map->size());
for (base::DictionaryValue::Iterator it(*pref_name_to_value_map);
!it.IsAtEnd(); it.Advance())
pref_names.push_back(it.key());
base::DictionaryValue* value_tree = new base::DictionaryValue;
base::DictionaryValue* is_user_controlled_tree = new base::DictionaryValue;
for (std::vector<std::string>::const_iterator it = pref_names.begin();
it != pref_names.end(); ++it) {
scoped_ptr<Value> pref_value_owned;
if (pref_name_to_value_map->RemoveWithoutPathExpansion(*it,
&pref_value_owned)) {
value_tree->Set(*it, pref_value_owned.release());
const PrefService::Preference* pref = source->FindPreference(it->c_str());
is_user_controlled_tree->Set(
*it, new base::FundamentalValue(pref->IsUserControlled()));
}
}
target_dictionary->Set(value_tree_key, value_tree);
target_dictionary->Set(is_user_controlled_tree_key, is_user_controlled_tree);
}
} // namespace
// AutomaticProfileResetter::InputBuilder ------------------------------------
// Collects all the information that is required by the evaluator program to
// assess whether or not the conditions for showing the reset prompt are met.
//
// This necessitates a lot of work that has to be performed on the UI thread,
// such as: accessing the Preferences, Local State, and TemplateURLService.
// In order to keep the browser responsive, the UI thread shall not be blocked
// for long consecutive periods of time. Unfortunately, we cannot reduce the
// total amount of work. Instead, what this class does is to split the work into
// shorter tasks that are posted one-at-a-time to the UI thread in a serial
// fashion, so as to give a chance to run other tasks that have accumulated in
// the meantime.
class AutomaticProfileResetter::InputBuilder
: public base::SupportsWeakPtr<InputBuilder> {
public:
typedef base::Callback<void(scoped_ptr<base::DictionaryValue>)>
ProgramInputCallback;
// The dependencies must have been initialized through |delegate|, i.e. the
// RequestCallback[...] methods must have already fired before calling this.
InputBuilder(Profile* profile, AutomaticProfileResetterDelegate* delegate)
: profile_(profile),
delegate_(delegate),
memento_in_prefs_(profile_),
memento_in_local_state_(profile_),
memento_in_file_(profile_) {}
~InputBuilder() {}
// Assembles the data required by the evaluator program into a dictionary
// format, and posts it back to the UI thread with |callback| once ready. In
// order not to block the UI thread for long consecutive periods of time, the
// work is divided into smaller tasks, see class comment above for details.
// It is safe to destroy |this| immediately from within the |callback|.
void BuildEvaluatorProgramInput(const ProgramInputCallback& callback) {
DCHECK(!data_);
DCHECK(!callback.is_null());
data_.reset(new base::DictionaryValue);
callback_ = callback;
AddAsyncTask(base::Bind(&InputBuilder::IncludeMementoValues, AsWeakPtr()));
AddTask(base::Bind(&InputBuilder::IncludeUserPreferences, AsWeakPtr()));
AddTask(base::Bind(&InputBuilder::IncludeLocalState, AsWeakPtr()));
AddTask(base::Bind(&InputBuilder::IncludeSearchEngines, AsWeakPtr()));
AddTask(base::Bind(&InputBuilder::IncludeLoadedModules, AsWeakPtr()));
// Each task will post the next one. Just trigger the chain reaction.
PostNextTask();
}
private:
// Asynchronous task that includes memento values (or empty strings in case
// mementos are not there).
void IncludeMementoValues() {
data_->SetString(kMementoValueInPrefsKey, memento_in_prefs_.ReadValue());
data_->SetString(kMementoValueInLocalStateKey,
memento_in_local_state_.ReadValue());
memento_in_file_.ReadValue(base::Bind(
&InputBuilder::IncludeFileBasedMementoCallback, AsWeakPtr()));
}
// Called back by |memento_in_file_| once the |memento_value| has been read.
void IncludeFileBasedMementoCallback(const std::string& memento_value) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
data_->SetString(kMementoValueInFileKey, memento_value);
// As an asynchronous task, we need to take care of posting the next task.
PostNextTask();
}
// Task that includes all user (i.e. profile-specific) preferences, along with
// information about whether the value is coming from the 'user' PrefStore.
// This is the most expensive operation, so it is itself split into two parts.
void IncludeUserPreferences() {
PrefService* prefs = profile_->GetPrefs();
DCHECK(prefs);
scoped_ptr<base::DictionaryValue> pref_name_to_value_map(
prefs->GetPreferenceValuesWithoutPathExpansion());
AddTask(base::Bind(&InputBuilder::IncludeUserPreferencesPartTwo,
AsWeakPtr(),
base::Passed(&pref_name_to_value_map)));
}
// Second part to above.
void IncludeUserPreferencesPartTwo(
scoped_ptr<base::DictionaryValue> pref_name_to_value_map) {
PrefService* prefs = profile_->GetPrefs();
DCHECK(prefs);
BuildSubTreesFromPreferences(
pref_name_to_value_map.Pass(),
prefs,
kUserPreferencesKey,
kUserPreferencesIsUserControlledKey,
data_.get());
}
// Task that includes all local state (i.e. shared) preferences, along with
// information about whether the value is coming from the 'user' PrefStore.
void IncludeLocalState() {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
scoped_ptr<base::DictionaryValue> pref_name_to_value_map(
local_state->GetPreferenceValuesWithoutPathExpansion());
BuildSubTreesFromPreferences(
pref_name_to_value_map.Pass(),
local_state,
kLocalStateKey,
kLocalStateIsUserControlledKey,
data_.get());
}
// Task that includes all information related to search engines.
void IncludeSearchEngines() {
scoped_ptr<base::DictionaryValue> default_search_provider_details(
delegate_->GetDefaultSearchProviderDetails());
data_->Set(kDefaultSearchProviderKey,
default_search_provider_details.release());
scoped_ptr<base::ListValue> search_providers_details(
delegate_->GetPrepopulatedSearchProvidersDetails());
data_->Set(kSearchProvidersKey, search_providers_details.release());
data_->SetBoolean(kDefaultSearchProviderIsUserControlledKey,
!delegate_->IsDefaultSearchProviderManaged());
}
// Task that includes information about loaded modules.
void IncludeLoadedModules() {
scoped_ptr<base::ListValue> loaded_module_digests(
delegate_->GetLoadedModuleNameDigests());
data_->Set(kLoadedModuleDigestsKey, loaded_module_digests.release());
}
// -------------------------------------------------------------------------
// Adds a |task| that can do as much asynchronous processing as it wants, but
// will need to finally call PostNextTask() on the UI thread when done.
void AddAsyncTask(const base::Closure& task) {
task_queue_.push(task);
}
// Convenience wrapper for synchronous tasks.
void SynchronousTaskWrapper(const base::Closure& task) {
base::ElapsedTimer timer;
task.Run();
UMA_HISTOGRAM_CUSTOM_TIMES(
"AutomaticProfileReset.InputBuilder.TaskDuration",
timer.Elapsed(),
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(2),
50);
PostNextTask();
}
// Adds a task that needs to finish synchronously. In exchange, PostNextTask()
// is called automatically when the |task| returns, and execution time is
// measured.
void AddTask(const base::Closure& task) {
task_queue_.push(
base::Bind(&InputBuilder::SynchronousTaskWrapper, AsWeakPtr(), task));
}
// Posts the next task from the |task_queue_|, unless it is exhausted, in
// which case it posts |callback_| to return with the results.
void PostNextTask() {
base::Closure next_task;
if (task_queue_.empty()) {
next_task = base::Bind(callback_, base::Passed(&data_));
} else {
next_task = task_queue_.front();
task_queue_.pop();
}
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE, next_task);
}
Profile* profile_;
AutomaticProfileResetterDelegate* delegate_;
ProgramInputCallback callback_;
PreferenceHostedPromptMemento memento_in_prefs_;
LocalStateHostedPromptMemento memento_in_local_state_;
FileHostedPromptMemento memento_in_file_;
scoped_ptr<base::DictionaryValue> data_;
std::queue<base::Closure> task_queue_;
DISALLOW_COPY_AND_ASSIGN(InputBuilder);
};
// AutomaticProfileResetter::EvaluationResults -------------------------------
// Encapsulates the output values extracted from the evaluator program.
struct AutomaticProfileResetter::EvaluationResults {
EvaluationResults()
: had_prompted_already(false),
satisfied_criteria_mask(0),
combined_status_mask(0) {}
std::string memento_value_in_prefs;
std::string memento_value_in_local_state;
std::string memento_value_in_file;
bool had_prompted_already;
uint32 satisfied_criteria_mask;
uint32 combined_status_mask;
};
// AutomaticProfileResetter --------------------------------------------------
AutomaticProfileResetter::AutomaticProfileResetter(Profile* profile)
: profile_(profile),
state_(STATE_UNINITIALIZED),
enumeration_of_loaded_modules_ready_(false),
template_url_service_ready_(false),
weak_ptr_factory_(this) {
DCHECK(profile_);
}
AutomaticProfileResetter::~AutomaticProfileResetter() {}
void AutomaticProfileResetter::Initialize() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK_EQ(state_, STATE_UNINITIALIZED);
if (!ShouldPerformDryRun() && !ShouldPerformLiveRun()) {
state_ = STATE_DISABLED;
return;
}
if (!GetProgramAndHashSeedOverridesFromExperiment(&program_, &hash_seed_)) {
ui::ResourceBundle& resources(ui::ResourceBundle::GetSharedInstance());
if (ShouldPerformLiveRun()) {
program_ = resources.GetRawDataResource(
IDR_AUTOMATIC_PROFILE_RESET_RULES).as_string();
hash_seed_ = resources.GetRawDataResource(
IDR_AUTOMATIC_PROFILE_RESET_HASH_SEED).as_string();
} else { // ShouldPerformDryRun()
program_ = resources.GetRawDataResource(
IDR_AUTOMATIC_PROFILE_RESET_RULES_DRY).as_string();
hash_seed_ = resources.GetRawDataResource(
IDR_AUTOMATIC_PROFILE_RESET_HASH_SEED_DRY).as_string();
}
}
delegate_.reset(new AutomaticProfileResetterDelegateImpl(
TemplateURLServiceFactory::GetForProfile(profile_)));
task_runner_for_waiting_ =
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::UI);
state_ = STATE_INITIALIZED;
}
void AutomaticProfileResetter::Activate() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK(state_ == STATE_INITIALIZED || state_ == STATE_DISABLED);
if (state_ == STATE_INITIALIZED) {
if (!program_.empty()) {
// Some steps in the flow (e.g. loaded modules, file-based memento) are
// IO-intensive, so defer execution until some time later.
task_runner_for_waiting_->PostDelayedTask(
FROM_HERE,
base::Bind(&AutomaticProfileResetter::PrepareEvaluationFlow,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromSeconds(kEvaluationFlowDelayInSeconds));
} else {
// Terminate early if there is no program included (nor set by tests).
state_ = STATE_DISABLED;
}
}
}
void AutomaticProfileResetter::SetProgramForTesting(
const std::string& program) {
program_ = program;
}
void AutomaticProfileResetter::SetHashSeedForTesting(
const std::string& hash_key) {
hash_seed_ = hash_key;
}
void AutomaticProfileResetter::SetDelegateForTesting(
scoped_ptr<AutomaticProfileResetterDelegate> delegate) {
delegate_ = delegate.Pass();
}
void AutomaticProfileResetter::SetTaskRunnerForWaitingForTesting(
const scoped_refptr<base::TaskRunner>& task_runner) {
task_runner_for_waiting_ = task_runner;
}
void AutomaticProfileResetter::PrepareEvaluationFlow() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK_EQ(state_, STATE_INITIALIZED);
state_ = STATE_WAITING_ON_DEPENDENCIES;
delegate_->RequestCallbackWhenTemplateURLServiceIsLoaded(
base::Bind(&AutomaticProfileResetter::OnTemplateURLServiceIsLoaded,
weak_ptr_factory_.GetWeakPtr()));
delegate_->RequestCallbackWhenLoadedModulesAreEnumerated(
base::Bind(&AutomaticProfileResetter::OnLoadedModulesAreEnumerated,
weak_ptr_factory_.GetWeakPtr()));
delegate_->LoadTemplateURLServiceIfNeeded();
delegate_->EnumerateLoadedModulesIfNeeded();
}
void AutomaticProfileResetter::OnTemplateURLServiceIsLoaded() {
template_url_service_ready_ = true;
OnDependencyIsReady();
}
void AutomaticProfileResetter::OnLoadedModulesAreEnumerated() {
enumeration_of_loaded_modules_ready_ = true;
OnDependencyIsReady();
}
void AutomaticProfileResetter::OnDependencyIsReady() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK_EQ(state_, STATE_WAITING_ON_DEPENDENCIES);
if (template_url_service_ready_ && enumeration_of_loaded_modules_ready_) {
state_ = STATE_READY;
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&AutomaticProfileResetter::BeginEvaluationFlow,
weak_ptr_factory_.GetWeakPtr()));
}
}
void AutomaticProfileResetter::BeginEvaluationFlow() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK_EQ(state_, STATE_READY);
DCHECK(!program_.empty());
DCHECK(!input_builder_);
state_ = STATE_WORKING;
input_builder_.reset(new InputBuilder(profile_, delegate_.get()));
input_builder_->BuildEvaluatorProgramInput(
base::Bind(&AutomaticProfileResetter::ContinueWithEvaluationFlow,
weak_ptr_factory_.GetWeakPtr()));
}
void AutomaticProfileResetter::ContinueWithEvaluationFlow(
scoped_ptr<base::DictionaryValue> program_input) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK_EQ(state_, STATE_WORKING);
input_builder_.reset();
base::SequencedWorkerPool* blocking_pool =
content::BrowserThread::GetBlockingPool();
scoped_refptr<base::TaskRunner> task_runner =
blocking_pool->GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
base::PostTaskAndReplyWithResult(
task_runner.get(),
FROM_HERE,
base::Bind(&EvaluateConditionsOnWorkerPoolThread,
hash_seed_,
program_,
base::Passed(&program_input)),
base::Bind(&AutomaticProfileResetter::FinishEvaluationFlow,
weak_ptr_factory_.GetWeakPtr()));
}
// static
scoped_ptr<AutomaticProfileResetter::EvaluationResults>
AutomaticProfileResetter::EvaluateConditionsOnWorkerPoolThread(
const std::string& hash_seed,
const std::string& program,
scoped_ptr<base::DictionaryValue> program_input) {
JtlInterpreter interpreter(hash_seed, program, program_input.get());
interpreter.Execute();
UMA_HISTOGRAM_ENUMERATION("AutomaticProfileReset.InterpreterResult",
interpreter.result(),
JtlInterpreter::RESULT_MAX);
// In each case below, the respective field in result originally contains the
// default, so if the getter fails, we still have the correct value there.
scoped_ptr<EvaluationResults> results(new EvaluationResults);
interpreter.GetOutputBoolean(kHadPromptedAlreadyKey,
&results->had_prompted_already);
interpreter.GetOutputString(kMementoValueInPrefsKey,
&results->memento_value_in_prefs);
interpreter.GetOutputString(kMementoValueInLocalStateKey,
&results->memento_value_in_local_state);
interpreter.GetOutputString(kMementoValueInFileKey,
&results->memento_value_in_file);
for (size_t i = 0; i < arraysize(kCombinedStatusMaskKeys); ++i) {
bool flag = false;
if (interpreter.GetOutputBoolean(kCombinedStatusMaskKeys[i], &flag) && flag)
results->combined_status_mask |= (1 << i);
}
for (size_t i = 0; i < arraysize(kSatisfiedCriteriaMaskKeys); ++i) {
bool flag = false;
if (interpreter.GetOutputBoolean(kSatisfiedCriteriaMaskKeys[i], &flag) &&
flag)
results->satisfied_criteria_mask |= (1 << i);
}
return results.Pass();
}
void AutomaticProfileResetter::FinishEvaluationFlow(
scoped_ptr<EvaluationResults> results) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK_EQ(state_, STATE_WORKING);
ReportStatistics(results->satisfied_criteria_mask,
results->combined_status_mask);
if (results->satisfied_criteria_mask != 0 && !results->had_prompted_already) {
PreferenceHostedPromptMemento memento_in_prefs(profile_);
LocalStateHostedPromptMemento memento_in_local_state(profile_);
FileHostedPromptMemento memento_in_file(profile_);
memento_in_prefs.StoreValue(results->memento_value_in_prefs);
memento_in_local_state.StoreValue(results->memento_value_in_local_state);
memento_in_file.StoreValue(results->memento_value_in_file);
if (ShouldPerformLiveRun()) {
delegate_->ShowPrompt();
} else {
UMA_HISTOGRAM_ENUMERATION("AutomaticProfileReset.PromptResult",
PROMPT_NOT_SHOWN,
PROMPT_RESULT_MAX);
}
}
state_ = STATE_DONE;
}
void AutomaticProfileResetter::ReportStatistics(uint32 satisfied_criteria_mask,
uint32 combined_status_mask) {
UMA_HISTOGRAM_ENUMERATION("AutomaticProfileReset.SatisfiedCriteriaMask",
satisfied_criteria_mask,
kSatisfiedCriteriaMaskMaximumValue);
UMA_HISTOGRAM_ENUMERATION("AutomaticProfileReset.CombinedStatusMask",
combined_status_mask,
kCombinedStatusMaskMaximumValue);
}
void AutomaticProfileResetter::Shutdown() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
state_ = STATE_DISABLED;
delegate_.reset();
weak_ptr_factory_.InvalidateWeakPtrs();
}
|