Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
import io.github.ghosthack.microhm.mux.client.AttachedSession;
import io.github.ghosthack.microhm.mux.client.SessionServerClient;
import io.github.ghosthack.microhm.mux.client.SessionServerException;
import io.github.ghosthack.microhm.mux.protocol.Protocol;
import io.github.ghosthack.microhm.mux.session.Session;

import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

/**
Expand Down Expand Up @@ -149,6 +151,31 @@ public SessionConnection attach(String session, int columns, int rows) {
return new SessionServerConnection(attached);
}

/** The daemon's event stream for every session (later ones too), filtered to its
* {@code title} events. The quiet period only paces {@code quiet} events, which this
* ignores, so it is set long to keep them rare. */
@Override
public Optional<TitleWatch> watchTitles(BiConsumer<String, String> onTitle) {
SessionServerClient.Watch watch = call(() -> client.watch(null, TITLE_WATCH_QUIET_MS, event -> {
if (Protocol.EVENT_TITLE.equals(event.type())) {
onTitle.accept(event.name(), event.title() == null ? "" : event.title());
}
}));
return Optional.of(new TitleWatch() {
@Override
public boolean isOpen() {
return watch.isOpen();
}

@Override
public void close() {
watch.close();
}
});
}

private static final long TITLE_WATCH_QUIET_MS = 60_000;

/** One daemon request, with its failure translated for the seam: same message, the
* daemon's exception kept as the cause so a log still shows which side failed. */
private static <T> T call(Supplier<T> request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;

/**
* The substrate that hosts named sessions — the app's session daemon. This is the seam
Expand Down Expand Up @@ -49,4 +51,25 @@ public interface SessionHost {
* therefore never called on the EDT.
*/
SessionConnection attach(String session, int columns, int rows);

/** An open title stream from {@link #watchTitles}. */
interface TitleWatch extends AutoCloseable {
/** False once the stream has ended (the daemon went away or dropped it). */
boolean isOpen();

@Override
void close();
}

/**
* Streams every session's OSC title as the program in it sets it, frame by frame: a
* spinner a harness animates in its title arrives as each frame it writes. {@code
* onTitle} gets {@code (sessionName, title)} on a background thread. Empty when this
* host cannot stream titles (callers fall back to {@link #capture}'s title); throws
* {@link SessionHostException} when it could but the stream would not open now (no
* server, or one too old to watch).
*/
default Optional<TitleWatch> watchTitles(BiConsumer<String, String> onTitle) {
return Optional.empty();
}
}
133 changes: 133 additions & 0 deletions app/src/main/java/io/github/ghosthack/microhm/app/ui/LiveTitles.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package io.github.ghosthack.microhm.app.ui;

import io.github.ghosthack.microhm.app.host.SessionHost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;

/**
* Keeps the host's title stream ({@link SessionHost#watchTitles}) open and hands each
* session's newest title to the UI, so the sidebar shows the frames a harness writes into
* its title as it writes them rather than whatever frame the next status poll samples.
*
* <p>Titles are coalesced per session between deliveries: a burst of spinner frames
* arriving faster than the EDT drains becomes one delivery carrying the latest frame of
* each session, so a busy harness can never queue up stale frames. Nothing is invented
* or interpolated; at worst a frame is skipped. A stream that ends (daemon restarted, no
* daemon yet, one too old to watch) is reopened with backoff, and the status poll's title
* covers the gap.
*/
final class LiveTitles {

private static final Logger LOG = LoggerFactory.getLogger(LiveTitles.class);

static final Duration BACKOFF_MIN = Duration.ofSeconds(1);
static final Duration BACKOFF_MAX = Duration.ofSeconds(30);
/** How often the loop checks that an open stream is still open. */
private static final Duration CHECK = Duration.ofSeconds(1);

private final SessionHost host;
private final Consumer<Runnable> edt;
private final Consumer<Map<String, String>> onTitles;
private final Map<String, String> latest = new ConcurrentHashMap<>();
private final AtomicBoolean drainQueued = new AtomicBoolean();
private volatile boolean running;
private Thread loop;

/**
* @param edt runs a task on the UI thread ({@code SwingUtilities::invokeLater})
* @param onTitles gets {@code sessionName -> newest title} on the UI thread
*/
LiveTitles(SessionHost host, Consumer<Runnable> edt, Consumer<Map<String, String>> onTitles) {
this.host = host;
this.edt = edt;
this.onTitles = onTitles;
}

synchronized void start() {
if (loop != null) {
return;
}
running = true;
loop = Thread.ofVirtual().name("mhm-live-titles").start(this::run);
}

synchronized void stop() {
running = false;
if (loop != null) {
loop.interrupt();
loop = null;
}
}

/** Called on the stream's reader thread for every title change. */
void titleChanged(String session, String title) {
latest.put(session, title);
if (drainQueued.compareAndSet(false, true)) {
edt.accept(this::drain);
}
}

private void drain() {
drainQueued.set(false);
Map<String, String> batch = new HashMap<>();
for (String session : latest.keySet()) {
String title = latest.remove(session);
if (title != null) {
batch.put(session, title);
}
}
if (!batch.isEmpty() && running) {
onTitles.accept(batch);
}
}

private void run() {
Duration backoff = BACKOFF_MIN;
SessionHost.TitleWatch watch = null;
try {
while (running) {
if (watch == null || !watch.isOpen()) {
closeQuietly(watch);
watch = null;
try {
Optional<SessionHost.TitleWatch> opened = host.watchTitles(this::titleChanged);
if (opened.isEmpty()) {
return; // this host has no title stream: the poll is all there is
}
watch = opened.get();
backoff = BACKOFF_MIN;
} catch (RuntimeException e) {
LOG.debug("title stream unavailable, retrying in {}: {}", backoff, e.toString());
Thread.sleep(backoff.toMillis());
Duration doubled = backoff.multipliedBy(2);
backoff = doubled.compareTo(BACKOFF_MAX) > 0 ? BACKOFF_MAX : doubled;
continue;
}
}
Thread.sleep(CHECK.toMillis());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
closeQuietly(watch);
}
}

private static void closeQuietly(SessionHost.TitleWatch watch) {
if (watch != null) {
try {
watch.close();
} catch (RuntimeException ignored) {
// already gone
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,16 @@ public String getToolTipText(MouseEvent event) {
* stopping: a tick that finds nothing pulsing stops the timer, and
* {@link #ensurePulsing()} restarts it wherever states or attachment change. */
private final Timer pulseTimer = new Timer(PULSE_FRAME_MS, e -> repaintPulsingDots());

/** Each session's title as its harness writes it, frame by frame (see
* {@link #onLiveTitles}); the status poll's sampled title is the fallback. */
private final LiveTitles liveTitles;

/** The window title follows the selected session's live status mark, but no faster
* than this: a native title-bar update per spinner frame costs more than it shows. */
static final int WINDOW_TITLE_MARK_MIN_MS = 250;
private final Timer windowTitleTimer = new Timer(WINDOW_TITLE_MARK_MIN_MS,
e -> updateWindowTitle(sidebarList.getSelectedValue()));
private final KeyEventDispatcher keyEventDispatcher = this::handleGlobalKeyEvent;
private final JButton sidebarButton = new JButton();
private final JButton openButton = new JButton("Open…");
Expand Down Expand Up @@ -586,6 +596,8 @@ public void doLayout() {
this.gracefulCloser = new GracefulCloser(host, Duration.ofMillis(250),
Duration.ofSeconds(10), Duration.ofSeconds(5));
this.statusPollTimer = new Timer(statusPollIntervalMs, e -> pollLiveSessions());
this.liveTitles = new LiveTitles(host, SwingUtilities::invokeLater, this::onLiveTitles);
windowTitleTimer.setRepeats(false);
statusPollTimer.setInitialDelay(500);
if (statusPollingEnabled) {
statusPollTimer.start();
Expand All @@ -606,6 +618,7 @@ public void doLayout() {
sessionEvents.addSessionRunEndedListener(sessionRunEndedListener);

refreshSidebar(null);
liveTitles.start();
}

/**
Expand Down Expand Up @@ -681,6 +694,8 @@ void shutdown() {
statusPollTimer.stop();
activeTabPollTimer.stop();
pulseTimer.stop();
liveTitles.stop();
windowTitleTimer.stop();
KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(keyEventDispatcher);
backgroundExecutor.shutdownNow();
settingsExecutor.shutdown();
Expand Down Expand Up @@ -1079,7 +1094,7 @@ private void applySidebar(ReconciliationResult result, String reselect) {
if (previous.state() != null) {
sidebarEntry.setState(previous.state(), previous.stateReason());
}
sidebarEntry.setPaneTitle(previous.paneTitle());
sidebarEntry.carryTitleFrom(previous);
}
allSidebarEntries.add(sidebarEntry);
}
Expand Down Expand Up @@ -1240,6 +1255,9 @@ private void updateWindowTitle(SidebarEntry entry) {
}
String path = entry.abbreviatedPath();
String sessionName = ellipsizeRight(entry.displayName(), WINDOW_TITLE_SESSION_MAX_CHARS);
if (!entry.titleMark().isEmpty()) {
sessionName = entry.titleMark() + " " + sessionName;
}
setTitle(sessionName + (path.isEmpty() ? "" : " — " + path) + " — " + APP_NAME);
}

Expand Down Expand Up @@ -1519,6 +1537,7 @@ private void onStatusResult(String sessionName, SessionStatusPoller.PollResult r
SessionState oldState = entry.state();
String oldReason = entry.stateReason();
String oldPaneTitle = entry.paneTitle();
String oldTitleMark = entry.titleMark();
if (result.stateConfirmed()) {
entry.setState(result.classification().state(), result.classification().reason());
}
Expand All @@ -1527,7 +1546,8 @@ private void onStatusResult(String sessionName, SessionStatusPoller.PollResult r
// tooltip can show differently afterwards
boolean changed = oldState != entry.state()
|| !Objects.equals(oldReason, entry.stateReason())
|| !Objects.equals(oldPaneTitle, entry.paneTitle());
|| !Objects.equals(oldPaneTitle, entry.paneTitle())
|| !oldTitleMark.equals(entry.titleMark());
SidebarView.FilterStatus newStatus = SidebarView.filterStatus(entry);
boolean filterMembershipMayChange = oldStatus != newStatus
&& visibleStatuses.size() != SidebarView.FilterStatus.values().length;
Expand Down Expand Up @@ -1557,6 +1577,48 @@ private void onStatusResult(String sessionName, SessionStatusPoller.PollResult r
// landing — nothing to update, and the next refreshSidebar() already dropped it
}

/**
* Titles just written by harnesses (on the EDT, newest per session). A new status
* mark repaints only its row; a new name may also re-sort the sidebar, as a polled
* rename does. The selected session's window title follows at most every
* {@link #WINDOW_TITLE_MARK_MIN_MS}.
*/
private void onLiveTitles(Map<String, String> titles) {
if (disposed) {
return;
}
boolean resort = false;
boolean selectedChanged = false;
SidebarEntry selected = sidebarList.getSelectedValue();
for (SidebarEntry entry : allSidebarEntries) {
String title = titles.get(entry.sessionName());
if (title == null || entry.status() != SidebarEntry.Status.LIVE) {
continue;
}
String oldDisplayName = entry.displayName();
String oldMark = entry.titleMark();
entry.setLiveTitle(title);
if (oldMark.equals(entry.titleMark()) && oldDisplayName.equals(entry.displayName())) {
continue;
}
if (sidebarSort == SidebarView.SortMode.SESSION_NAME && !oldDisplayName.equals(entry.displayName())) {
resort = true;
} else {
int index = indexOfSessionName(entry.sessionName());
if (index >= 0) {
sidebarList.repaint(sidebarList.getCellBounds(index, index));
}
}
selectedChanged |= entry.equals(selected);
}
if (resort) {
rebuildVisibleSidebar(lastSelectedSessionName, false);
}
if (selectedChanged && !windowTitleTimer.isRunning()) {
windowTitleTimer.start();
}
}

/** Moves the sidebar's hover highlight to {@code index} (-1 for none), repainting
* only the two rows involved. */
private void setSidebarHover(int index) {
Expand Down
Loading
Loading