OLD | NEW |
| (Empty) |
1 // Copyright 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 "webkit/common/user_agent/user_agent.h" | |
6 | |
7 #include "base/lazy_instance.h" | |
8 #include "base/logging.h" | |
9 #include "base/synchronization/lock.h" | |
10 | |
11 namespace webkit_glue { | |
12 | |
13 namespace { | |
14 | |
15 class UserAgentState { | |
16 public: | |
17 UserAgentState(); | |
18 ~UserAgentState(); | |
19 | |
20 void Set(const std::string& user_agent); | |
21 const std::string& Get() const; | |
22 | |
23 private: | |
24 mutable std::string user_agent_; | |
25 | |
26 mutable bool user_agent_requested_; | |
27 | |
28 // This object can be accessed from multiple threads, so use a lock around | |
29 // accesses to the data members. | |
30 mutable base::Lock lock_; | |
31 }; | |
32 | |
33 UserAgentState::UserAgentState() | |
34 : user_agent_requested_(false) { | |
35 } | |
36 | |
37 UserAgentState::~UserAgentState() { | |
38 } | |
39 | |
40 void UserAgentState::Set(const std::string& user_agent) { | |
41 base::AutoLock auto_lock(lock_); | |
42 if (user_agent == user_agent_) { | |
43 // We allow the user agent to be set multiple times as long as it | |
44 // is set to the same value, in order to simplify unit testing | |
45 // given g_user_agent is a global. | |
46 return; | |
47 } | |
48 DCHECK(!user_agent.empty()); | |
49 DCHECK(!user_agent_requested_) << "Setting the user agent after someone has " | |
50 "already requested it can result in unexpected behavior."; | |
51 user_agent_ = user_agent; | |
52 } | |
53 | |
54 const std::string& UserAgentState::Get() const { | |
55 base::AutoLock auto_lock(lock_); | |
56 user_agent_requested_ = true; | |
57 | |
58 DCHECK(!user_agent_.empty()); | |
59 | |
60 return user_agent_; | |
61 } | |
62 | |
63 base::LazyInstance<UserAgentState> g_user_agent = LAZY_INSTANCE_INITIALIZER; | |
64 | |
65 } // namespace | |
66 | |
67 void SetUserAgent(const std::string& user_agent) { | |
68 g_user_agent.Get().Set(user_agent); | |
69 } | |
70 | |
71 const std::string& GetUserAgent(const GURL& url) { | |
72 return g_user_agent.Get().Get(); | |
73 } | |
74 | |
75 } // namespace webkit_glue | |
OLD | NEW |