3 * Reporting progress for long-running jobs
5 * (c) 2018 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of the Trivial IP Encryption (TrIPE) Android app.
12 * TrIPE is free software: you can redistribute it and/or modify it under
13 * the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your
15 * option) any later version.
17 * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
26 package uk.org.distorted.tripe; package object progress {
28 /*----- Imports -----------------------------------------------------------*/
30 import scala.collection.mutable.{Publisher, Subscriber};
32 import java.lang.Math.ceil;
33 import java.lang.System.currentTimeMillis;
35 /*----- Main code ---------------------------------------------------------*/
37 def formatTime(t: Int): String =
40 val (s, t1) = (t%60, t/60);
41 val (m, h) = (t1%60, t1/60);
42 if (h > 0) f"$h%d:$m%02d:$s%02d"
46 private val UDATA = Seq("kB", "MB", "GB", "TB", "PB", "EB");
47 def formatBytes(n: Long): String = {
48 val (x, u) = ((n.toDouble, "B ") /: UDATA) { (xu, n) => (xu, n) match {
49 case ((x, u), name) if x >= 1024.0 => (x/1024.0, name)
56 def set(line: String);
59 def commit(line: String) { commit(); set(line); commit(); }
63 abstract class Event; // other subclasses can be added!
64 abstract class Progress extends Event { def cur: Long; } // it changed
66 def unapply(p: Progress) =
70 case class Update(override val cur: Long) extends Progress; // progress has been made
71 case class Changed(override val cur: Long) extends Progress; // what or max changed
72 abstract class Stopped extends Event; // job has stopped
73 case object Done extends Stopped; // job completed successfuly
74 final case class Failed(why: String) extends Stopped; // job failed
75 case object Cancelled extends Stopped; // job was cancelled
77 trait Job extends Publisher[Event] {
78 def what: String; // imperative for what we're doing
79 def cur: Long; // current position in work
80 def max: Long; // maximum work to do
81 def format: String = { // describe progress in useful terms
85 val fm = m.formatted("%d");
86 s"%${fm.length}d/%s".format(c, fm) // ugh!
87 } else if (c > 0) s"$c"
92 private[this] val t0 = currentTimeMillis;
95 def taken: Double = (currentTimeMillis - t0)/1000.0;
97 /* Report the estimated time remaining in seconds, or -1 if no idea.
99 * The model here is very stupid. Weird jobs should override this and do
100 * something more sensible.
103 if (max < 0 || cur <= 0) -1
104 else taken*(max - cur)/cur.toDouble;
107 /*----- Terminal eyecandy (FIXME: split this out) -------------------------*/
109 import java.io.FileDescriptor;
110 import java.lang.System.{out => stdout};
113 object TerminalEyecandy extends Eyecandy with Subscriber[Event, Job] {
114 private var last = "";
115 var eyecandyp = isatty(FileDescriptor.out);
117 /* Assume that characters take up one cell each. This is going to fail
118 * badly for combining characters, zero-width characters, wide Asian
119 * characters, and lots of other Unicode characters. The problem is that
120 * Java doesn't have any way to query the display width of a character,
121 * and, honestly, I don't care enough to do the (substantial) work required
122 * to do this properly.
125 def set(line: String) {
128 /* If the old line is longer than the new one, then we must overprint
131 if (line.length < last.length) {
132 val n = last.length - line.length;
133 for (_ <- 0 until n) stdout.write('\b');
134 for (_ <- 0 until n) stdout.write(' ');
137 /* Figure out the length of the common prefix between what we had
138 * before and what we have now.
140 val m = (0 until (last.length min line.length)) prefixLength
141 { i => last(i) == line(i) };
143 /* Delete the tail from the old line and print the new version. */
144 for (_ <- m until last.length) stdout.write('\b');
145 stdout.print(line.substring(m));
149 /* Update the state. */
153 def clear() { set(""); }
157 if (eyecandyp) stdout.write('\n');
158 else stdout.println(last);
163 private final val spinner = """/-\|""";
164 private var step: Int = 0;
165 private final val width = 40;
167 def begin(job: Job) { job.subscribe(this); }
169 def notify(job: Job, ev: Event) {
171 case Progress(cur) =>
172 /* Redraw the status line. */
176 val sb = new StringBuilder;
177 sb ++= job.what; sb += ' ';
179 /* Step the spinner. */
180 step += 1; if (step >= spinner.length) step = 0;
181 sb += spinner(step); sb += ' ';
185 sb ++= "[unknown progress]";
187 val n = (width*cur/max).toInt;
189 for (_ <- 0 until n) sb += '=';
190 for (_ <- n until 40) sb += ' ';
194 if (f != "") { sb += ' '; sb ++= f; }
195 sb ++= (100*cur/max).formatted(" %3d%%");
199 sb += ' '; sb += '(';
200 sb ++= formatTime(ceil(eta).toInt);
209 val t = formatTime(ceil(job.taken).toInt);
210 set(s"${job.what} done ($t)"); commit();
213 set(s"${job.what} CANCELLED"); commit();
216 set(s"${job.what} FAILED: $msg"); commit();
223 /*----- Testing cruft -----------------------------------------------------*/
225 trait AsyncJob extends Job {
227 private var _cur: Long = 0; override def cur = _cur;
237 class ToyJob(val max: Long) extends Job {
238 val what = "Dummy job";
239 private var _i: Long = 0; def cur = _i;
243 for (i <- 1l until max) { _i = i; publish(Update(i)); sleep(100); }
248 def testjob(n: Long) {
249 val j = new ToyJob(n);
250 TerminalEyecandy.begin(j);
254 /*----- That's all, folks -------------------------------------------------*/