1// Copyright (C) 2018 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import {duration, time} from './time'; 16import {HighPrecisionTime} from './high_precision_time'; 17import {HighPrecisionTimeSpan} from './high_precision_time_span'; 18import {HorizontalBounds} from './geom'; 19 20export class TimeScale { 21 readonly timeSpan: HighPrecisionTimeSpan; 22 readonly pxBounds: HorizontalBounds; 23 private readonly timePerPx: number; 24 25 constructor(timespan: HighPrecisionTimeSpan, pxBounds: HorizontalBounds) { 26 this.pxBounds = pxBounds; 27 this.timeSpan = timespan; 28 const delta = pxBounds.right - pxBounds.left; 29 if (timespan.duration <= 0 || delta <= 0) { 30 this.timePerPx = 1; 31 } else { 32 this.timePerPx = timespan.duration / delta; 33 } 34 } 35 36 timeToPx(ts: time): number { 37 const timeOffset = 38 Number(ts - this.timeSpan.start.integral) - 39 this.timeSpan.start.fractional; 40 return this.pxBounds.left + timeOffset / this.timePerPx; 41 } 42 43 hpTimeToPx(time: HighPrecisionTime): number { 44 const timeOffset = time.sub(this.timeSpan.start).toNumber(); 45 return this.pxBounds.left + timeOffset / this.timePerPx; 46 } 47 48 // Convert pixels to a high precision time object, which can be further 49 // converted to other time formats. 50 pxToHpTime(px: number): HighPrecisionTime { 51 const timeOffset = (px - this.pxBounds.left) * this.timePerPx; 52 return this.timeSpan.start.addNumber(timeOffset); 53 } 54 55 durationToPx(dur: duration): number { 56 return Number(dur) / this.timePerPx; 57 } 58 59 pxToDuration(pxDelta: number): number { 60 return pxDelta * this.timePerPx; 61 } 62} 63