1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.ahat;
18 
19 import com.android.ahat.progress.Progress;
20 
21 /**
22  * A progress bar that prints ascii to System.out.
23  * <p>
24  * For best results, have System.out positioned at a new line before using
25  * this progress indicator.
26  */
27 class AsciiProgress implements Progress {
28   private String description;
29   private long duration;
30   private long progress;
31 
display(String description, long percent)32   private static void display(String description, long percent) {
33     System.out.print(String.format("\r[ %3d%% ] %s ...", percent, description));
34     System.out.flush();
35   }
36 
37   @Override
start(String description, long duration)38   public void start(String description, long duration) {
39     assert this.description == null;
40     this.description = description;
41     this.duration = duration;
42     this.progress = 0;
43     display(description, 0);
44   }
45 
46   @Override
advance(long n)47   public void advance(long n) {
48     update(progress + n);
49   }
50 
51   @Override
update(long current)52   public void update(long current) {
53     assert description != null;
54     long oldPercent = progress * 100 / duration;
55     long newPercent = current * 100 / duration;
56     progress = current;
57 
58     if (newPercent > oldPercent) {
59       display(description, newPercent);
60     }
61   }
62 
63   @Override
done()64   public void done() {
65     update(duration);
66     System.out.println();
67     this.description = null;
68   }
69 }
70