1// Copyright (c) 2011 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 "ppapi/shared_impl/time_conversion.h"
6
7namespace ppapi {
8
9namespace {
10
11// Since WebKit doesn't use ticks for event times, we have to compute what
12// the time ticks would be assuming the wall clock time doesn't change.
13//
14// This should only be used for WebKit times which we can't change the
15// definition of.
16double GetTimeToTimeTicksDeltaInSeconds() {
17  static double time_to_ticks_delta_seconds = 0.0;
18  if (time_to_ticks_delta_seconds == 0.0) {
19    double wall_clock = TimeToPPTime(base::Time::Now());
20    double ticks = TimeTicksToPPTimeTicks(base::TimeTicks::Now());
21    time_to_ticks_delta_seconds = ticks - wall_clock;
22  }
23  return time_to_ticks_delta_seconds;
24}
25
26}  // namespace
27
28PP_Time TimeToPPTime(base::Time t) { return t.ToDoubleT(); }
29
30base::Time PPTimeToTime(PP_Time t) {
31  // The time code handles exact "0" values as special, and produces
32  // a "null" Time object. But calling code would expect t==0 to represent the
33  // epoch (according to the description of PP_Time). Hence we just return the
34  // epoch in this case.
35  if (t == 0.0)
36    return base::Time::UnixEpoch();
37  return base::Time::FromDoubleT(t);
38}
39
40PP_TimeTicks TimeTicksToPPTimeTicks(base::TimeTicks t) {
41  return static_cast<double>(t.ToInternalValue()) /
42         base::Time::kMicrosecondsPerSecond;
43}
44
45PP_TimeTicks EventTimeToPPTimeTicks(double event_time) {
46  return event_time + GetTimeToTimeTicksDeltaInSeconds();
47}
48
49double PPTimeTicksToEventTime(PP_TimeTicks t) {
50  return t - GetTimeToTimeTicksDeltaInSeconds();
51}
52
53double PPGetLocalTimeZoneOffset(const base::Time& time) {
54  // Explode it to local time and then unexplode it as if it were UTC. Also
55  // explode it to UTC and unexplode it (this avoids mismatching rounding or
56  // lack thereof). The time zone offset is their difference.
57  base::Time::Exploded exploded = {0};
58  base::Time::Exploded utc_exploded = {0};
59  time.LocalExplode(&exploded);
60  time.UTCExplode(&utc_exploded);
61  if (exploded.HasValidValues() && utc_exploded.HasValidValues()) {
62    base::Time adj_time = base::Time::FromUTCExploded(exploded);
63    base::Time cur = base::Time::FromUTCExploded(utc_exploded);
64    return (adj_time - cur).InSecondsF();
65  }
66  return 0.0;
67}
68
69}  // namespace ppapi
70