Home | History | Annotate | Download | only in metrics
      1 // 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 
      7 #include <vector>
      8 
      9 #include "base/lazy_instance.h"
     10 #include "base/threading/thread_checker.h"
     11 
     12 namespace base {
     13 namespace {
     14 
     15 // A helper class for tracking callbacks and ensuring thread-safety.
     16 class Callbacks {
     17  public:
     18   Callbacks() {}
     19 
     20   // Records the |action|.
     21   void Record(const std::string& action) {
     22     DCHECK(thread_checker_.CalledOnValidThread());
     23     for (size_t i = 0; i < callbacks_.size(); ++i) {
     24       callbacks_[i].Run(action);
     25     }
     26   }
     27 
     28   // Adds |callback| to the list of |callbacks_|.
     29   void AddCallback(const ActionCallback& callback) {
     30     DCHECK(thread_checker_.CalledOnValidThread());
     31     callbacks_.push_back(callback);
     32   }
     33 
     34   // Removes the first instance of |callback| from the list of |callbacks_|, if
     35   // there is one.
     36   void RemoveCallback(const ActionCallback& callback) {
     37     DCHECK(thread_checker_.CalledOnValidThread());
     38     for (size_t i = 0; i < callbacks_.size(); ++i) {
     39       if (callbacks_[i].Equals(callback)) {
     40         callbacks_.erase(callbacks_.begin() + i);
     41         return;
     42       }
     43     }
     44   }
     45 
     46  private:
     47   base::ThreadChecker thread_checker_;
     48   std::vector<ActionCallback> callbacks_;
     49 
     50   DISALLOW_COPY_AND_ASSIGN(Callbacks);
     51 };
     52 
     53 base::LazyInstance<Callbacks> g_callbacks = LAZY_INSTANCE_INITIALIZER;
     54 
     55 }  // namespace
     56 
     57 void RecordAction(const UserMetricsAction& action) {
     58   g_callbacks.Get().Record(action.str_);
     59 }
     60 
     61 void RecordComputedAction(const std::string& action) {
     62   g_callbacks.Get().Record(action);
     63 }
     64 
     65 void AddActionCallback(const ActionCallback& callback) {
     66   g_callbacks.Get().AddCallback(callback);
     67 }
     68 
     69 void RemoveActionCallback(const ActionCallback& callback) {
     70   g_callbacks.Get().RemoveCallback(callback);
     71 
     72 }
     73 
     74 }  // namespace base
     75