blob: 169a0634e406f6b8c317b7a4fd5b9b9c41db6d8b [file] [log] [blame]
[email protected]e6e30ac2014-01-13 21:24:391// Copyright 2014 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 "base/metrics/user_metrics.h"
6
avi9b6f42932015-12-26 22:15:147#include <stddef.h>
8
[email protected]e6e30ac2014-01-13 21:24:399#include <vector>
10
beaudoind5c435e2016-04-22 14:17:1011#include "base/bind.h"
[email protected]e6e30ac2014-01-13 21:24:3912#include "base/lazy_instance.h"
beaudoind5c435e2016-04-22 14:17:1013#include "base/location.h"
avi9b6f42932015-12-26 22:15:1414#include "base/macros.h"
[email protected]abca0982014-04-10 01:12:3615#include "base/threading/thread_checker.h"
[email protected]e6e30ac2014-01-13 21:24:3916
17namespace base {
18namespace {
19
beaudoind5c435e2016-04-22 14:17:1020LazyInstance<std::vector<ActionCallback>> g_callbacks =
21 LAZY_INSTANCE_INITIALIZER;
22LazyInstance<scoped_refptr<SingleThreadTaskRunner>> g_task_runner =
23 LAZY_INSTANCE_INITIALIZER;
[email protected]e6e30ac2014-01-13 21:24:3924
25} // namespace
26
27void RecordAction(const UserMetricsAction& action) {
beaudoind5c435e2016-04-22 14:17:1028 RecordComputedAction(action.str_);
[email protected]e6e30ac2014-01-13 21:24:3929}
30
31void RecordComputedAction(const std::string& action) {
beaudoind5c435e2016-04-22 14:17:1032 if (!g_task_runner.Get()) {
33 DCHECK(g_callbacks.Get().empty());
34 return;
35 }
36
37 if (!g_task_runner.Get()->BelongsToCurrentThread()) {
38 g_task_runner.Get()->PostTask(FROM_HERE,
39 Bind(&RecordComputedAction, action));
40 return;
41 }
42
43 for (const ActionCallback& callback : g_callbacks.Get()) {
44 callback.Run(action);
45 }
[email protected]e6e30ac2014-01-13 21:24:3946}
47
48void AddActionCallback(const ActionCallback& callback) {
beaudoind5c435e2016-04-22 14:17:1049 // Only allow adding a callback if the task runner is set.
50 DCHECK(g_task_runner.Get());
51 DCHECK(g_task_runner.Get()->BelongsToCurrentThread());
52 g_callbacks.Get().push_back(callback);
[email protected]e6e30ac2014-01-13 21:24:3953}
54
55void RemoveActionCallback(const ActionCallback& callback) {
beaudoind5c435e2016-04-22 14:17:1056 DCHECK(g_task_runner.Get());
57 DCHECK(g_task_runner.Get()->BelongsToCurrentThread());
58 std::vector<ActionCallback>* callbacks = g_callbacks.Pointer();
59 for (size_t i = 0; i < callbacks->size(); ++i) {
60 if ((*callbacks)[i].Equals(callback)) {
61 callbacks->erase(callbacks->begin() + i);
62 return;
63 }
64 }
65}
[email protected]abca0982014-04-10 01:12:3666
beaudoind5c435e2016-04-22 14:17:1067void SetRecordActionTaskRunner(
68 scoped_refptr<SingleThreadTaskRunner> task_runner) {
69 DCHECK(task_runner->BelongsToCurrentThread());
70 DCHECK(!g_task_runner.Get() || g_task_runner.Get()->BelongsToCurrentThread());
71 g_task_runner.Get() = task_runner;
[email protected]e6e30ac2014-01-13 21:24:3972}
73
74} // namespace base