Make ViewComponent api better for expected use

- Exposing eventloop if user need to interact with it
- Add api/feature to set used view rect expand to
  full terminal width
- Add plain ProgressView samples
- Relates #995
- Fixes #997
This commit is contained in:
Janne Valkealahti
2024-02-02 09:32:07 +00:00
parent 10d9940299
commit 9446afecb7
2 changed files with 115 additions and 7 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2023 the original author or authors.
* Copyright 2023-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package org.springframework.shell.component;
import org.jline.terminal.Size;
import org.jline.terminal.Terminal;
import org.springframework.shell.component.message.ShellMessageBuilder;
@@ -22,6 +23,7 @@ import org.springframework.shell.component.view.TerminalUI;
import org.springframework.shell.component.view.control.View;
import org.springframework.shell.component.view.control.ViewDoneEvent;
import org.springframework.shell.component.view.event.EventLoop;
import org.springframework.shell.geom.Rectangle;
import org.springframework.util.Assert;
/**
@@ -34,37 +36,65 @@ public class ViewComponent {
private final Terminal terminal;
private final View view;
private EventLoop eventLoop;
private TerminalUI ui;
private boolean useTerminalWidth = true;
/**
* Construct view component with a given {@link Terminal} and {@link View}.
*
* @param terminal the terminal
* @param view the main view
*/
public ViewComponent(Terminal terminal, View view) {
Assert.notNull(terminal, "terminal must be set");
Assert.notNull(view, "view must be set");
this.terminal = terminal;
this.view = view;
this.ui = new TerminalUI(terminal);
this.eventLoop = ui.getEventLoop();
}
/**
* Run a view execution loop.
*/
public void run() {
TerminalUI ui = new TerminalUI(terminal);
eventLoop = ui.getEventLoop();
eventLoop.onDestroy(eventLoop.viewEvents(ViewDoneEvent.class, view)
.subscribe(event -> {
exit();
}
));
view.setEventLoop(eventLoop);
Size terminalSize = terminal.getSize();
Rectangle rect = view.getRect();
if (useTerminalWidth) {
view.setRect(rect.x(), rect.y(), terminalSize.getColumns() - rect.x(), rect.height());
}
ui.setRoot(view, false);
ui.run();
}
/**
* Sets if full terminal width should be used for a view. Defaults to {@code true}.
*
* @param useTerminalWidth the use terminal width flag
*/
public void setUseTerminalWidth(boolean useTerminalWidth) {
this.useTerminalWidth = useTerminalWidth;
}
/**
* Gets an {@link EventLoop} associated with this view component.
*
* @return event loop with this view component
*/
public EventLoop getEventLoop() {
return eventLoop;
}
/**
* Request exit from an execution loop.
*/
public void exit() {
if (eventLoop == null) {
return;
}
eventLoop.dispatch(ShellMessageBuilder.ofInterrupt());
}