Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added idle bars #1680

Merged
merged 9 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cli/src/main/java/de/jplag/cli/CLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
import de.jplag.JPlag;
import de.jplag.JPlagResult;
import de.jplag.Language;
import de.jplag.cli.logger.CliProgressBarProvider;
import de.jplag.cli.logger.CollectedLoggerFactory;
import de.jplag.cli.logger.TongfeiProgressBarProvider;
import de.jplag.cli.server.ReportViewer;
import de.jplag.clustering.ClusteringOptions;
import de.jplag.clustering.Preprocessing;
Expand Down Expand Up @@ -85,7 +85,7 @@ public static void main(String[] args) {
ParseResult parseResult = cli.parseOptions(args);

if (!parseResult.isUsageHelpRequested() && !(parseResult.subcommand() != null && parseResult.subcommand().isUsageHelpRequested())) {
ProgressBarLogger.setProgressBarProvider(new TongfeiProgressBarProvider());
ProgressBarLogger.setProgressBarProvider(new CliProgressBarProvider());
switch (cli.options.mode) {
case RUN -> cli.runJPlag(parseResult);
case VIEW -> cli.runViewer(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@
/**
* A ProgressBar provider, that used the tongfei progress bar library underneath, to show progress bars on the cli.
*/
public class TongfeiProgressBarProvider implements ProgressBarProvider {
public class CliProgressBarProvider implements ProgressBarProvider {
@Override
public ProgressBar initProgressBar(ProgressBarType type, int totalSteps) {
me.tongfei.progressbar.ProgressBar progressBar = new ProgressBarBuilder().setTaskName(type.getDefaultText()).setInitialMax(totalSteps)
.setStyle(ProgressBarStyle.ASCII).build();
return new TongfeiProgressBar(progressBar);
if (type.isIdleBar()) {
return new IdleBar(type.getDefaultText());
} else {
me.tongfei.progressbar.ProgressBar progressBar = new ProgressBarBuilder().setTaskName(type.getDefaultText()).setInitialMax(totalSteps)
.setStyle(ProgressBarStyle.ASCII).build();
return new TongfeiProgressBar(progressBar);
}
}
}
104 changes: 104 additions & 0 deletions cli/src/main/java/de/jplag/cli/logger/IdleBar.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package de.jplag.cli.logger;

import java.io.IOException;

import org.apache.commons.lang3.time.DurationFormatUtils;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;

import de.jplag.logging.ProgressBar;

/**
* Prints an idle progress bar, that does not count upwards.
*/
public class IdleBar implements ProgressBar {
private final Thread runner;

private long startTime;
private final String text;
private int length;

private int currentPos;
private int currentDirection;

private boolean running = false;

public IdleBar(String text) {
this.runner = new Thread(this::run);
this.length = 50;
this.currentDirection = -1;
this.currentPos = 0;
this.text = text;
try {
Terminal terminal = TerminalBuilder.terminal();
this.length = Math.min(terminal.getWidth() / 2, terminal.getWidth() - 50);
terminal.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (this.length < 10) {
this.length = 10;
}
}

public void start() {
this.startTime = System.currentTimeMillis();
this.running = true;
this.runner.start();
}

@Override
public void dispose() {
this.running = false;
try {
this.runner.join();
} catch (InterruptedException ignored) {
}
System.out.println();
}

private void run() {
while (running) {
System.out.print('\r');
System.out.print(printLine());
if (currentPos == 0 || currentPos == length - 1) {
currentDirection *= -1;
}
try {
Thread.sleep(200);
} catch (InterruptedException ignore) {
// ignore wakeup
}
currentPos += currentDirection;
}
}

private String printLine() {
StringBuilder line = new StringBuilder();
line.append(this.text).append(' ');

line.append('<');
line.append(" ".repeat(Math.max(0, currentPos)));
line.append("<+>");
line.append(" ".repeat(Math.max(0, length - currentPos - 1)));
line.append('>');

long timeRunning = System.currentTimeMillis() - this.startTime;
line.append(' ');
String duration = DurationFormatUtils.formatDuration(timeRunning, "H:mm:ss");
line.append(duration);

return line.toString();
}

@Override
public void step(int number) {
}

public static void main(String[] args) throws InterruptedException {
IdleBar bar = new IdleBar("Printing progress");
bar.start();
Thread.sleep(20000);
bar.dispose();
}
}
72 changes: 72 additions & 0 deletions cli/src/test/java/de/jplag/cli/logger/IdleBarTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package de.jplag.cli.logger;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class IdleBarTest {
private static final String TEST_BAR_TEXT = "Test";
private static final long TEST_TIME = 10000;
private static final long IDLE_BAR_ANIMATION_DELAY = 200;

/**
* Tests if the output of the idle bar looks plausible
*/
@Test
void testIdleBarPlausible() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream oldSystemOut = System.out;
System.setOut(new PrintStream(outputStream));

IdleBar idleBar = new IdleBar(TEST_BAR_TEXT);
idleBar.start();
try {
Thread.sleep(TEST_TIME);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
idleBar.dispose();
System.setOut(oldSystemOut);

String result = outputStream.toString();
String[] animationFrames = result.substring(1).split("\\r");
Assertions.assertTrue(Math.abs(animationFrames.length - (TEST_TIME / IDLE_BAR_ANIMATION_DELAY)) <= 2,
"Unexpected number of animation frames.");

String firstFrame = animationFrames[0];
int numberOfSpaces = firstFrame.lastIndexOf('>') - firstFrame.indexOf('<') - 3 - 1;
for (int i = 0; i < animationFrames.length; i++) {
checkIdleBarOutput(animationFrames[i], i, numberOfSpaces);
}
}

/**
* Checks that the given string matches the expected content of an animation frame
* @param output The animation frame
* @param frameIndex The index of the frame
* @param numberOfSpaces The number of spaces within the bar
*/
private void checkIdleBarOutput(String output, int frameIndex, int numberOfSpaces) {
int pass = frameIndex / numberOfSpaces;
int offset = frameIndex % numberOfSpaces;
if (pass % 2 == 1) {
offset = numberOfSpaces - offset;
}

String expectedOutput = TEST_BAR_TEXT + ' ' + '<' + " ".repeat(offset) + "<+>" + " ".repeat(numberOfSpaces - offset) + '>';

int endOfPredictableOutput = output.lastIndexOf(' ');
String predictableOutput = output.substring(0, endOfPredictableOutput);
String time = output.substring(endOfPredictableOutput + 1).trim();

Assertions.assertEquals(expectedOutput, predictableOutput);
Assertions.assertTrue(time.matches("[0-9]:[0-9]{2}:[0-9]{2}"), "Invalid format for time");

String[] timeParts = time.split(":");
int seconds = Integer.parseInt(timeParts[0]) * 60 * 60 + Integer.parseInt(timeParts[1]) * 60 + Integer.parseInt(timeParts[2]);
int expectedTime = (int) ((IDLE_BAR_ANIMATION_DELAY * frameIndex) / 1000);
Assertions.assertTrue(Math.abs(seconds - expectedTime) < 1, "Frame time of by more than one second");
}
}
6 changes: 5 additions & 1 deletion core/src/main/java/de/jplag/logging/ProgressBarLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ private static class DummyBar implements ProgressBar {

public DummyBar(ProgressBarType type, int totalSteps) {
this.currentStep = 0;
logger.info("{} ({})", type.getDefaultText(), totalSteps);
if (type.isIdleBar()) {
logger.info("{} - started", type.getDefaultText());
} else {
logger.info("{} ({})", type.getDefaultText(), totalSteps);
}
}

@Override
Expand Down
18 changes: 14 additions & 4 deletions core/src/main/java/de/jplag/logging/ProgressBarType.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@
* The available processes. Used as a hint for the ui, which step JPlag is currently performing.
*/
public enum ProgressBarType {
LOADING("Loading Submissions "),
PARSING("Parsing Submissions "),
COMPARING("Comparing Submissions");
LOADING("Loading Submissions ", false),
PARSING("Parsing Submissions ", false),
COMPARING("Comparing Submissions", false),
TokenStringNormalizer("Normalizing token Sequence ", true);

private final String defaultText;
private final boolean isIdleBar;

ProgressBarType(String defaultText) {
ProgressBarType(String defaultText, boolean isIdleBar) {
this.defaultText = defaultText;
this.isIdleBar = isIdleBar;
}

/**
Expand All @@ -20,4 +23,11 @@ public enum ProgressBarType {
public String getDefaultText() {
return defaultText;
}

/**
* @return True, if this bar should be rendered as an idle bar instead.
*/
public boolean isIdleBar() {
return isIdleBar;
}
}
Loading