Class AbstractBigViewer

java.lang.Object
sc.fiji.snt.viewer.AbstractBigViewer
Direct Known Subclasses:
Bdv, Bvv

public abstract class AbstractBigViewer extends Object
Abstract base for SNT's BigDataViewer-family viewers (Bvv, Bdv, etc.).

Provides shared infrastructure for tree/path management, calibration, and bookmark support, leaving viewer-specific rendering, source loading, and camera control to concrete subclasses.

The AbstractBigViewer.AnnotationOverlay interface defined here is the common contract that all viewer overlays must satisfy so that BookmarkManager can drive them without knowing the concrete viewer type.

Author:
Tiago Ferreira
See Also:
  • Field Details

  • Constructor Details

    • AbstractBigViewer

      protected AbstractBigViewer()
    • AbstractBigViewer

      protected AbstractBigViewer(SNT snt)
  • Method Details

    • getSNT

      public SNT getSNT()
      Returns:
      SNT instance this viewer is tethered to, or null if no SNT instance is available.
    • isTracingEnabled

      public boolean isTracingEnabled()
      Returns:
      whether this viewer's own Start/Stop Tracing toggle is on, i.e. whether AbstractBigViewer.AbstractTracer.handleClick(MouseEvent) will act on the next click (start/extend/fork a path) rather than ignoring it outright. Exposed so other click-consuming features sharing this viewer's display component (e.g. SeedOverlayBigViewerHandler's Alt+Click, which collides with Alt+Click-to-fork below) can back off while tracing-by-click is live, since AbstractTracer reacts in mouseReleased - always dispatched before mouseClicked - so a later listener's MouseEvent#consume() cannot undo it.
    • isEditModeEnabled

      public boolean isEditModeEnabled()
      Returns:
      whether this viewer is currently in Edit Mode (node-level editing of a single selected path)
    • toggleEditMode

      public void toggleEditMode()
      Toggles Edit Mode: node-level editing of the single selected path, mirroring the Edit-path commands of the classic canvas. Only available in SNT-tethered viewers. Entering requires exactly one selected path and suspends tracing for the duration.
    • onSntEditModeChanged

      public void onSntEditModeChanged(boolean enabled)
      Called by SNT when Edit Mode is (de)activated from any front-end, including this one (see SNT#enterEditMode(Path))
    • refreshEditNodesOnSelectionChange

      protected void refreshEditNodesOnSelectionChange()
      Re-evaluates the Edit Mode markers after a selection change (they are only shown for a selected path)
    • onSntEditedPathModified

      public void onSntEditedPathModified()
      Called by SNT when nodes of the path being edited were modified in place by another front-end
    • onSntActiveNodeChanged

      public void onSntActiveNodeChanged()
      Called by SNT when the active node (or its lock state) was changed by another front-end
    • onSntEditingPathChanged

      public void onSntEditingPathChanged()
      Called by SNT when the path being edited has changed while in Edit Mode
    • resolveCursorWorldPosition

      protected double[] resolveCursorWorldPosition()
      World position of the cursor, as used by Edit Mode to place/move nodes. The default is the position reported by getGlobalMouseCoordinates(RealPoint) (appropriate for an orthogonal slicing view); Bvv overrides it to resolve depth the same way its tracer does.
      Returns:
      calibrated (x,y,z) position, or null if it could not be resolved
    • invalidatePathGeometry

      protected void invalidatePathGeometry()
      Discards cached path geometry and repaints. Needed after in-place edits of a Path (e.g., a moved node), which the structural fingerprint of the cached screen data does not detect
    • installContextMenu

      protected void installContextMenu()
      Attaches the context menu (see BigViewerMenu) to the viewer's display. To be called once the display exists. No-op in standalone viewers
    • runContextCommand

      public String runContextCommand(ContextMenuCommand cmd)
      Runs a command of the viewer's context menu without displaying it
      Parameters:
      cmd - the command
      Returns:
      null if the command was run, otherwise the reason why it was not
    • revealContextCommand

      public void revealContextCommand(ContextMenuCommand cmd)
      Displays the viewer's context menu at the center of the display, with the item of a command armed
      Parameters:
      cmd - the command
    • runContextItem

      public String runContextItem(JMenuItem canvasItem)
      Runs the equivalent of a tracing canvas menu item without displaying the viewer's menu
      Parameters:
      canvasItem - the item of the tracing canvas menu
      Returns:
      null if the item was run, otherwise the reason why it was not
    • revealContextItem

      public void revealContextItem(JMenuItem canvasItem)
      Displays the viewer's context menu with the equivalent of a tracing canvas menu item armed
      Parameters:
      canvasItem - the item of the tracing canvas menu
    • setTracingLockedByPause

      public void setTracingLockedByPause(boolean locked)
      Locks/unlocks this viewer's tracing-mode toolbar buttons to "No tracing", as for a global SNT pause. Also used to suspend tracing-by-click while in Edit Mode. Does nothing if this viewer has no tracer
      Parameters:
      locked - whether tracing is currently suspended
    • getKeybindings

      protected abstract org.scijava.ui.behaviour.util.InputActionBindings getKeybindings()
      Returns:
      the key bindings of the viewer's frame, or null if the frame does not exist (yet)
    • installEditKeybindings

      protected void installEditKeybindings(InputMap inputMap, ActionMap actionMap)
      Adds transient key bindings (taking precedence over the viewer's own and the permanent SNT ones) for the duration of Edit Mode. Counterpart of removeEditKeybindings()
    • removeEditKeybindings

      protected void removeEditKeybindings()
      Removes the bindings added by installEditKeybindings(InputMap, ActionMap)
    • getGuiUtils

      protected GuiUtils getGuiUtils()
    • enableTracing

      public void enableTracing(boolean manual)
      Enables tracing on this viewer, as if the user had clicked its manual/interactive tracing-mode toggle button (see AbstractTracer#getToggleAction(boolean)), so a click on the canvas traces instead of panning it. Shows an error dialog and leaves tracing off if manual is false (semi-automated tracing) and no image data is available to trace on. Does nothing if this viewer has no tracer (e.g. a standalone viewer with no attached SNT instance, or the toolbar has not been built yet).
      Parameters:
      manual - true for manual (point-and-click) tracing, false for semi-automated (auto-trace) tracing
      See Also:
    • isPathInProgress

      public boolean isPathInProgress()
      Returns:
      whether this viewer currently has a path in progress, i.e. the user has clicked to start (or extend/fork) a path but has not yet finished or discarded it. Always false if this viewer has no tracer (see enableTracing(boolean)).
      See Also:
    • registerOmeZarrSource

      public void registerOmeZarrSource(String path)
      Registers the path of a source so that a unit set through showCalibrationDialog(java.awt.Component) can be saved to it. Ignored unless path is a local OME-Zarr (OME-NGFF v0.5) directory
      Parameters:
      path - the path of the loaded dataset
    • getDefaultRenderingStyle

      public AbstractBigViewer.PathRenderingOptions.Style getDefaultRenderingStyle()
      Gets the path rendering style used when no preference has been stored. Centerlines by default; overridden by viewers that favor frusta.
      Returns:
      the default style
    • isDisposed

      public final boolean isDisposed()
      Returns:
      whether dispose() has been called
    • dispose

      public final void dispose()
      Releases the resources held by this viewer (overlays, timers, cached data, ...) and closes its window. Called when the window is dismissed. Safe to call from any thread, and more than once
    • disposeViewer

      protected void disposeViewer()
      Viewer-specific part of dispose(), called at most once. Implementations must not call dispose() themselves, and should leave the bookkeeping of the tethered SNTUI to it
    • syncPathManagerList

      public boolean syncPathManagerList()
      Replaces the rendered trees with the current contents of the Path Manager. Only available in SNT-tethered instances.
      Returns:
      true if paths were synced; false if the path manager is empty
      Throws:
      IllegalArgumentException - if this is a standalone viewer
    • collapseGroupsCard

      protected static void collapseGroupsCard(bdv.ui.CardPanel cardPanel)
      Collapses the stock "Groups" card. Must be called on the EDT
      Parameters:
      cardPanel - the viewer's card panel
    • getViewerFrame

      public abstract JFrame getViewerFrame()
      Returns the top-level Swing window for this viewer, or null if not yet open.
    • getViewerSplitPanel

      protected abstract JSplitPane getViewerSplitPanel()
      Returns the JSplitPane that separates the viewer canvas from the card panel. Both BDV and BVV frames expose this via their own getSplitPanel() methods, but those classes share no common supertype above JFrame, so this method lets subclasses expose the split pane without the abstract method returning a viewer-specific frame type.
    • getViewerWidth

      public abstract int getViewerWidth()
      Returns the width of the viewer canvas in logical pixels, or 0 if the viewer is not yet initialized.
    • getViewerHeight

      public abstract int getViewerHeight()
      Returns the height of the viewer canvas in logical pixels, or 0 if the viewer is not yet initialized.
    • getViewerCanvas

      public abstract Component getViewerCanvas()
      Returns the viewer canvas itself, i.e., the actual Component getViewerWidth()/ getViewerHeight() measure, or null if the viewer is not yet initialized. Unlike those two, callers can use this to locate the canvas on screen (e.g. via SwingUtilities.convertPoint()) - the canvas is not necessarily centered in, or even the same size as, the frame's content pane, since getViewerSplitPanel() may also be hosting a side panel next to it
    • getViewerTransform

      public abstract net.imglib2.realtransform.AffineTransform3D getViewerTransform()
      Returns a snapshot of the current viewer-to-screen (world-to-screen) transform. The returned object is a copy; callers may modify it freely.
    • setViewerTransform

      public abstract void setViewerTransform(net.imglib2.realtransform.AffineTransform3D target, long durationMs)
      Animates the viewer transform to target over durationMs milliseconds. Use durationMs = 0 for an immediate jump.
      Parameters:
      target - the desired world-to-screen transform
      durationMs - animation duration in milliseconds (0 = immediate)
    • showViewerMessage

      public abstract void showViewerMessage(String msg)
      Displays a short status message in the viewer's overlay area.

      This is bdv-core/bvv-core's fading toast: it auto-dismisses after a few seconds. For an ongoing, non-auto-dismissing indication of a long-running operation, use updateStatus(java.lang.String, int, int) instead.

      Parameters:
      msg - the message to show
    • updateStatus

      public void updateStatus(String message, int step, int nSteps)
      Updates the persistent progress bar docked at the bottom of this viewer's card panel. Unlike showViewerMessage(java.lang.String), it stays visible until reset.
      • nSteps = 0: hides the bar
      • nSteps < 0: indeterminate mode (animated, no percentage)
      • nSteps > 0: determinate mode showing step/nSteps
      Safe to call from any thread.
      Parameters:
      message - short status message displayed inside the bar
      step - current step (0-based; ignored in indeterminate mode)
      nSteps - total steps (0 = hide, negative = indeterminate)
    • initProgressBar

      protected void initProgressBar(bdv.ui.CardPanel cardPanel)
      Creates the progress bar driven by updateStatus(String, int, int) and docks it at the bottom of the card panel, below all cards and without a card header. This avoids the viewport flicker caused by adding the bar to the frame's BorderLayout.SOUTH.
      Parameters:
      cardPanel - the viewer's card panel
    • resyncCalibrationFromActiveSource

      public abstract void resyncCalibrationFromActiveSource()
      Forces snt's image metadata (dimensions, calibration, pixel data, channel/frame) to be re-read from this viewer's currently active Source, the same resync AbstractBigViewer.AbstractTracer performs on its own before starting a new path (see AbstractTracer#syncChannelFromActiveSource()).

      That resync is otherwise only triggered by the first click of a new path, so snt's calibration can be stale (or still at whatever BigDataLoaderCmd's best-effort fallback produced at load time) for anything that reads it beforehand - such as SNT#buildMaterializedCrop(BoundingBox). Callers that need calibration to reflect exactly what this viewer is currently rendering, before the user has traced anything, should call this first.

      A no-op if no tracer has been created yet, or if the active source can't be resolved.

    • applyAutoBrightness

      protected abstract void applyAutoBrightness(AbstractBigViewer.BrightnessScope scope)
      Recomputes the display range (brightness/contrast) for the source(s) selected by scope, from data percentiles, on a bounded background thread - see ViewerSettingsUtils.initBrightnessSafely(bdv.viewer.ViewerState, bdv.viewer.ConverterSetups, java.lang.String). Called automatically with AbstractBigViewer.BrightnessScope.ALL right after a source is first added, and re-invocable on demand (any scope) via the "Auto Brightness/Contrast" scene-control button (see autoBrightnessButton(sc.fiji.snt.viewer.AbstractBigViewer.Actions)). Does nothing if this viewer isn't yet backed by an underlying BDV/BVV scene (e.g. show(...) hasn't been called).
      Parameters:
      scope - which source(s) to recompute
    • addToCardPanelBottom

      protected static void addToCardPanelBottom(bdv.ui.CardPanel cardPanel, JComponent comp)
      Docks a component at the bottom of a CardPanel, below all cards, without a card header. Uses MigLayout's "dock south" constraint. If the CardPanel's container layout ever changes away from MigLayout this degrades gracefully: the component simply won't appear (no crash, no viewport flicker). Shared by Bvv and Bdv's own progress bars.
    • showLoadedData

      public abstract void showLoadedData()
      Displays the main tracing data (the currently active channel/frame of the image being traced) from the associated SNT instance. Only available in SNT-tethered instances.
      Throws:
      IllegalArgumentException - if this is a standalone viewer, or no valid image data is available
    • showSecondaryData

      public abstract void showSecondaryData()
      Displays the secondary tracing data (the filtered/processed layer used for cost-function-based tracing) from the associated SNT instance. Only available in SNT-tethered instances.
      Throws:
      IllegalArgumentException - if this is a standalone viewer, or no secondary data is available
    • hideSecondaryData

      public abstract void hideSecondaryData()
      Removes the secondary tracing data layer previously added by showSecondaryData() from this viewer, if one is currently displayed. No-op otherwise (e.g., standalone viewers, untethered instances, or when no secondary layer has been shown yet).
      See Also:
    • updateSecondaryLayerIndicator

      public abstract void updateSecondaryLayerIndicator()
      Refreshes the persistent "secondary layer active" indicator shown in this viewer's SNT Controls card, reflecting SNT.isTracingOnSecondaryImageActive(). No-op if this is not a tethered, tracer-enabled instance (i.e., the indicator was never built). Safe to call from any thread.
    • resetView

      public abstract void resetView()
      Resets the view to frame all loaded data.
    • isOpen

      public abstract boolean isOpen()
      Returns true if the viewer window is currently visible and usable.
    • repaint

      public abstract void repaint()
      Requests a repaint of the viewer canvas.
    • syncOverlays

      public abstract void syncOverlays()
      Synchronizes all active rendering overlays (paths, markers) with the current state of renderedTrees and any pending annotation changes.
    • setDisplayRadii

      public abstract void setDisplayRadii(boolean display)
      Sets whether paths are rendered as frusta (tubes) or simple centerlines, and triggers an overlay cache invalidation.
      Parameters:
      display - true to render frusta using per-node radii; false for fast centerline rendering
    • annotations

      public abstract AbstractBigViewer.AnnotationOverlay annotations()
      Returns the annotation overlay for this viewer. The overlay renders point markers in the viewer's world coordinate space. May return null if the viewer has not been opened yet.
    • getDefaultMarkerSize

      public abstract float getDefaultMarkerSize()
      Returns the default sphere radius (in physical units) for newly placed markers. Implementations typically derive this from their rendering-options or a sensible default.
    • getDefaultMarkerColor

      public abstract Color getDefaultMarkerColor()
      Returns the default color for newly placed markers, or null to use the viewer's own fallback color.
    • getCurrentTimepoint

      public abstract int getCurrentTimepoint()
      Returns this viewer's current timepoint (1-based, matching Path.getFrame()'s convention), or 1 if no data is loaded / timepoint tracking is unavailable.
    • setCurrentTimepoint

      public abstract void setCurrentTimepoint(int timepoint)
      Navigates this viewer to the specified timepoint (1-based, matching Path.getFrame()'s convention). Does nothing if no data is loaded.
      Parameters:
      timepoint - the 1-based timepoint to navigate to; values < 1 are coerced to 1
    • flyTo

      public boolean flyTo(BoundingBox box)
      Animates the camera to frame the given world-coordinate bounding box: an isotropic scale is computed so the box's width/height fit the viewport, and the transform is translated to center the box's centroid on screen. Any existing rotation is dropped.

      A degenerate box (zero width/height - e.g. a single-node selection, whose origin and originOpposite are the same point) cannot be "fit" (there is nothing to scale to), so this recenters on the centroid at the viewer's current zoom level instead.

      Parameters:
      box - the world-coordinate bounding box to frame; a no-op if null, its corners are not real (e.g. an empty/uncomputed box), or the viewport has not yet been realized
      Returns:
      true if the transform was computed and applied; false otherwise
    • flyTo

      public void flyTo(double x, double y, double z, int t, String label)
      Animates the camera so that the given world position lands at the center of the viewport, keeping the current rotation and scale, and jumps to the given timepoint if it differs from the current one.
      Parameters:
      x - the X coordinate (world/physical units)
      y - the Y coordinate (world/physical units)
      z - the Z coordinate (world/physical units)
      t - the (1-based) timepoint to display
      label - text shown in the viewer message
    • setViewerTransformImmediate

      protected void setViewerTransformImmediate(net.imglib2.realtransform.AffineTransform3D target)
      Sets the viewer transform at once (no animation). Used by PathPlayer, which updates the transform at every tick. The default implementation relies on a minimal-duration animation.
      Parameters:
      target - the transform to be applied
    • playPaths

      public PathPlayer playPaths(Collection<Path> paths, double speed, double fov)
      Plays a walkthrough of the specified paths: the view is centered on a point traveling along each path at constant speed (translation only: the current rotation is preserved). Playback is non-blocking, and can be aborted by clicking on the display or by calling stopPlayback(). Since the distance covered per tick does not depend on rendering speed, playbacks are reproducible, and the elapsed time reported by PathPlayer.getSummary() reflects how well the viewer keeps up.
      Parameters:
      paths - the paths to be played, in order
      speed - the travel speed, in world units per second (<= 0 for the default of 50)
      fov - the width of the field of view, in world units, or <= 0 to keep the current zoom
      Returns:
      the player, or null if the viewer is not ready. Use it to register callbacks or retrieve the summary
    • stopPlayback

      public void stopPlayback()
      Stops the playback started by playPaths(Collection, double, double), if any
    • promptGoTo

      public void promptGoTo()
      Prompts for an XYZ location (physical units), pre-filled with the clipboard contents if these look like coordinates, and flies to it at the current timepoint.
    • getSceneCenter

      public SNTPoint getSceneCenter()
      The world-space point currently displayed at the center of this viewer, i.e. the inverse of flyTo(sc.fiji.snt.util.BoundingBox)'s centroid-to-screen-center mapping: applies the inverse viewer transform to the viewport's center screen point, at the focal plane (viewer-space Z = 0).

      Correct as-is for an orthogonal slicing view (the displayed slice is the focal plane). Bvv overrides this to prefer the depth of whatever is actually visible there (see Bvv.findSceneCenterMaxima()), falling back to this same focal-plane result when that ray finds nothing.

      Returns:
      the world-space scene center, or null if the viewport has not yet been realized
    • createMarkerManager

      protected abstract BookmarkManager createMarkerManager()
      Creates and returns a new BookmarkManager for this viewer. Called exactly once (lazily) by getMarkerManager().
    • getGlobalMouseCoordinates

      public abstract void getGlobalMouseCoordinates(net.imglib2.RealPoint pos)
      Writes the current global (world-space) mouse position into pos. Callers must supply a pre-allocated RealPoint with at least 3 dimensions.
      Parameters:
      pos - 3D point to receive the world-space cursor position
    • getCurrentSource

      protected abstract bdv.viewer.SourceAndConverter<?> getCurrentSource()
      Returns the currently active source, or null if none.
    • addMouseListenerToDisplay

      public abstract void addMouseListenerToDisplay(MouseListener ml)
      Adds a mouse listener to the viewer's canvas component so that click events on the display surface can be handled (e.g. for hit testing annotation markers).
      Parameters:
      ml - the listener to add
    • getViewerAction

      protected abstract Action getViewerAction(String name)
      Looks up a named action from the viewer's keybindings action map. Returns null if the action is not registered or the viewer is not ready.
      Parameters:
      name - the action key (e.g., "align XY plane")
    • registerNativeCommands

      protected void registerNativeCommands(SNTCommandFinder commandFinder, ActionMap actionMap, InputMap inputMap, List<String> path, Icon icon, Set<String> excludedNames, KeyStroke... excludedTriggers)
      Registers this viewer's native (library-level) single-shot commands -- i.e., entries of the BDV/BVV keybindings ActionMap, as opposed to SNT's own overlaid commands (see AbstractBigViewer.Actions) -- in commandFinder, so they become searchable/runnable from the command palette. Meant to be called once per viewer instance, only while Stream mode is active

      Continuous, held-key or mouse-drag behaviors (pan, rotate, zoom, scroll) are not picked up by this scrape: they live elsewhere so they are excluded by construction. excludedTriggers additionally drops named actions bound to specific keys that clutter the palette.

      Parameters:
      commandFinder - the palette to register into; a no-op if null
      actionMap - the viewer's concatenated keybindings ActionMap
      inputMap - the viewer's concatenated keybindings InputMap, used only to resolve excludedTriggers to the action keys they are bound to
      path - palette category shown for every registered entry, e.g. List.of("Bvv Viewer")
      icon - icon applied to every registered entry via Action.SMALL_ICON; may be null
      excludedNames - action-map keys to skip outright, matched case-insensitively against the raw (un-prettified) key -- for contextual/"abort this in-progress gesture" natives that have no single dedicated trigger key, or SNT press/release-pair overlays (e.g., "hide annotations (hold)") that only make sense as a held key, never as a one-shot palette command
      excludedTriggers - keystrokes whose bound action should be skipped (the keystroke itself does not need to be a valid trigger for this viewer; unresolved ones are ignored)
    • registerCommandFinderAccelerator

      protected static void registerCommandFinderAccelerator(InputMap sntIMap, ActionMap sntAMap, SNTCommandFinder commandFinder)
      Wires commandFinder's own show/toggle shortcut (SNTCommandFinder.getAccelerator()) into this viewer's keybindings, so it fires while the Bvv/Bdv window itself has focus. Standard Swing accelerators (as installed by SNTCommandFinder.attach(JDialog)) don't reach here: BDV/BVV's behavior-based trigger layer intercepts keystrokes before a component's ordinary InputMap/ActionMap ever sees them (see the identical constraint noted where sntIMap/ sntAMap are built in Bvv/Bdv), so the shortcut has to be added to that same sntIMap/sntAMap pair instead, alongside SNT's other viewer-overlay bindings.
      Parameters:
      sntIMap - the viewer's own SNT-overlay InputMap, not yet installed via addInputMap
      sntAMap - the matching ActionMap, not yet installed via addActionMap
      commandFinder - the palette whose accelerator should open/focus it; a no-op if null
    • registerSntKeybindings

      protected void registerSntKeybindings(InputMap sntIMap, ActionMap sntAMap, AbstractBigViewer.Actions actions, Action addMarker, AbstractBigViewer.AbstractTracer tracer)
      Registers SNT's viewer keybindings shared by Bvv and Bdv: M (marker), H (hold to hide annotations), L (secondary layer), P (pick sigma point) and, if a tracer is available, the tracing shortcuts (G, Shift+G, Enter, Esc, Z, Space). They must go through BDV/BVV's keybindings system, since its input trigger layer shadows ordinary Swing InputMaps. Same sntIMap/sntAMap constraints as registerCommandFinderAccelerator(javax.swing.InputMap, javax.swing.ActionMap, sc.fiji.snt.gui.SNTCommandFinder).
      Parameters:
      sntIMap - the viewer's own SNT-overlay InputMap, not yet installed
      sntAMap - the matching ActionMap, not yet installed
      actions - the viewer's AbstractBigViewer.Actions
      addMarker - the action bound to M
      tracer - the viewer's tracer, or null if tracing is unavailable
    • registerKeyframeCapture

      protected void registerKeyframeCapture(InputMap sntIMap, ActionMap sntAMap)
      Registers the keyframe hotkeys: K captures a Keyframe and appends it to a running script-ready kfs block that is printed to the console and copied to the clipboard, and Shift+K clears that block. Same sntIMap/sntAMap constraints as registerCommandFinderAccelerator(javax.swing.InputMap, javax.swing.ActionMap, sc.fiji.snt.gui.SNTCommandFinder).
      Parameters:
      sntIMap - the viewer's own SNT-overlay InputMap, not yet installed
      sntAMap - the matching ActionMap, not yet installed
    • captureKeyframe

      public Keyframe captureKeyframe()
      Captures the current viewer state as a Keyframe: transform, camera/slab parameters (BVV only), timepoint, and visible actors.
      Returns:
      the current state as a Keyframe
      Throws:
      IllegalStateException - if no viewer is active
    • getRenderSettleTime

      public long getRenderSettleTime()
      Gets the time without new render passes after which a recorded frame is considered fully refined.
      Returns:
      the settle time in milliseconds
      See Also:
    • setRenderSettleTime

      public void setRenderSettleTime(long millis)
      Sets the time without new render passes after which a recorded frame is considered fully refined and is captured by renderFrames(List, String). The viewer renders progressively (coarse first): values that are too small may yield low-resolution frames, while large values slow down recording. Default is 250 ms.
      Parameters:
      millis - the settle time in milliseconds (non-negative)
    • playback

      public void playback(List<Keyframe> keyframes)
      Plays back an animation between keyframes in the viewer without saving frames. The frame count of each transition is read from Keyframe.frames on the destination keyframe.
      Parameters:
      keyframes - ordered list of keyframes (at least 2)
      See Also:
    • playback

      public void playback(List<Keyframe> keyframes, int from, int to)
      Plays back keyframes from to to (both inclusive, 0-based).
      Parameters:
      keyframes - ordered list of all keyframes
      from - start index
      to - end index
      See Also:
    • renderFrames

      public void renderFrames(List<Keyframe> keyframes, String outputDir)
      Renders an animation between keyframes, saving each frame as a PNG. The transform is interpolated using SimilarityTransformAnimator and the timepoint linearly (if specified in both keyframes); visibility and slab bounds snap at keyframe boundaries. The first keyframe's Keyframe.frames is ignored. Must be called from a non-EDT thread: blocks until done.
      Parameters:
      keyframes - ordered list of keyframes (at least 2)
      outputDir - directory for the PNGs (created if needed); if null, frames are played back live without saving
      Throws:
      IllegalArgumentException - if arguments are inconsistent
      IllegalStateException - if no viewer is active
    • getViewerState

      protected abstract bdv.viewer.SynchronizedViewerState getViewerState()
      Returns the viewer's state (sources, groups, timepoint) or null if not yet live
    • loadViewerSettings

      protected abstract void loadViewerSettings(String path) throws Exception
      Loads viewer settings (display ranges, colors, etc.) from an XML file.
      Parameters:
      path - the path of the settings file
      Throws:
      Exception - if the settings could not be loaded
    • saveViewerSettings

      protected abstract void saveViewerSettings(String path) throws Exception
      Saves viewer settings (display ranges, colors, etc.) to an XML file.
      Parameters:
      path - the path of the settings file
      Throws:
      Exception - if the settings could not be saved
    • getSettingsTag

      protected abstract String getSettingsTag()
      Tag identifying the viewer type in the names of settings files (e.g., "bdv" or "bvv")
    • installFileDrop

      protected void installFileDrop(bdv.ui.CardPanel c)
      Allows files to be imported by dropping them onto a component (e.g., the viewer's card panel): reconstructions (SWC, TRACES, etc.) as in add(File[]), display settings files as in loadViewerSettings(String), and CSV files into the marker manager. Children added to the component later are covered as they do not define drop targets
    • initBrightnessOrRestore

      protected void initBrightnessOrRestore(bdv.viewer.ViewerState state, bdv.viewer.ConverterSetups setups, String title, String id, String label)
      Initializes the display range of the sources. If saved settings for this dataset exist, and the user agrees to restore them, they are loaded instead of computing the display range
      Parameters:
      state - the viewer state
      setups - the converter setups
      title - the dataset title (null to use the name of the first source)
      id - the dataset identifier, e.g., path (null to use the title)
      label - short description of the viewer/dataset, for logging
    • restoreSidecarSettings

      protected void restoreSidecarSettings(bdv.viewer.ViewerState state, bdv.viewer.ConverterSetups setups)
      Restores the settings file stored next to the primary source, if any, without touching the display range otherwise. For viewers that rely on their own auto-brightness (e.g., BDV)
    • setupIdToName

      protected Map<Integer,String> setupIdToName()
      Maps current converter setup ids to source names
    • showShortcuts

      protected abstract void showShortcuts(GuiUtils gui)
      Displays the dialog listing the viewer's keyboard shortcuts
    • getDisplayRange

      public double[] getDisplayRange(int sourceIndex)
      Returns the display range (brightness min/max) of a source in the viewer.
      Parameters:
      sourceIndex - 0-based index of the source (e.g., channel), or a negative value for the active source
      Returns:
      {min, max} in raw intensity units, or null if unavailable
      See Also:
    • getSourceData

      public net.imglib2.RandomAccessibleInterval<?> getSourceData(int sourceIndex, int level)
      Returns the pixel data of a source in the viewer at the current timepoint. Unlike SNT.getLoadedData(), which holds a single channel, this gives access to any source.
      Parameters:
      sourceIndex - 0-based index of the source (e.g., channel), or a negative value for the active source
      level - the resolution level (0: full resolution). Clamped to the levels available
      Returns:
      the source's data
      Throws:
      IllegalStateException - if the viewer has no live state or the source cannot be resolved/read
      See Also:
    • getSourceName

      public String getSourceName(int sourceIndex)
      Returns the name of a source in the viewer.
      Parameters:
      sourceIndex - 0-based index of the source (e.g., channel), or a negative value for the active source
      Returns:
      the source name, or null if unavailable
    • getNumResolutionLevels

      public int getNumResolutionLevels(int sourceIndex)
      Returns the number of resolution levels of a source in the viewer.
      Parameters:
      sourceIndex - 0-based index of the source (e.g., channel), or a negative value for the active source
      Returns:
      the number of levels (1 if the source has no pyramid or is unavailable)
    • getDownsamplingFactors

      public double[] getDownsamplingFactors(int sourceIndex, int level)
      Returns how much coarser a resolution level is than full resolution, along each axis.
      Parameters:
      sourceIndex - 0-based index of the source (e.g., channel), or a negative value for the active source
      level - the resolution level (clamped to the levels available)
      Returns:
      {x, y, z} downsampling factors (all 1 for level 0)
    • getConverterSetups

      protected abstract bdv.viewer.ConverterSetups getConverterSetups()
      Returns the viewer's per-source display settings (levels, LUTs) or null if not yet live
    • getCamParams

      protected double[] getCamParams()
      Returns the current {dCam, nearClip, farClip}. Defaults to BVV's defaults: viewers without a perspective camera (BDV) keep this implementation.
    • applyCamParams

      protected void applyCamParams(double dCam, double nearClip, double farClip)
      Applies camera/slab parameters from a Keyframe. No-op by default
    • awaitRender

      protected void awaitRender(Runnable trigger, long settleMillis) throws InterruptedException
      Runs trigger (which updates the viewer and requests a repaint) and blocks until the resulting frame has been rendered. Must not be called on the EDT. The default implementation waits a fixed interval.
      Parameters:
      trigger - the action that changes the scene
      settleMillis - the time without new render passes after which the frame is considered fully refined (implementations may ignore it)
      Throws:
      InterruptedException - if interrupted while waiting
    • addTree

      public void addTree(Tree tree)
      Adds a Tree to the viewer overlay, assigning it a unique display label.
      Parameters:
      tree - the Tree to render; must not be null or empty
    • addTree

      protected void addTree(Tree tree, boolean syncNow)
      Internal add with optional immediate overlay sync. Subclasses may override if they need to track per-tree state beyond the shared map.
    • add

      public void add(Object o)
      Script-friendly dispatcher: accepts a Tree, DirectedWeightedGraph, File[], or any Collection of supported objects.
      Parameters:
      o - the object to add
      Throws:
      IllegalArgumentException - if the type is not supported
    • add

      protected void add(Object o, boolean syncNow)
      Internal dispatcher with deferred sync support for batch operations.
    • addCollection

      protected void addCollection(Collection<?> collection, boolean syncNow)
      Adds all elements of a collection, optionally syncing once at the end.
    • add

      public void add(File[] reconstructionFiles)
      Loads reconstruction files (SWC, JSON, TRACES) and adds them to the viewer. Trees are colored with distinct colors and the overlay is synced once at the end. Subclasses may override for async loading with progress feedback (see Bvv).
      Parameters:
      reconstructionFiles - the files to load; null or empty is silently ignored
    • removeTree

      public boolean removeTree(String treeLabel)
      Removes the tree with the given label from the overlay.
      Parameters:
      treeLabel - the display label of the tree to remove
      Returns:
      true if a tree with that label existed and was removed
    • clearAllTrees

      public void clearAllTrees()
      Removes all rendered trees from the overlay.
    • getRenderedTrees

      public Collection<Tree> getRenderedTrees()
      Returns a snapshot of the currently rendered trees (insertion order). Deliberately an independent copy, not a live view over renderedTrees - see renderedTreesLock': a live view (the previous behavior) is vulnerable to a ConcurrentModificationException if another thread mutates renderedTrees while this collection is being iterated, which for a caller like Bvv.OverlayRenderer#updatePaths(Collection) (iterating well after this method returns) is a real, previously-observed race during active interactive tracing.
      Returns:
      collection of rendered trees (insertion order)
    • getMarkerManager

      public BookmarkManager getMarkerManager()
      Returns the marker manager panel, creating it lazily on first call via createMarkerManager().
      Returns:
      the marker manager for this viewer
    • hasMarkerManager

      public boolean hasMarkerManager()
      Checks whether a BookmarkManager has already been created for this viewer, without triggering its (lazy, non-trivial) creation as getMarkerManager() would. Useful for display/logging code that wants to report marker counts only if the panel is already in use.
    • setCalibration

      public void setCalibration(double[] spacing, String unit)
      Sets the voxel calibration for the viewer.
      Parameters:
      spacing - voxel sizes [x, y, z]
      unit - physical unit string (e.g., "um")
    • getCalibration

      public double[] getCalibration()
      Returns the current voxel sizes, or null if not set.
    • getBoundingBox

      public BoundingBox getBoundingBox()
      Returns the world-space bounding box of the primary loaded volume. The box is anchored at the translation of the first source's sourceTransform (the same value SNT.getWorldOriginOffset() is built from in Stream mode), or at (0,0,0) if no source is available. Only the translation is considered: rotation/shear is ignored
      Returns:
      the volume's bounding box, or null if dimensions/calibration are not yet known
    • getPrimarySourcePath

      public String getPrimarySourcePath()
      Returns the file path/URL of the primary loaded volume, for display/logging purposes (e.g., a Notes entry documenting the dataset being traced).

      Only sources registered through datasetPaths (i.e., datasets opened via AbstractSpimData-based show(...) overloads, such as N5/Zarr/BDV/IMS data) are tracked. There is no guaranteed order if more than one source is loaded; this simply returns the first entry found.

      Returns:
      the source path/URL, or null if unknown/not applicable
    • getSourcePaths

      public List<String> getSourcePaths()
      Returns the distinct file paths/URLs of all datasets tracked by this viewer (see getPrimarySourcePath() for the tracking caveat)
      Returns:
      the source paths/URLs (unordered, possibly empty)
    • getPhysicalUnit

      public String getPhysicalUnit()
      Derives the best available physical unit string. Subclasses may override to add viewer-specific fallbacks (e.g., reading units from source VoxelDimensions).
    • getUniqueLabel

      protected String getUniqueLabel(Tree tree)
      Returns a display label for the tree that is unique within renderedTrees. Derived from the tree's own label, appending "(2)", "(3)" etc. as needed.
    • isPathRenderingEnabled

      protected abstract boolean isPathRenderingEnabled()
      Returns true if path/tree overlay rendering is currently enabled.
    • setPathRenderingEnabled

      protected abstract void setPathRenderingEnabled(boolean enabled)
      Enables or disables path/tree overlay rendering.
    • setPathOverlayOffset

      public abstract void setPathOverlayOffset(double offsetX, double offsetY, double offsetZ)
      Applies a world-space offset to all rendered path annotations.
      Parameters:
      offsetX - x offset in calibrated units
      offsetY - y offset in calibrated units
      offsetZ - z offset in calibrated units
    • getRenderingOptions

      public AbstractBigViewer.PathRenderingOptions getRenderingOptions()
      Returns the rendering options shared across this viewer's overlays.
    • optionsButton

      protected JButton optionsButton(AbstractBigViewer.Actions actions)
      Builds the "Options" button (Import Reconstructions.../Remove All Annotations...) shared by Bvv/Bdv's own SNT Annotations toolbar.
    • autoBrightnessButton

      protected JButton autoBrightnessButton(AbstractBigViewer.Actions actions)
      Builds the "Auto Brightness/Contrast" options button (Current Source.../Active Source(s).../All Sources...) for the scene-control toolbar. See applyAutoBrightness(BrightnessScope).
    • tracingStatusRow

      protected JComponent tracingStatusRow(AbstractBigViewer.Actions actions, AbstractBigViewer.AbstractTracer tracer)
      Builds the second row shown below the SNT Annotations toolbar whenever this viewer has an active AbstractBigViewer.AbstractTracer (undo/cancel controls, secondary-layer toggle, progress bar). Shared by Bvv/Bdv, which both keep the returned components (see tracingStatusBar, tracingCancelButton, tracingUndoButton, secondaryLayerIndicator) in sync from their own AbstractBigViewer.AbstractTracer subclass.
    • showCalibrationDialog

      public void showCalibrationDialog(Component parent)
      Prompts the user for voxel spacing and its physical unit, and updates calibration.

      Confirming here also propagates to snt via SNT.setImageMetadata(int, int, int, double, double, double, java.lang.String).Dimensions are left untouched (passed as 0, which setImageMetadata treats as "no change").

      Parameters:
      parent - component used to anchor the dialog
    • addSharedSceneOptions

      protected void addSharedSceneOptions(JPopupMenu menu, AbstractBigViewer.Actions actions)
      Adds the entries common to the scene-control "Options" menu of Bvv/Bdv: navigation, restore view (display settings) and help. Viewer-specific entries should be added to the menu beforehand
    • finishSceneControlToolbar

      protected JToolBar finishSceneControlToolbar(JToolBar bar, JPopupMenu menu)
      Completes a scene-control toolbar started with buildBaseSceneControlToolbar() by appending the trailing "Options" button holding the given menu
      Returns:
      the toolbar, for chaining
    • buildBaseSceneControlToolbar

      protected JToolBar buildBaseSceneControlToolbar()
      Builds the shared scene-control toolbar: fit-source button, align-plane buttons (XY, XZ, YZ), minimap toggle, text-overlay toggle, scale-bar toggle. Subclasses call this and may prepend or append viewer-specific buttons.
      Returns:
      a partially populated JToolBar ready for additional buttons