diff --git a/pom.xml b/pom.xml index e756b2a..430c25d 100644 --- a/pom.xml +++ b/pom.xml @@ -192,6 +192,7 @@ org.scijava scijava-common + 2.98.1-SNAPSHOT org.scijava @@ -207,6 +208,10 @@ com.miglayout miglayout-swing + + org.apache.commons + commons-compress + org.jfree jfreechart diff --git a/src/main/java/net/imagej/ui/swing/SwingColorBar.java b/src/main/java/net/imagej/ui/swing/SwingColorBar.java index 0bbea6a..d85e523 100644 --- a/src/main/java/net/imagej/ui/swing/SwingColorBar.java +++ b/src/main/java/net/imagej/ui/swing/SwingColorBar.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -47,7 +47,7 @@ /** * A widget for displaying a {@link ColorTable} as a bar. - * + * * @author Curtis Rueden * @author Grant Harris */ @@ -81,7 +81,7 @@ public SwingColorBar(final ColorTable lut, final int height) { /** Sets the {@link ColorTable} displayed by this color bar. */ public void setColorTable(final ColorTable colorTable) { - + if (bar == null || bar.getWidth() != colorTable.getLength()) { // create compatible image bar = AWTImageTools.createImage(colorTable.getLength(), 1); @@ -94,7 +94,7 @@ public void setColorTable(final ColorTable colorTable) { gfx.setColor(new Color(argb, false)); gfx.drawLine(i, 0, i, 1); } - gfx.dispose(); + gfx.dispose(); } // -- JComponent methods -- @@ -124,11 +124,11 @@ public void paintComponent(final Graphics g) { // -- Main method -- public static void main(final String[] args) { - final ColorTable[] luts = - { ColorTables.FIRE, ColorTables.ICE, ColorTables.SPECTRUM, - ColorTables.RED, ColorTables.GREEN, ColorTables.BLUE, ColorTables.CYAN, - ColorTables.MAGENTA, ColorTables.YELLOW, ColorTables.GRAYS, - ColorTables.REDGREEN, ColorTables.RGB332 }; + final ColorTable[] luts = { ColorTables.FIRE, ColorTables.ICE, + ColorTables.SPECTRUM, ColorTables.RED, ColorTables.GREEN, + ColorTables.BLUE, ColorTables.CYAN, ColorTables.MAGENTA, + ColorTables.YELLOW, ColorTables.GRAYS, ColorTables.REDGREEN, + ColorTables.RGB332 }; final JFrame frame = new JFrame(); frame.setTitle("LUTs"); diff --git a/src/main/java/net/imagej/ui/swing/commands/OverlayManager.java b/src/main/java/net/imagej/ui/swing/commands/OverlayManager.java index 3344cd3..7b338ef 100644 --- a/src/main/java/net/imagej/ui/swing/commands/OverlayManager.java +++ b/src/main/java/net/imagej/ui/swing/commands/OverlayManager.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -39,7 +39,7 @@ /** * Command to pop up the {@link SwingOverlayManager}. - * + * * @author Adam Fraser */ @Plugin(type = Command.class, menu = { // @@ -51,7 +51,8 @@ public class OverlayManager extends ContextCommand { @Override public void run() { - final SwingOverlayManager overlaymgr = new SwingOverlayManager(getContext()); + final SwingOverlayManager overlaymgr = new SwingOverlayManager( + getContext()); overlaymgr.setVisible(true); } diff --git a/src/main/java/net/imagej/ui/swing/mdi/viewer/SwingMdiImageDisplayViewer.java b/src/main/java/net/imagej/ui/swing/mdi/viewer/SwingMdiImageDisplayViewer.java index b12630a..47ac4e5 100644 --- a/src/main/java/net/imagej/ui/swing/mdi/viewer/SwingMdiImageDisplayViewer.java +++ b/src/main/java/net/imagej/ui/swing/mdi/viewer/SwingMdiImageDisplayViewer.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -44,14 +44,15 @@ /** * Multiple Document Interface implementation of Swing image display viewer. The * MDI display is housed in a {@link JInternalFrame}. - * + * * @author Grant Harris * @author Curtis Rueden * @author Lee Kamentsky * @see SwingImageDisplayViewer */ @Plugin(type = DisplayViewer.class) -public class SwingMdiImageDisplayViewer extends AbstractSwingImageDisplayViewer +public class SwingMdiImageDisplayViewer extends + AbstractSwingImageDisplayViewer { // -- DisplayViewer methods -- diff --git a/src/main/java/net/imagej/ui/swing/overlay/AbstractJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/AbstractJHotDrawAdapter.java index 04f1417..567f0e4 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/AbstractJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/AbstractJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -55,7 +55,7 @@ /** * An abstract class that gives default behavior for the {@link JHotDrawAdapter} * interface. - * + * * @author Lee Kamentsky */ public abstract class AbstractJHotDrawAdapter diff --git a/src/main/java/net/imagej/ui/swing/overlay/AngleJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/AngleJHotDrawAdapter.java index a4ceaf1..2e53fdf 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/AngleJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/AngleJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -46,7 +46,7 @@ /** * JHotDraw adapter for angle overlays. - * + * * @author Lee Kamentsky * @author Barry DeZonia * @see SwingAngleTool diff --git a/src/main/java/net/imagej/ui/swing/overlay/BezierPathFunctions.java b/src/main/java/net/imagej/ui/swing/overlay/BezierPathFunctions.java index 21b5216..fbdf66f 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/BezierPathFunctions.java +++ b/src/main/java/net/imagej/ui/swing/overlay/BezierPathFunctions.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -47,7 +47,7 @@ /** * Utility functions for {@link GeneralPathJHotDrawAdapter}. - * + * * @author Johannes Schindelin */ public class BezierPathFunctions { @@ -115,11 +115,10 @@ public static void addToRegionOfInterest(final PathIterator iterator, } public enum OP { - ADD, XOR, INTERSECT, SUBTRACT + ADD, XOR, INTERSECT, SUBTRACT } - public static BezierPath add(final BezierPath path1, final BezierPath path2) - { + public static BezierPath add(final BezierPath path1, final BezierPath path2) { return op(path1, path2, OP.ADD); } diff --git a/src/main/java/net/imagej/ui/swing/overlay/DefaultJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/DefaultJHotDrawAdapter.java index 5240e6a..f6ed97f 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/DefaultJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/DefaultJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -60,7 +60,7 @@ * The default adapter handles any kind of overlay. It uses the fill color and * alpha of the overlay to draw the mask and leaves the rest of the figure * transparent. - * + * * @author Lee Kamentsky */ @Plugin(type = JHotDrawAdapter.class, @@ -95,8 +95,8 @@ public Figure createDefaultFigure() { } @Override - public void - updateFigure(final OverlayView overlay, final ImageFigure figure) + public void updateFigure(final OverlayView overlay, + final ImageFigure figure) { super.updateFigure(overlay, figure); @@ -109,18 +109,16 @@ public Figure createDefaultFigure() { final long minY = (long) Math.floor(roi.realMin(1)); final long maxY = (long) Math.ceil(roi.realMax(1)) + 1; final ColorRGB color = overlay.getData().getFillColor(); - final IndexColorModel cm = - new IndexColorModel(1, 2, new byte[] { 0, (byte) color.getRed() }, - new byte[] { 0, (byte) color.getGreen() }, new byte[] { 0, - (byte) color.getBlue() }, new byte[] { 0, - (byte) overlay.getData().getAlpha() }); + final IndexColorModel cm = new IndexColorModel(1, 2, new byte[] { 0, + (byte) color.getRed() }, new byte[] { 0, (byte) color.getGreen() }, + new byte[] { 0, (byte) color.getBlue() }, new byte[] { 0, (byte) overlay + .getData().getAlpha() }); final int w = (int) (maxX - minX); final int h = (int) (maxY - minY); - final BufferedImage img = - new BufferedImage(w, h, BufferedImage.TYPE_BYTE_INDEXED, cm); - final SampleModel sm = - new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, w, h, - new int[] { 1 }); + final BufferedImage img = new BufferedImage(w, h, + BufferedImage.TYPE_BYTE_INDEXED, cm); + final SampleModel sm = new SinglePixelPackedSampleModel( + DataBuffer.TYPE_BYTE, w, h, new int[] { 1 }); final DataBuffer dbuncast = sm.createDataBuffer(); assert dbuncast instanceof DataBufferByte; final DataBufferByte db = (DataBufferByte) dbuncast; @@ -140,8 +138,8 @@ public Figure createDefaultFigure() { index++; } } - final Raster raster = - Raster.createRaster(sm, db, new java.awt.Point(0, 0)); + final Raster raster = Raster.createRaster(sm, db, new java.awt.Point(0, + 0)); img.setData(raster); figure.setBounds(new Rectangle2D.Double(minX, minY, w, h)); figure.setBufferedImage(img); diff --git a/src/main/java/net/imagej/ui/swing/overlay/EllipseJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/EllipseJHotDrawAdapter.java index 19ad2a4..ef6e9a9 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/EllipseJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/EllipseJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -50,7 +50,7 @@ /** * JHotDraw adapter for ellipse overlays. - * + * * @author Lee Kamentsky * @author Barry DeZonia * @see SwingEllipseTool @@ -99,8 +99,7 @@ public Figure createDefaultFigure() { } @Override - public void updateFigure(final OverlayView view, final EllipseFigure figure) - { + public void updateFigure(final OverlayView view, final EllipseFigure figure) { super.updateFigure(view, figure); final EllipseOverlay overlay = downcastOverlay(view.getData()); final double centerX = overlay.getOrigin(0); @@ -113,8 +112,8 @@ public void updateFigure(final OverlayView view, final EllipseFigure figure) } @Override - public void - updateOverlay(final EllipseFigure figure, final OverlayView view) + public void updateOverlay(final EllipseFigure figure, + final OverlayView view) { super.updateOverlay(figure, view); final EllipseOverlay overlay = downcastOverlay(view.getData()); diff --git a/src/main/java/net/imagej/ui/swing/overlay/FigureCreatedEvent.java b/src/main/java/net/imagej/ui/swing/overlay/FigureCreatedEvent.java index c5e8be6..fef45af 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/FigureCreatedEvent.java +++ b/src/main/java/net/imagej/ui/swing/overlay/FigureCreatedEvent.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,11 +35,10 @@ import org.jhotdraw.draw.Figure; - /** * An event that reports the creation of a JHotDraw {@link Figure}, linked to an * ImageJ {@link OverlayView} in a particular {@link ImageDisplay}. - * + * * @author Lee Kamentsky * @author Curtis Rueden */ diff --git a/src/main/java/net/imagej/ui/swing/overlay/GeneralPathFigure.java b/src/main/java/net/imagej/ui/swing/overlay/GeneralPathFigure.java index 7c8a0a3..28abb69 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/GeneralPathFigure.java +++ b/src/main/java/net/imagej/ui/swing/overlay/GeneralPathFigure.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -54,9 +54,8 @@ /** * A composite figure, made up of possibly-overlapping {@link BezierFigure}s. - * * The described figures are always winding rule even/odd. - * + * * @author Johannes Schindelin */ @SuppressWarnings("hiding") @@ -67,10 +66,13 @@ public class GeneralPathFigure extends AbstractAttributedFigure { public GeneralPathFigure(final BezierFigure... list) { figures = new ArrayList() { + @Override public boolean add(final BezierFigure figure) { - figure.restoreAttributesTo(GeneralPathFigure.this.getAttributesRestoreData()); + figure.restoreAttributesTo(GeneralPathFigure.this + .getAttributesRestoreData()); figure.addFigureListener(new FigureListener() { + @Override public void areaInvalidated(FigureEvent e) { invalidate(); @@ -80,7 +82,8 @@ public void areaInvalidated(FigureEvent e) { @Override public void attributeChanged(FigureEvent e) { invalidate(); - fireAttributeChanged(e.getAttribute(), e.getOldValue(), e.getNewValue()); + fireAttributeChanged(e.getAttribute(), e.getOldValue(), e + .getNewValue()); } @Override @@ -228,9 +231,8 @@ public void restoreAttributesTo(Object restoreData) { } /** - * Sets an attribute of the figure. - * AttributeKey name and semantics are defined by the class implementing - * the figure interface. + * Sets an attribute of the figure. AttributeKey name and semantics are + * defined by the class implementing the figure interface. */ @Override public void set(AttributeKey key, T newValue) { @@ -240,7 +242,7 @@ public void set(AttributeKey key, T newValue) { } } - /* -- public methods -- */ + /* -- public methods -- */ @SuppressWarnings("null") public synchronized void setGeneralPath(final GeneralPath path) { @@ -252,24 +254,25 @@ public synchronized void setGeneralPath(final GeneralPath path) { for (; !iterator.isDone(); iterator.next()) { int type = iterator.currentSegment(segment); switch (type) { - case PathIterator.SEG_MOVETO: - if (bezierPath != null) add(bezierPath, false); - bezierPath = new BezierPath(); - bezierPath.moveTo(segment[0], segment[1]); - break; - case PathIterator.SEG_LINETO: - bezierPath.lineTo(segment[0], segment[1]); - break; - case PathIterator.SEG_QUADTO: - bezierPath.quadTo(segment[0], segment[1], segment[2], segment[3]); - break; - case PathIterator.SEG_CUBICTO: - bezierPath.curveTo(segment[0], segment[1], segment[2], segment[3], segment[4], segment[5]); - break; - case PathIterator.SEG_CLOSE: - add(bezierPath, true); - bezierPath = null; - break; + case PathIterator.SEG_MOVETO: + if (bezierPath != null) add(bezierPath, false); + bezierPath = new BezierPath(); + bezierPath.moveTo(segment[0], segment[1]); + break; + case PathIterator.SEG_LINETO: + bezierPath.lineTo(segment[0], segment[1]); + break; + case PathIterator.SEG_QUADTO: + bezierPath.quadTo(segment[0], segment[1], segment[2], segment[3]); + break; + case PathIterator.SEG_CUBICTO: + bezierPath.curveTo(segment[0], segment[1], segment[2], segment[3], + segment[4], segment[5]); + break; + case PathIterator.SEG_CLOSE: + add(bezierPath, true); + bezierPath = null; + break; } } if (bezierPath != null) add(bezierPath, false); diff --git a/src/main/java/net/imagej/ui/swing/overlay/GeneralPathJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/GeneralPathJHotDrawAdapter.java index 6520f3e..35b9016 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/GeneralPathJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/GeneralPathJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -45,10 +45,11 @@ /** * JHotDraw adapter for composite area selections. - * + * * @author Johannes Schindelin */ -@Plugin(type = JHotDrawAdapter.class, priority = GeneralPathJHotDrawAdapter.PRIORITY) +@Plugin(type = JHotDrawAdapter.class, + priority = GeneralPathJHotDrawAdapter.PRIORITY) public class GeneralPathJHotDrawAdapter extends AbstractJHotDrawAdapter { @@ -81,8 +82,7 @@ public Overlay createNewOverlay() { @Override public Figure createDefaultFigure() { - final GeneralPathFigure figure = - new GeneralPathFigure(new PolygonFigure()); + final GeneralPathFigure figure = new GeneralPathFigure(new PolygonFigure()); initDefaultSettings(figure); figure.set(AttributeKeys.WINDING_RULE, AttributeKeys.WindingRule.EVEN_ODD); return figure; diff --git a/src/main/java/net/imagej/ui/swing/overlay/IJBezierTool.java b/src/main/java/net/imagej/ui/swing/overlay/IJBezierTool.java index 5d8d37c..c23e901 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/IJBezierTool.java +++ b/src/main/java/net/imagej/ui/swing/overlay/IJBezierTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,10 +35,9 @@ import org.jhotdraw.draw.DrawingView; import org.jhotdraw.draw.tool.BezierTool; - /** * A JHotDraw {@link BezierTool} for ImageJ's Swing UI. - * + * * @author Lee Kamentsky * @author Johannes Schindelin */ @@ -67,8 +66,8 @@ protected void finishCreation(final BezierFigure figure, final DrawingView drawingView) { super.finishCreation(figure, drawingView); - final JHotDrawService jHotDrawService = - getDisplay().getContext().getService(JHotDrawService.class); + final JHotDrawService jHotDrawService = getDisplay().getContext() + .getService(JHotDrawService.class); jHotDrawService.linkOverlay(figure, getAdapter(), getDisplay()); } diff --git a/src/main/java/net/imagej/ui/swing/overlay/IJCreationTool.java b/src/main/java/net/imagej/ui/swing/overlay/IJCreationTool.java index 6abdd7a..3db7f85 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/IJCreationTool.java +++ b/src/main/java/net/imagej/ui/swing/overlay/IJCreationTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -38,10 +38,12 @@ /** * A JHotDraw {@link CreationTool} for ImageJ's Swing UI. - * + * * @author Lee Kamentsky */ -public class IJCreationTool extends CreationTool implements JHotDrawTool { +public class IJCreationTool extends CreationTool implements + JHotDrawTool +{ private final ImageDisplay display; private final JHotDrawAdapter adapter; @@ -65,9 +67,9 @@ protected Figure createFigure() { @Override protected void creationFinished(final Figure figure) { super.creationFinished(figure); - final JHotDrawService jHotDrawService = - getDisplay().getContext().getService(JHotDrawService.class); - jHotDrawService.linkOverlay((F)figure, getAdapter(), getDisplay()); + final JHotDrawService jHotDrawService = getDisplay().getContext() + .getService(JHotDrawService.class); + jHotDrawService.linkOverlay((F) figure, getAdapter(), getDisplay()); } // -- JHotDrawTool methods -- @@ -94,14 +96,14 @@ public void mouseClicked(MouseEvent evt) { if (!isLeftClick(evt)) return; super.mouseClicked(evt); } - + @Override public void mousePressed(MouseEvent evt) { if (!isLeftClick(evt)) return; super.mousePressed(evt); adapter.mouseDown(getDisplay(), evt.getX(), evt.getY()); } - + @Override public void mouseReleased(MouseEvent evt) { if (!isLeftClick(evt)) return; diff --git a/src/main/java/net/imagej/ui/swing/overlay/IJDelegationSelectionTool.java b/src/main/java/net/imagej/ui/swing/overlay/IJDelegationSelectionTool.java index b4a1f43..e295b3c 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/IJDelegationSelectionTool.java +++ b/src/main/java/net/imagej/ui/swing/overlay/IJDelegationSelectionTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,7 +35,7 @@ /** * A JHotDraw {@link DelegationSelectionTool} for ImageJ's Swing UI. - * + * * @author Johannes Schindelin */ public class IJDelegationSelectionTool extends DelegationSelectionTool diff --git a/src/main/java/net/imagej/ui/swing/overlay/JHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/JHotDrawAdapter.java index 87bcab9..af455e7 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/JHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/JHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -51,7 +51,7 @@ * merely by implementing this interface, it is encouraged to instead extend * {@link AbstractJHotDrawAdapter}, for convenience. *

- * + * * @author Lee Kamentsky * @author Curtis Rueden */ @@ -61,7 +61,7 @@ public interface JHotDrawAdapter extends ImageJPlugin, /** * Determines whether the adapter is designed to work with the given tool. - * + * * @param tool The tool in question. * @return True iff the adapter is compatible with the given tool. */ @@ -70,7 +70,7 @@ public interface JHotDrawAdapter extends ImageJPlugin, /** * Determines whether the adapter can handle a particular overlay, or overlay * / figure combination. - * + * * @param overlay - an overlay that might be editable * @param figure - a figure that will be either updated by the overlay or will * update the overlay. The figure can be null: this indicates that @@ -81,7 +81,7 @@ public interface JHotDrawAdapter extends ImageJPlugin, /** * Creates a new overlay. - * + * * @return an Overlay of the associated type in the default initial state */ Overlay createNewOverlay(); @@ -91,7 +91,7 @@ public interface JHotDrawAdapter extends ImageJPlugin, /** * Update the overlay to match the appearance of the figure - * + * * @param figure the figure that holds the current correct appearance * @param view view of the overlay that needs to be changed to bring it * in-sync with the figure. @@ -100,7 +100,7 @@ public interface JHotDrawAdapter extends ImageJPlugin, /** * Update the appearance of the figure to match the overlay - * + * * @param view view of the overlay to be represented by the figure * @param figure the figure that is to be made to look like the overlay */ diff --git a/src/main/java/net/imagej/ui/swing/overlay/JHotDrawService.java b/src/main/java/net/imagej/ui/swing/overlay/JHotDrawService.java index a9d2916..6fa1056 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/JHotDrawService.java +++ b/src/main/java/net/imagej/ui/swing/overlay/JHotDrawService.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -54,7 +54,7 @@ /** * The JHotDraw service manages the bidirectional linkage between ImageJ * {@link Overlay}s and JHotDraw {@link Figure}s. - * + * * @author Lee Kamentsky * @author Curtis Rueden */ @@ -79,7 +79,7 @@ public class JHotDrawService extends AbstractService implements ImageJService { /** * Gets the adapter associated with the given tool. - * + * * @param tool The tool for which a compatible adapter is needed. * @return the highest-priority adapter that supports the tool */ @@ -92,7 +92,7 @@ public JHotDrawAdapter getAdapter(final Tool tool) { /** * Gets the first available adapter for the given overlay. - * + * * @param overlay the overlay to adapt * @return the highest-priority adapter that supports the overlay */ @@ -102,7 +102,7 @@ public JHotDrawAdapter getAdapter(final Overlay overlay) { /** * Gets the first available adapter for the given overlay. - * + * * @param overlay the overlay to adapt * @param figure the figure to be associated with the overlay * @return the highest-priority adapter that supports the overlay adapted to @@ -119,7 +119,7 @@ public JHotDrawAdapter getAdapter(final Overlay overlay, /** * Gets all adapters capable of handling a given overlay. - * + * * @param overlay the overlay to adapt * @return a collection of all adapters capable of handling the overlay */ @@ -129,7 +129,7 @@ public ArrayList> getAdapters(final Overlay overlay) { /** * Gets all adapters capable of handling a given overlay/figure combination. - * + * * @param overlay the overlay to adapt * @param figure the figure to be associated with the overlay * @return collection of valid adapters @@ -137,8 +137,7 @@ public ArrayList> getAdapters(final Overlay overlay) { public ArrayList> getAdapters(final Overlay overlay, final Figure figure) { - final ArrayList> result = - new ArrayList<>(); + final ArrayList> result = new ArrayList<>(); for (final JHotDrawAdapter adapter : adapters()) { if (adapter.supports(overlay, figure)) result.add(adapter); } @@ -175,8 +174,8 @@ private List> adapters() { if (adapters == null) { // ask the plugin service for the list of available JHotDraw adapters @SuppressWarnings({ "rawtypes", "unchecked" }) - final List> instances = - (List) pluginService.createInstancesOfType(JHotDrawAdapter.class); + final List> instances = (List) pluginService + .createInstancesOfType(JHotDrawAdapter.class); adapters = instances; log.info("Found " + adapters.size() + " JHotDraw adapters."); } diff --git a/src/main/java/net/imagej/ui/swing/overlay/JHotDrawTool.java b/src/main/java/net/imagej/ui/swing/overlay/JHotDrawTool.java index 90c4de4..587162c 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/JHotDrawTool.java +++ b/src/main/java/net/imagej/ui/swing/overlay/JHotDrawTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -40,7 +40,7 @@ /** * A JHotDraw {@link Tool} (not a {@link org.scijava.tool.Tool}) with * some extra needed API methods. - * + * * @author Johannes Schindelin */ public interface JHotDrawTool extends Tool { diff --git a/src/main/java/net/imagej/ui/swing/overlay/LineJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/LineJHotDrawAdapter.java index 408f26e..7f6670b 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/LineJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/LineJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,7 +49,7 @@ /** * JHotDraw adapter for line overlays. - * + * * @author Lee Kamentsky * @author Barry DeZonia * @see SwingLineTool diff --git a/src/main/java/net/imagej/ui/swing/overlay/PointFigure.java b/src/main/java/net/imagej/ui/swing/overlay/PointFigure.java index d9692a2..a204b8f 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/PointFigure.java +++ b/src/main/java/net/imagej/ui/swing/overlay/PointFigure.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -48,7 +48,7 @@ /** * Implementation of a point as a JHotDraw figure. - * + * * @author Johannes Schindelin * @author Barry DeZonia */ @@ -175,8 +175,8 @@ public boolean contains(final Point2D.Double p) { } @Override - public void - setBounds(final Point2D.Double anchor, final Point2D.Double lead) + public void setBounds(final Point2D.Double anchor, + final Point2D.Double lead) { double dx = anchor.x - bounds.x; double dy = anchor.y - bounds.y; @@ -185,7 +185,7 @@ public boolean contains(final Point2D.Double p) { /** * Moves the Figure to a new location. - * + * * @param tx the transformation matrix. */ @Override @@ -288,5 +288,4 @@ public void draw(final Graphics2D g) { } } - } diff --git a/src/main/java/net/imagej/ui/swing/overlay/PointJHotDrawOverlay.java b/src/main/java/net/imagej/ui/swing/overlay/PointJHotDrawOverlay.java index 9796e9d..9fe4d75 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/PointJHotDrawOverlay.java +++ b/src/main/java/net/imagej/ui/swing/overlay/PointJHotDrawOverlay.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -44,7 +44,7 @@ /** * JHotDraw adapter for point tool. - * + * * @author Barry DeZonia * @see SwingPointTool */ diff --git a/src/main/java/net/imagej/ui/swing/overlay/PolygonFigure.java b/src/main/java/net/imagej/ui/swing/overlay/PolygonFigure.java index 9fae53c..2697744 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/PolygonFigure.java +++ b/src/main/java/net/imagej/ui/swing/overlay/PolygonFigure.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -38,7 +38,7 @@ /** * TODO - * + * * @author Johannes Schindelin */ public class PolygonFigure extends BezierFigure { diff --git a/src/main/java/net/imagej/ui/swing/overlay/PolygonJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/PolygonJHotDrawAdapter.java index 612abf9..7821303 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/PolygonJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/PolygonJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -52,7 +52,7 @@ /** * JHotDraw adapter for polygon/freehand overlays. - * + * * @author Lee Kamentsky * @author Barry DeZonia * @see SwingPolygonTool @@ -98,8 +98,7 @@ public Figure createDefaultFigure() { } @Override - public void updateOverlay(final BezierFigure figure, final OverlayView view) - { + public void updateOverlay(final BezierFigure figure, final OverlayView view) { super.updateOverlay(figure, view); final PolygonOverlay poverlay = downcastOverlay(view.getData()); final PolygonRegionOfInterest roi = poverlay.getRegionOfInterest(); diff --git a/src/main/java/net/imagej/ui/swing/overlay/PolygonNodeHandle.java b/src/main/java/net/imagej/ui/swing/overlay/PolygonNodeHandle.java index db5eca4..a217d5d 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/PolygonNodeHandle.java +++ b/src/main/java/net/imagej/ui/swing/overlay/PolygonNodeHandle.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -38,9 +38,9 @@ /** * The BezierFigure uses a BezierNodeHandle which can change the curve - * connecting vertices from a line to a Bezier curve. We subclass both - * the figure and the node handle to defeat this. - * + * connecting vertices from a line to a Bezier curve. We subclass both the + * figure and the node handle to defeat this. + * * @author Johannes Schindelin */ public class PolygonNodeHandle extends BezierNodeHandle { @@ -60,9 +60,9 @@ public void trackEnd(final Point anchor, final Point lead, final int modifiersEx) { // Remove the behavior associated with the shift keys - super.trackEnd(anchor, lead, modifiersEx & - ~(InputEvent.META_DOWN_MASK | InputEvent.CTRL_DOWN_MASK | - InputEvent.ALT_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); + super.trackEnd(anchor, lead, modifiersEx & ~(InputEvent.META_DOWN_MASK | + InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK | + InputEvent.SHIFT_DOWN_MASK)); } } diff --git a/src/main/java/net/imagej/ui/swing/overlay/PolylineFigure.java b/src/main/java/net/imagej/ui/swing/overlay/PolylineFigure.java index f624107..f4ddffa 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/PolylineFigure.java +++ b/src/main/java/net/imagej/ui/swing/overlay/PolylineFigure.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -38,7 +38,7 @@ /** * JHotDraw Figure for a multi-segmented line - * + * * @author Benjamin Nanes */ public class PolylineFigure extends BezierFigure { diff --git a/src/main/java/net/imagej/ui/swing/overlay/PolylineJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/PolylineJHotDrawAdapter.java index d2085e7..e4bf389 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/PolylineJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/PolylineJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,7 +49,7 @@ /** * JHotDraw adapter for multi-segmented lines - * + * * @author Benjamin Nanes */ @Plugin(type = JHotDrawAdapter.class, priority = SwingPolylineTool.PRIORITY) diff --git a/src/main/java/net/imagej/ui/swing/overlay/RectangleJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/RectangleJHotDrawAdapter.java index 3c8eb36..c608c8d 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/RectangleJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/RectangleJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,7 +49,7 @@ /** * JHotDraw adapter for rectangle overlays. - * + * * @author Lee Kamentsky * @author Grant Harris * @author Barry DeZonia @@ -94,8 +94,8 @@ public Figure createDefaultFigure() { } @Override - public void - updateFigure(final OverlayView view, final RectangleFigure figure) + public void updateFigure(final OverlayView view, + final RectangleFigure figure) { super.updateFigure(view, figure); final RectangleOverlay overlay = downcastOverlay(view.getData()); diff --git a/src/main/java/net/imagej/ui/swing/overlay/SwingOverlayManager.java b/src/main/java/net/imagej/ui/swing/overlay/SwingOverlayManager.java index 3cbe154..de5e32f 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/SwingOverlayManager.java +++ b/src/main/java/net/imagej/ui/swing/overlay/SwingOverlayManager.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -104,21 +104,20 @@ /** * Overlay Manager Swing UI - * + * * @author Barry DeZonia * @author Adam Fraser */ -public class SwingOverlayManager - extends JFrame - implements ActionListener, ItemListener +public class SwingOverlayManager extends JFrame implements ActionListener, + ItemListener { // -- constants -- - - //private static final long serialVersionUID = -6498169032123522303L; + + // private static final long serialVersionUID = -6498169032123522303L; // no longer supported - //private static final String ACTION_ADD = "add"; + // private static final String ACTION_ADD = "add"; private static final String ACTION_ADD_PARTICLES = "add particles"; private static final String ACTION_AND = "and"; private static final String ACTION_DELETE = "delete"; @@ -142,14 +141,14 @@ public class SwingOverlayManager private static final String ACTION_SORT = "sort"; private static final String ACTION_SPECIFY = "specify"; // no longer supported - //private static final String ACTION_UPDATE = "update"; + // private static final String ACTION_UPDATE = "update"; private static final String ACTION_XOR = "xor"; - + private static final String LAST_X = "lastXLocation"; private static final String LAST_Y = "lastYLocation"; // -- instance variables -- - + private final Context context; private final JList jlist; private final JCheckBox showAllCheckBox; @@ -179,16 +178,16 @@ public class SwingOverlayManager private boolean altDown = false; // -- constructor -- - + /** - * Creates a JList to list the overlays. + * Creates a JList to list the overlays. */ public SwingOverlayManager(final Context context) { this.context = context; context.inject(this); jlist = new JList<>(new OverlayListModel(overlayService.getOverlayInfo())); - //jlist.setCellRenderer(new OverlayRenderer()); + // jlist.setCellRenderer(new OverlayRenderer()); final JScrollPane listScroller = new JScrollPane(jlist); listScroller.setPreferredSize(new Dimension(250, 80)); @@ -199,10 +198,10 @@ public SwingOverlayManager(final Context context) { listPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); final JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new GridLayout(9,1,5,0)); + buttonPane.setLayout(new GridLayout(9, 1, 5, 0)); // NO LONGER SUPPORTING - //buttonPane.add(getAddButton()); - //buttonPane.add(getUpdateButton()); + // buttonPane.add(getAddButton()); + // buttonPane.add(getUpdateButton()); buttonPane.add(getDeleteButton()); buttonPane.add(getRenameButton()); buttonPane.add(getMeasureButton()); @@ -215,17 +214,17 @@ public SwingOverlayManager(final Context context) { final JPanel boolPane = new JPanel(); boolPane.setLayout(new BoxLayout(boolPane, BoxLayout.Y_AXIS)); - showAllCheckBox = new JCheckBox("Show All",false); - editModeCheckBox = new JCheckBox("Edit Mode",false); + showAllCheckBox = new JCheckBox("Show All", false); + editModeCheckBox = new JCheckBox("Edit Mode", false); boolPane.add(showAllCheckBox); boolPane.add(editModeCheckBox); showAllCheckBox.addItemListener(this); editModeCheckBox.addItemListener(this); - + final JPanel controlPanel = new JPanel(); controlPanel.setLayout(new BorderLayout()); - controlPanel.add(buttonPane,BorderLayout.CENTER); - controlPanel.add(boolPane,BorderLayout.SOUTH); + controlPanel.add(buttonPane, BorderLayout.CENTER); + controlPanel.add(boolPane, BorderLayout.SOUTH); final Container cp = this.getContentPane(); cp.add(listPanel, BorderLayout.CENTER); @@ -236,16 +235,16 @@ public SwingOverlayManager(final Context context) { setupCloseListener(); setupKeyListener(); restoreLocation(); - + pack(); - + eventService.subscribe(this); populateOverlayList(); } // -- public interface -- - + @Override public void actionPerformed(final ActionEvent e) { final String command = e.getActionCommand(); @@ -254,71 +253,47 @@ public void actionPerformed(final ActionEvent e) { if (command.equals(ACTION_ADD)) add(); */ - if (command.equals(ACTION_ADD_PARTICLES)) - addParticles(); - else if (command.equals(ACTION_AND)) - and(); - else if (command.equals(ACTION_DELETE)) - delete(); - else if (command.equals(ACTION_DESELECT)) - deselect(); - else if (command.equals(ACTION_DIVIDE)) - divide(); - else if (command.equals(ACTION_DRAW)) - draw(); - else if (command.equals(ACTION_FILL)) - fill(); - else if (command.equals(ACTION_FLATTEN)) - flatten(); - else if (command.equals(ACTION_HELP)) - help(); - else if (command.equals(ACTION_LIST)) - getList(); - else if (command.equals(ACTION_MEASURE)) - measure(); - else if (command.equals(ACTION_MULTI_MEASURE)) - multiMeasure(); - else if (command.equals(ACTION_MULTI_PLOT)) - multiPlot(); - else if (command.equals(ACTION_OPEN)) - open(); - else if (command.equals(ACTION_OPTIONS)) - options(); - else if (command.equals(ACTION_OR)) - or(); - else if (command.equals(ACTION_PROPERTIES)) - properties(); - else if (command.equals(ACTION_REMOVE_SLICE_INFO)) - removeSliceInfo(); - else if (command.equals(ACTION_RENAME)) - rename(); - else if (command.equals(ACTION_SAVE)) - save(); - else if (command.equals(ACTION_SORT)) - sort(); - else if (command.equals(ACTION_SPECIFY)) - specify(); + if (command.equals(ACTION_ADD_PARTICLES)) addParticles(); + else if (command.equals(ACTION_AND)) and(); + else if (command.equals(ACTION_DELETE)) delete(); + else if (command.equals(ACTION_DESELECT)) deselect(); + else if (command.equals(ACTION_DIVIDE)) divide(); + else if (command.equals(ACTION_DRAW)) draw(); + else if (command.equals(ACTION_FILL)) fill(); + else if (command.equals(ACTION_FLATTEN)) flatten(); + else if (command.equals(ACTION_HELP)) help(); + else if (command.equals(ACTION_LIST)) getList(); + else if (command.equals(ACTION_MEASURE)) measure(); + else if (command.equals(ACTION_MULTI_MEASURE)) multiMeasure(); + else if (command.equals(ACTION_MULTI_PLOT)) multiPlot(); + else if (command.equals(ACTION_OPEN)) open(); + else if (command.equals(ACTION_OPTIONS)) options(); + else if (command.equals(ACTION_OR)) or(); + else if (command.equals(ACTION_PROPERTIES)) properties(); + else if (command.equals(ACTION_REMOVE_SLICE_INFO)) removeSliceInfo(); + else if (command.equals(ACTION_RENAME)) rename(); + else if (command.equals(ACTION_SAVE)) save(); + else if (command.equals(ACTION_SORT)) sort(); + else if (command.equals(ACTION_SPECIFY)) specify(); /* else if (command.equals(ACTION_UPDATE)) update(); */ - else if (command.equals(ACTION_XOR)) - xor(); + else if (command.equals(ACTION_XOR)) xor(); } // -- private helpers for overlay list maintenance -- - private class OverlayListModel extends AbstractListModel { - //private static final long serialVersionUID = 7941252533859436640L; + // private static final long serialVersionUID = 7941252533859436640L; private OverlayInfoList overlayInfoList; - + public OverlayListModel(OverlayInfoList list) { overlayInfoList = list; } - + @Override public OverlayInfo getElementAt(final int index) { return overlayInfoList.getOverlayInfo(index); @@ -352,7 +327,7 @@ private void populateOverlayList() { } jlist.updateUI(); } - + /* private class OverlayRenderer extends DefaultListCellRenderer { @@ -372,10 +347,10 @@ public Component getListCellRendererComponent(final JList list, final Overlay overlay = (Overlay) value; // TODO: create overlay thumbnail from overlay final ImageIcon icon = iconTable.get(overlay); -// if (icon == null) { -// icon = new ImageIcon(...); -// iconTable.put(overlay, ImageIcon); -// } + // if (icon == null) { + // icon = new ImageIcon(...); + // iconTable.put(overlay, ImageIcon); + // } label.setIcon(icon); } else { @@ -392,21 +367,22 @@ public Component getListCellRendererComponent(final JList list, @EventHandler protected void onEvent(final OverlayCreatedEvent event) { - //System.out.println("\tCREATED: " + event.toString()); + // System.out.println("\tCREATED: " + event.toString()); overlayService.getOverlayInfo().addOverlay(event.getObject()); jlist.updateUI(); } @EventHandler protected void onEvent(final OverlayDeletedEvent event) { - //System.out.println("\tDELETED: " + event.toString()); + // System.out.println("\tDELETED: " + event.toString()); Overlay overlay = event.getObject(); overlayService.getOverlayInfo().deleteOverlay(overlay); - int[] newSelectedIndices = overlayService.getOverlayInfo().selectedIndices(); + int[] newSelectedIndices = overlayService.getOverlayInfo() + .selectedIndices(); jlist.setSelectedIndices(newSelectedIndices); jlist.updateUI(); } - + /* // Update when a display is activated. @EventHandler @@ -424,7 +400,8 @@ protected void onEvent(final DataViewSelectionEvent event) { // Select or deselect the corresponding overlay in the list final Overlay overlay = (Overlay) event.getView().getData(); final int overlayIndex = overlayService.getOverlayInfo().findIndex(overlay); - final OverlayInfo overlayInfo = overlayService.getOverlayInfo().getOverlayInfo(overlayIndex); + final OverlayInfo overlayInfo = overlayService.getOverlayInfo() + .getOverlayInfo(overlayIndex); overlayInfo.setSelected(event.isSelected()); /* old way if (event.isSelected()) { @@ -464,23 +441,23 @@ protected void onKeyPressedEvent(KyPressedEvent ev) { if (key == KeyCode.DELETE) delete(); } */ - + @SuppressWarnings("unused") @EventHandler protected void onEvent(OverlayRestructuredEvent event) { - //System.out.println("restructured"); + // System.out.println("restructured"); jlist.updateUI(); } @SuppressWarnings("unused") @EventHandler protected void onEvent(OverlayUpdatedEvent event) { - //System.out.println("updated"); + // System.out.println("updated"); jlist.updateUI(); } // -- private helpers that implement overlay interaction commands -- - + /* no longer supported private void add() { final ImageDisplay activeDisplay = @@ -496,32 +473,36 @@ private void add() { jlist.updateUI(); } */ - + private void addParticles() { JOptionPane.showMessageDialog(this, "unimplemented"); } - + private void and() { makeCompositeOverlay(CompositeOverlay.Operation.AND); } - + private void delete() { if (overlayService.getOverlayInfo().getOverlayInfoCount() == 0) return; List overlaysToDelete = new LinkedList<>(); - final int[] selectedIndices = overlayService.getOverlayInfo().selectedIndices(); + final int[] selectedIndices = overlayService.getOverlayInfo() + .selectedIndices(); if (selectedIndices.length == 0) { - final int result = - JOptionPane.showConfirmDialog( - this, "Delete all overlays?", "Delete All", JOptionPane.YES_NO_OPTION); + final int result = JOptionPane.showConfirmDialog(this, + "Delete all overlays?", "Delete All", JOptionPane.YES_NO_OPTION); if (result != JOptionPane.YES_OPTION) return; - for (int i = 0; i < overlayService.getOverlayInfo().getOverlayInfoCount(); i++) { - overlaysToDelete.add(overlayService.getOverlayInfo().getOverlayInfo(i).getOverlay()); + for (int i = 0; i < overlayService.getOverlayInfo() + .getOverlayInfoCount(); i++) + { + overlaysToDelete.add(overlayService.getOverlayInfo().getOverlayInfo(i) + .getOverlay()); } } else { for (int i = 0; i < selectedIndices.length; i++) { int index = selectedIndices[i]; - overlaysToDelete.add(overlayService.getOverlayInfo().getOverlayInfo(index).getOverlay()); + overlaysToDelete.add(overlayService.getOverlayInfo().getOverlayInfo( + index).getOverlay()); } } for (Overlay overlay : overlaysToDelete) { @@ -531,37 +512,35 @@ private void delete() { overlayService.removeOverlay(overlay); } } - + private void deselect() { overlayService.getOverlayInfo().deselectAll(); jlist.clearSelection(); } - + /** * Takes the currently selected CompositeOverlay and turns it into its - * constituent overlays. The CompositeOverlay is deleted. It does one layer - * of division (it is not a deep division). + * constituent overlays. The CompositeOverlay is deleted. It does one layer of + * division (it is not a deep division). */ private void divide() { List overlays = overlayService.getOverlayInfo().selectedOverlays(); int i = 0; while (i < overlays.size()) { Overlay o = overlays.get(i); - if (! (o instanceof CompositeOverlay)) - overlays.remove(i); - else - i++; + if (!(o instanceof CompositeOverlay)) overlays.remove(i); + else i++; } if (overlays.size() == 0) { - JOptionPane.showMessageDialog( - this, "One or more composite overlays must be selected"); + JOptionPane.showMessageDialog(this, + "One or more composite overlays must be selected"); return; } for (Overlay o : overlays) { overlayService.divideCompositeOverlay((CompositeOverlay) o); } } - + private void draw() { ChannelCollection channels = getChannels(); List selected = overlayService.getOverlayInfo().selectedOverlays(); @@ -579,90 +558,94 @@ private void fill() { overlayService.fillOverlay(o, disp, channels); } } - + private void flatten() { - final ImageDisplay imageDisplay = - imageDisplayService.getActiveImageDisplay(); + final ImageDisplay imageDisplay = imageDisplayService + .getActiveImageDisplay(); if (imageDisplay == null) return; // FIXME: Migrate Flatten functionality into a core service API. commandService.run("net.imagej.plugins.commands.display.Flatten", true, "display", imageDisplay); } - + private void help() { try { - final URL url = - new URL("https://imagej.net/software/imagej2/implementation-notes#image--overlay--overlay-manager"); + final URL url = new URL( + "https://imagej.net/software/imagej2/implementation-notes#image--overlay--overlay-manager"); platformService.open(url); - } catch (IOException e) { + } + catch (IOException e) { // do nothing } } - + private void getList() { JOptionPane.showMessageDialog(this, "unimplemented"); } - + private void measure() { JOptionPane.showMessageDialog(this, "unimplemented"); } - + private void multiMeasure() { JOptionPane.showMessageDialog(this, "unimplemented"); } - + private void multiPlot() { JOptionPane.showMessageDialog(this, "unimplemented"); } - + private void open() { JOptionPane.showMessageDialog(this, "unimplemented"); } - + private void options() { JOptionPane.showMessageDialog(this, "unimplemented"); } - + private void or() { makeCompositeOverlay(CompositeOverlay.Operation.OR); } - + private void properties() { int[] selected = overlayService.getOverlayInfo().selectedIndices(); if (selected.length == 0) { - JOptionPane.showMessageDialog(this, "This command requires one or more selections"); + JOptionPane.showMessageDialog(this, + "This command requires one or more selections"); return; } // else one or more selections exist runPropertiesPlugin(); } - + private void removeSliceInfo() { JOptionPane.showMessageDialog(this, "unimplemented"); } - + private void rename() { - final int[] selectedIndices = overlayService.getOverlayInfo().selectedIndices(); + final int[] selectedIndices = overlayService.getOverlayInfo() + .selectedIndices(); if (selectedIndices.length < 1) { JOptionPane.showMessageDialog(this, "Must select an overlay to rename"); return; } if (selectedIndices.length > 1) { - JOptionPane.showMessageDialog(this, "Cannot rename multiple overlays simultaneously"); + JOptionPane.showMessageDialog(this, + "Cannot rename multiple overlays simultaneously"); return; } - final OverlayInfo info = overlayService.getOverlayInfo().getOverlayInfo(selectedIndices[0]); + final OverlayInfo info = overlayService.getOverlayInfo().getOverlayInfo( + selectedIndices[0]); if (info == null) return; // TODO - UI agnostic way here - final String name = JOptionPane.showInputDialog(this, "Enter new name for overlay"); - if ((name == null) || (name.length() == 0)) - info.getOverlay().setName(null); - else - info.getOverlay().setName(name); + final String name = JOptionPane.showInputDialog(this, + "Enter new name for overlay"); + if ((name == null) || (name.length() == 0)) info.getOverlay().setName(null); + else info.getOverlay().setName(name); jlist.updateUI(); } - + private void save() { JOptionPane.showMessageDialog(this, "unimplemented"); /* @@ -672,7 +655,7 @@ private void save() { JOptionPane.showMessageDialog(this, "Cannot save - one or more overlays must be selected first"); return; } - + final JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Save Overlay to file ..."); chooser.setAcceptAllFileFilterUsed(false); @@ -689,7 +672,7 @@ private void save() { basename.toLowerCase().endsWith(".zip")) { basename = basename.substring(0,basename.length()-4); } - + // one roi selected if (selectedIndices.length == 1) { // save overlay in its own user named .ovl file @@ -704,24 +687,24 @@ private void save() { } */ } - + private void sort() { overlayService.getOverlayInfo().sort(); int[] newSelections = overlayService.getOverlayInfo().selectedIndices(); jlist.setSelectedIndices(newSelections); jlist.updateUI(); } - + private void specify() { - final ImageDisplay imageDisplay = - imageDisplayService.getActiveImageDisplay(); + final ImageDisplay imageDisplay = imageDisplayService + .getActiveImageDisplay(); if (imageDisplay == null) return; // FIXME: Migrate SelectionSpecify functionality into OverlayService API. commandService.run("net.imagej.plugins.commands.overlay.SelectionSpecify", true, "display", imageDisplay); } - + /* * old functionality : now that all overlays always tracked this no longer * makes sense @@ -735,14 +718,14 @@ private void update() { "Exactly one item must be selected"); return; } - + final Overlay overlay = getActiveOverlay(); if (overlay == null) { JOptionPane.showMessageDialog(this, "An overlay must be selected in the current view"); return; } - + final int index = infoList.findIndex(overlay); if (index != -1) { // already in list @@ -756,16 +739,18 @@ private void update() { jlist.updateUI(); } */ - + private void xor() { makeCompositeOverlay(CompositeOverlay.Operation.XOR); } - + // -- private helpers for hotkey handling -- private void setupKeyListener() { - //KeyListener listener = new AWTKeyEventDispatcher(fakeDisplay, eventService); + // KeyListener listener = new AWTKeyEventDispatcher(fakeDisplay, + // eventService); final KeyListener listener = new KeyListener() { + @Override public void keyPressed(KeyEvent e) { altDown = e.isAltDown() || e.isAltGraphDown(); @@ -776,15 +761,17 @@ public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_F) flatten(); if (e.getKeyCode() == KeyEvent.VK_DELETE) delete(); } + @Override public void keyReleased(KeyEvent e) { altDown = e.isAltDown() || e.isAltGraphDown(); shiftDown = e.isShiftDown(); } + @Override public void keyTyped(KeyEvent e) { /* do nothing */ } }; - + final Stack stack = new Stack<>(); stack.push(this); while (!stack.empty()) { @@ -799,7 +786,7 @@ public void keyTyped(KeyEvent e) { /* do nothing */ } } // -- private helpers for frame location -- - + /** Persists the application frame's current location. */ private void saveLocation() { Prefs.put(getClass(), LAST_X, getLocation().x); @@ -812,9 +799,10 @@ private void restoreLocation() { final int lastY = Prefs.getInt(getClass(), LAST_Y, 0); setLocation(lastX, lastY); } - + private void setupCloseListener() { addWindowListener(new WindowAdapter() { + @Override public void windowClosing(WindowEvent e) { // Remember screen location of window for next time @@ -826,14 +814,16 @@ public void windowClosing(WindowEvent e) { // -- private helpers for list selection event listening -- private void setupListSelectionListener() { - final ListSelectionListener - listSelectionListener = new ListSelectionListener() { + final ListSelectionListener listSelectionListener = + new ListSelectionListener() + { + @Override public void valueChanged(final ListSelectionEvent listSelectionEvent) { if (selecting) return; selecting = true; - final ImageDisplay display = - imageDisplayService.getActiveImageDisplay(); + final ImageDisplay display = imageDisplayService + .getActiveImageDisplay(); if (display == null) return; final JList list = (JList) listSelectionEvent.getSource(); final List selectionValues = list.getSelectedValuesList(); @@ -860,10 +850,9 @@ public void valueChanged(final ListSelectionEvent listSelectionEvent) { } // -- private helpers for constructing popup menu -- - + private JPopupMenu getPopupMenu() { - if (popupMenu == null) - popupMenu = createPopupMenu(); + if (popupMenu == null) popupMenu = createPopupMenu(); return popupMenu; } @@ -886,7 +875,7 @@ private JPopupMenu createPopupMenu() { menu.add(getOptionsMenuItem()); return menu; } - + private JMenuItem getAddParticlesMenuItem() { final JMenuItem item; item = new JMenuItem("Add Particles"); @@ -894,7 +883,7 @@ private JMenuItem getAddParticlesMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getAndMenuItem() { final JMenuItem item; item = new JMenuItem("AND"); @@ -902,7 +891,7 @@ private JMenuItem getAndMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getHelpMenuItem() { final JMenuItem item; item = new JMenuItem("Help"); @@ -910,7 +899,7 @@ private JMenuItem getHelpMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getListMenuItem() { final JMenuItem item; item = new JMenuItem("List"); @@ -918,7 +907,7 @@ private JMenuItem getListMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getMultiMeasureMenuItem() { final JMenuItem item; item = new JMenuItem("Multi Measure"); @@ -926,7 +915,7 @@ private JMenuItem getMultiMeasureMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getMultiPlotMenuItem() { final JMenuItem item; item = new JMenuItem("Multi Plot"); @@ -934,7 +923,7 @@ private JMenuItem getMultiPlotMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getOpenMenuItem() { final JMenuItem item; item = new JMenuItem("Open..."); @@ -942,7 +931,7 @@ private JMenuItem getOpenMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getOptionsMenuItem() { final JMenuItem item; item = new JMenuItem("Options..."); @@ -950,7 +939,7 @@ private JMenuItem getOptionsMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getOrMenuItem() { final JMenuItem item; item = new JMenuItem("OR (Combine)"); @@ -958,7 +947,7 @@ private JMenuItem getOrMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getRemoveSliceInfoMenuItem() { final JMenuItem item; item = new JMenuItem("Remove Slice Info"); @@ -966,7 +955,7 @@ private JMenuItem getRemoveSliceInfoMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getSaveMenuItem() { final JMenuItem item; item = new JMenuItem("Save..."); @@ -974,7 +963,7 @@ private JMenuItem getSaveMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getSortMenuItem() { final JMenuItem item; item = new JMenuItem("Sort"); @@ -982,7 +971,7 @@ private JMenuItem getSortMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getSpecifyMenuItem() { final JMenuItem item; item = new JMenuItem("Specify..."); @@ -990,7 +979,7 @@ private JMenuItem getSpecifyMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getDivideMenuItem() { final JMenuItem item; item = new JMenuItem("Divide"); @@ -998,7 +987,7 @@ private JMenuItem getDivideMenuItem() { item.addActionListener(this); return item; } - + private JMenuItem getXorMenuItem() { final JMenuItem item; item = new JMenuItem("XOR"); @@ -1006,7 +995,7 @@ private JMenuItem getXorMenuItem() { item.addActionListener(this); return item; } - + // -- private helpers to implement main pane button controls -- /* no longer supported @@ -1017,76 +1006,81 @@ private JButton getAddButton() { return button; } */ - + private JButton getDeleteButton() { final JButton button = new JButton("Delete"); button.setActionCommand(ACTION_DELETE); button.addActionListener(this); return button; } - + private JButton getDeselectButton() { final JButton button = new JButton("Deselect"); button.setActionCommand(ACTION_DESELECT); button.addActionListener(this); return button; } - + private JButton getDrawButton() { final JButton button = new JButton("Draw"); button.setActionCommand(ACTION_DRAW); button.addActionListener(this); return button; } - + private JButton getFillButton() { final JButton button = new JButton("Fill"); button.setActionCommand(ACTION_FILL); button.addActionListener(this); return button; } - + private JButton getFlattenButton() { final JButton button = new JButton("Flatten [f]"); button.setActionCommand(ACTION_FLATTEN); button.addActionListener(this); return button; } - + private JButton getMeasureButton() { final JButton button = new JButton("Measure"); button.setActionCommand(ACTION_MEASURE); button.addActionListener(this); return button; } - + private JButton getMoreButton() { - final JButton button = new JButton("More "+'\u00bb'); + final JButton button = new JButton("More " + '\u00bb'); button.addMouseListener(new MouseListener() { + @Override public void mouseClicked(MouseEvent e) { getPopupMenu().show(e.getComponent(), e.getX(), e.getY()); } + @Override public void mouseEntered(MouseEvent evt) { /* do nothing */ } + @Override public void mouseExited(MouseEvent evt) { /* do nothing */ } + @Override public void mousePressed(MouseEvent evt) { /* do nothing */ } + @Override public void mouseReleased(MouseEvent evt) { /* do nothing */ } - + }); return button; } - + private JButton getPropertiesButton() { final JButton button = new JButton("Properties..."); button.setActionCommand(ACTION_PROPERTIES); button.addActionListener(this); return button; } - + private JButton getRenameButton() { final JButton button = new JButton("Rename..."); button.setActionCommand(ACTION_RENAME); @@ -1102,32 +1096,31 @@ private JButton getUpdateButton() { return button; } */ - + // -- private helpers to change state when checkboxes change -- // TODO - + @Override public void itemStateChanged(ItemEvent evt) { final boolean selected = (evt.getStateChange() == ItemEvent.SELECTED); if (evt.getSource() == showAllCheckBox) { - //System.out.println("show all is now "+selected); + // System.out.println("show all is now "+selected); } if (evt.getSource() == editModeCheckBox) { - //System.out.println("edit mode is now "+selected); + // System.out.println("edit mode is now "+selected); // link both checkboxes in selected case - if (selected) - showAllCheckBox.setSelected(true); + if (selected) showAllCheckBox.setSelected(true); } } // -- private helpers for TODO XXXX -- - + // TODO - assumes first selected overlay view is the only one. bad? @SuppressWarnings("unused") private Overlay getActiveOverlay() { - final ImageDisplay activeDisplay = - imageDisplayService.getActiveImageDisplay(); + final ImageDisplay activeDisplay = imageDisplayService + .getActiveImageDisplay(); if (activeDisplay == null) return null; final List views = activeDisplay; for (DataView view : views) { @@ -1136,10 +1129,11 @@ private Overlay getActiveOverlay() { } return null; } - + private void runPropertiesPlugin() { final Map inputMap = new HashMap<>(); - inputMap.put("overlays", overlayService.getOverlayInfo().selectedOverlays()); + inputMap.put("overlays", overlayService.getOverlayInfo() + .selectedOverlays()); // FIXME: Migrate OverlayProperties functionality into OverlayService API. commandService.run( "net.imagej.plugins.commands.overlay.SelectedManagerOverlayProperties", @@ -1151,16 +1145,17 @@ private ChannelCollection getChannels() { if (altDown) return opts.getBgValues(); return opts.getFgValues(); } - + private void makeCompositeOverlay(CompositeOverlay.Operation op) { ImageDisplay imageDisplay = imageDisplayService.getActiveImageDisplay(); if (imageDisplay == null) return; List overlays = overlayService.getOverlayInfo().selectedOverlays(); - if (overlays.size() == 0) overlays = overlayService.getOverlays(imageDisplay); + if (overlays.size() == 0) overlays = overlayService.getOverlays( + imageDisplay); if (overlays.size() < 2) { JOptionPane.showMessageDialog(this, - "This command only works with 2 or more overlays"); - return; + "This command only works with 2 or more overlays"); + return; } // else overlays.size() >= 2 CompositeOverlay newOverlay = new CompositeOverlay(context); @@ -1169,5 +1164,5 @@ private void makeCompositeOverlay(CompositeOverlay.Operation op) { imageDisplay.display(newOverlay); imageDisplay.update(); } - + } diff --git a/src/main/java/net/imagej/ui/swing/overlay/ThresholdFigure.java b/src/main/java/net/imagej/ui/swing/overlay/ThresholdFigure.java index f52cfc3..83f87d0 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/ThresholdFigure.java +++ b/src/main/java/net/imagej/ui/swing/overlay/ThresholdFigure.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -51,7 +51,7 @@ /** * Implementation of JHotDraw Figure that can display a {@link ThresholdOverlay} - * + * * @author Barry DeZonia */ public class ThresholdFigure extends AbstractAttributedFigure implements @@ -65,7 +65,7 @@ public class ThresholdFigure extends AbstractAttributedFigure implements private final ThresholdOverlay overlay; private final Rectangle2D.Double rect; private double[] tmpPos; - + public ThresholdFigure(ImageDisplay display, Dataset dataset, ThresholdOverlay overlay) { @@ -79,7 +79,7 @@ public ThresholdFigure(ImageDisplay display, Dataset dataset, set(AttributeKeys.FILL_COLOR, Color.DARK_GRAY); // always have a color set overlay.setFigure(this); } - + @Override public boolean contains(Point2D.Double pt) { int d = dataset.numDimensions(); @@ -127,12 +127,12 @@ public Double getStartPoint() { public Double getEndPoint() { return new Double(dataset.max(0), dataset.max(1)); } - + @Override public Rectangle2D.Double getDrawingArea() { return new Rectangle2D.Double(0, 0, dataset.max(0), dataset.max(1)); } - + @Override public void setBounds(Double anchor, Double lead) { // do nothing diff --git a/src/main/java/net/imagej/ui/swing/overlay/ThresholdJHotDrawAdapter.java b/src/main/java/net/imagej/ui/swing/overlay/ThresholdJHotDrawAdapter.java index d98a1ec..4496315 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/ThresholdJHotDrawAdapter.java +++ b/src/main/java/net/imagej/ui/swing/overlay/ThresholdJHotDrawAdapter.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -47,7 +47,7 @@ /** * JHotDraw adapter for threshold overlays. - * + * * @author Barry DeZonia * @see SwingPolygonTool */ diff --git a/src/main/java/net/imagej/ui/swing/overlay/ToolDelegator.java b/src/main/java/net/imagej/ui/swing/overlay/ToolDelegator.java index 7aa9756..4374612 100644 --- a/src/main/java/net/imagej/ui/swing/overlay/ToolDelegator.java +++ b/src/main/java/net/imagej/ui/swing/overlay/ToolDelegator.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -44,7 +44,7 @@ /** * TODO - * + * * @author Johannes Schindelin */ public class ToolDelegator extends AbstractTool { @@ -235,9 +235,8 @@ protected boolean maybeSwitchTool(final MouseEvent event) { JHotDrawTool tool = creationTool; final DrawingView view = getView(); if (view != null && view.isEnabled()) { - if (view.findHandle(anchor) != null || - (view.findFigure(anchor) != null && view.findFigure(anchor) - .isSelectable())) + if (view.findHandle(anchor) != null || (view.findFigure(anchor) != null && + view.findFigure(anchor).isSelectable())) { if (selection) tool = selectionTool; else tool = null; diff --git a/src/main/java/net/imagej/ui/swing/sdi/viewer/SwingSdiImageDisplayViewer.java b/src/main/java/net/imagej/ui/swing/sdi/viewer/SwingSdiImageDisplayViewer.java index d3f7ee1..863425e 100644 --- a/src/main/java/net/imagej/ui/swing/sdi/viewer/SwingSdiImageDisplayViewer.java +++ b/src/main/java/net/imagej/ui/swing/sdi/viewer/SwingSdiImageDisplayViewer.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -42,13 +42,14 @@ /** * Single Document Interface implementation of Swing image display viewer. The * SDI display is housed in a {@link JFrame}. - * + * * @author Curtis Rueden * @author Lee Kamentsky * @see SwingImageDisplayViewer */ @Plugin(type = DisplayViewer.class) -public class SwingSdiImageDisplayViewer extends AbstractSwingImageDisplayViewer +public class SwingSdiImageDisplayViewer extends + AbstractSwingImageDisplayViewer { // -- DisplayViewer methods -- diff --git a/src/main/java/net/imagej/ui/swing/tools/SwingAngleTool.java b/src/main/java/net/imagej/ui/swing/tools/SwingAngleTool.java index 6b1d1aa..8fb7bdd 100644 --- a/src/main/java/net/imagej/ui/swing/tools/SwingAngleTool.java +++ b/src/main/java/net/imagej/ui/swing/tools/SwingAngleTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,7 +35,7 @@ /** * Swing/JHotDraw implementation of angle tool. - * + * * @author Lee Kamentsky * @author Barry DeZonia * @see net.imagej.ui.swing.overlay.AngleJHotDrawAdapter diff --git a/src/main/java/net/imagej/ui/swing/tools/SwingEllipseTool.java b/src/main/java/net/imagej/ui/swing/tools/SwingEllipseTool.java index 1d92389..a91438d 100644 --- a/src/main/java/net/imagej/ui/swing/tools/SwingEllipseTool.java +++ b/src/main/java/net/imagej/ui/swing/tools/SwingEllipseTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,7 +35,7 @@ /** * Swing/JHotDraw implementation of ellipse tool. - * + * * @author Lee Kamentsky * @author Barry DeZonia * @see net.imagej.ui.swing.overlay.EllipseJHotDrawAdapter diff --git a/src/main/java/net/imagej/ui/swing/tools/SwingLineTool.java b/src/main/java/net/imagej/ui/swing/tools/SwingLineTool.java index d692f5c..0af65d1 100644 --- a/src/main/java/net/imagej/ui/swing/tools/SwingLineTool.java +++ b/src/main/java/net/imagej/ui/swing/tools/SwingLineTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,7 +35,7 @@ /** * Swing/JHotDraw implementation of line tool. - * + * * @author Lee Kamentsky * @author Barry DeZonia * @see net.imagej.ui.swing.overlay.LineJHotDrawAdapter diff --git a/src/main/java/net/imagej/ui/swing/tools/SwingPointTool.java b/src/main/java/net/imagej/ui/swing/tools/SwingPointTool.java index 5d8f755..d7160c3 100644 --- a/src/main/java/net/imagej/ui/swing/tools/SwingPointTool.java +++ b/src/main/java/net/imagej/ui/swing/tools/SwingPointTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -36,7 +36,7 @@ /** * Swing/JHotDraw implementation of point tool. - * + * * @author Barry DeZonia * @see net.imagej.ui.swing.overlay.PointJHotDrawOverlay */ diff --git a/src/main/java/net/imagej/ui/swing/tools/SwingPolygonTool.java b/src/main/java/net/imagej/ui/swing/tools/SwingPolygonTool.java index d9e363f..0338622 100644 --- a/src/main/java/net/imagej/ui/swing/tools/SwingPolygonTool.java +++ b/src/main/java/net/imagej/ui/swing/tools/SwingPolygonTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,7 +35,7 @@ /** * Swing/JHotDraw implementation of polygon/freehand tool. - * + * * @author Lee Kamentsky * @author Barry DeZonia * @see net.imagej.ui.swing.overlay.PolygonJHotDrawAdapter diff --git a/src/main/java/net/imagej/ui/swing/tools/SwingPolylineTool.java b/src/main/java/net/imagej/ui/swing/tools/SwingPolylineTool.java index 5399386..334ee3f 100644 --- a/src/main/java/net/imagej/ui/swing/tools/SwingPolylineTool.java +++ b/src/main/java/net/imagej/ui/swing/tools/SwingPolylineTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,12 +35,11 @@ /** * Swing/JHotDraw implementation of multi-segmented line tool. - * + * * @author Benjamin Nanes */ -@Plugin(type = Tool.class, name = "Polyline", - description = "Polyline overlays", iconPath = "/icons/tools/polyline.png", - priority = SwingPolylineTool.PRIORITY) +@Plugin(type = Tool.class, name = "Polyline", description = "Polyline overlays", + iconPath = "/icons/tools/polyline.png", priority = SwingPolylineTool.PRIORITY) public class SwingPolylineTool extends AbstractTool { public static final double PRIORITY = SwingLineTool.PRIORITY - 1; diff --git a/src/main/java/net/imagej/ui/swing/tools/SwingRectangleTool.java b/src/main/java/net/imagej/ui/swing/tools/SwingRectangleTool.java index 20ec08e..0e5e17d 100644 --- a/src/main/java/net/imagej/ui/swing/tools/SwingRectangleTool.java +++ b/src/main/java/net/imagej/ui/swing/tools/SwingRectangleTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -35,15 +35,14 @@ /** * Swing/JHotDraw implementation of rectangle tool. - * + * * @author Lee Kamentsky * @author Grant Harris * @author Barry DeZonia * @see net.imagej.ui.swing.overlay.RectangleJHotDrawAdapter */ @Plugin(type = Tool.class, name = "Rectangle", - description = "Rectangular overlays", - iconPath = "/icons/tools/rectangle.png", + description = "Rectangular overlays", iconPath = "/icons/tools/rectangle.png", priority = SwingRectangleTool.PRIORITY) public class SwingRectangleTool extends AbstractTool { diff --git a/src/main/java/net/imagej/ui/swing/tools/SwingTextTool.java b/src/main/java/net/imagej/ui/swing/tools/SwingTextTool.java index 0e1125f..57ef7f8 100644 --- a/src/main/java/net/imagej/ui/swing/tools/SwingTextTool.java +++ b/src/main/java/net/imagej/ui/swing/tools/SwingTextTool.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -36,7 +36,7 @@ /** * Swing/JHotDraw implementation of text tool. - * + * * @author Curtis Rueden */ @Plugin(type = Tool.class, name = "Text", description = "Text tool", diff --git a/src/main/java/net/imagej/ui/swing/updater/ConflictDialog.java b/src/main/java/net/imagej/ui/swing/updater/ConflictDialog.java index aba8130..0be9417 100644 --- a/src/main/java/net/imagej/ui/swing/updater/ConflictDialog.java +++ b/src/main/java/net/imagej/ui/swing/updater/ConflictDialog.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -54,8 +54,9 @@ import net.imagej.updater.Conflicts.Resolution; /** - * This dialog lists conflicts and let's the user choose how to resolve (or ignore) them. - * + * This dialog lists conflicts and let's the user choose how to resolve (or + * ignore) them. + * * @author Johannes Schindelin */ @SuppressWarnings("serial") @@ -96,7 +97,8 @@ public ConflictDialog(final UpdaterFrame owner, final String title) { final JPanel buttons = new JPanel(); ok = SwingTools.button("OK", "Apply resolutions [Enter]", this, buttons); cancel = SwingTools.button("Cancel", "Dismiss [Esc]", this, buttons); - buttons.setMaximumSize(buttons.getPreferredSize()); // do not allow vertical resizing + buttons.setMaximumSize(buttons.getPreferredSize()); // do not allow vertical + // resizing rootPanel.add(buttons); // do not show, right now @@ -114,8 +116,7 @@ public ConflictDialog(final UpdaterFrame owner, final String title) { @Override public void windowClosing(final WindowEvent e) { updateConflictList(); - if (conflictList.size() > 0) - wasCanceled = true; + if (conflictList.size() > 0) wasCanceled = true; } }); } @@ -161,7 +162,8 @@ protected void listIssues() { for (final Conflict conflict : conflictList) { maybeAddSeparator(); - newText(conflict.getSeverity().toString() + ": ", conflict.isError() ? red : normal); + newText(conflict.getSeverity().toString() + ": ", conflict.isError() ? red + : normal); final String filename = conflict.getFilename(); if (filename != null) addText(filename, bold); addText("\n" + conflict.getConflict()); diff --git a/src/main/java/net/imagej/ui/swing/updater/DiffFile.java b/src/main/java/net/imagej/ui/swing/updater/DiffFile.java index db24808..9258c10 100644 --- a/src/main/java/net/imagej/ui/swing/updater/DiffFile.java +++ b/src/main/java/net/imagej/ui/swing/updater/DiffFile.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -62,10 +62,11 @@ /** * A {@link JFrame} to show the differences between the remote and local * versions of a file known to the ImageJ Updater. - * + * * @author Johannes Schindelin */ public class DiffFile extends JFrame { + private static final long serialVersionUID = 1L; protected String title; protected LogService log; @@ -80,17 +81,16 @@ public class DiffFile extends JFrame { /** * Initialize the frame. - * - * @param files - * the collection of files, including information about the - * update site from which we got the file - * @param file - * the file to diff - * @param mode - * the diff mode + * + * @param files the collection of files, including information about the + * update site from which we got the file + * @param file the file to diff + * @param mode the diff mode * @throws MalformedURLException */ - public DiffFile(final FilesCollection files, final FileObject file, final Mode mode) throws MalformedURLException { + public DiffFile(final FilesCollection files, final FileObject file, + final Mode mode) throws MalformedURLException + { util = files.util; title = file.getLocalFilename(true) + " differences"; log = files.log; @@ -110,10 +110,10 @@ public DiffFile(final FilesCollection files, final FileObject file, final Mode m setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); getContentPane().add(diffView); addWindowListener(new WindowAdapter() { + @Override public void windowClosing(WindowEvent e) { - if (worker != null) - worker.interrupt(); + if (worker != null) worker.interrupt(); } }); pack(); @@ -121,18 +121,19 @@ public void windowClosing(WindowEvent e) { /** * Switch to a different diff mode. - * - * @param mode - * the mode to diff to + * + * @param mode the mode to diff to */ protected void show(final Mode mode) { show(() -> { try { setTitle(title + " (" + mode + ")"); diff.showDiff(filename, remote, local, mode); - } catch (MalformedURLException e) { + } + catch (MalformedURLException e) { log.error(e); - } catch (IOException e) { + } + catch (IOException e) { log.error(e); } }); @@ -140,31 +141,30 @@ protected void show(final Mode mode) { /** * Show a different diff. - * - * @param runnable - * the object printing to the {@link DiffView} + * + * @param runnable the object printing to the {@link DiffView} */ protected synchronized void show(final Runnable runnable) { - if (worker != null) - worker.interrupt(); - else - diffView.setCursor(waitCursor); + if (worker != null) worker.interrupt(); + else diffView.setCursor(waitCursor); worker = new Thread() { + @Override public void run() { try { clearDiff(); runnable.run(); - } catch (RuntimeException e) { - if (!(e.getCause() instanceof InterruptedException)) - log.error(e); + } + catch (RuntimeException e) { + if (!(e.getCause() instanceof InterruptedException)) log.error(e); worker.interrupt(); - } catch (Error e) { + } + catch (Error e) { log.error(e); worker.interrupt(); } diffView.setCursor(normalCursor); - synchronized(DiffFile.this) { + synchronized (DiffFile.this) { worker = null; } } @@ -179,7 +179,8 @@ protected void clearDiff() { final Document doc = diffView.getDocument(); try { doc.remove(diffOffset, doc.getLength() - diffOffset); - } catch (BadLocationException e) { + } + catch (BadLocationException e) { log.error(e); } } @@ -189,9 +190,9 @@ protected void clearDiff() { */ private void addModeLinks() { for (final Mode mode : Mode.values()) { - if (diffView.getDocument().getLength() > 0) - diffView.normal(" "); + if (diffView.getDocument().getLength() > 0) diffView.normal(" "); diffView.link(mode.toString(), new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { show(mode); @@ -201,24 +202,24 @@ public void actionPerformed(ActionEvent e) { } /** - * Add an action link to show the Git log of the file. - * - * This method only adds the link if it can determine where the source for - * this component lives. - * - * @param files - * the file collection including information where the file lives - * @param fileObject - * the component to inspect + * Add an action link to show the Git log of the file. This method only adds + * the link if it can determine where the source for this component lives. + * + * @param files the file collection including information where the file lives + * @param fileObject the component to inspect */ - private void addGitLogLink(final FilesCollection files, final FileObject fileObject) { - // first, we need to find Implementation-Build entries in the respective manifests + private void addGitLogLink(final FilesCollection files, + final FileObject fileObject) + { + // first, we need to find Implementation-Build entries in the respective + // manifests String commitLocal = getCommit(local); if (commitLocal == null || "".equals(commitLocal)) commitLocal = "HEAD"; String commitRemote = getCommit(remote); if (commitLocal.equals(commitRemote)) { - diffView.warn("The remote and local versions were built from the same commit!"); + diffView.warn( + "The remote and local versions were built from the same commit!"); return; } @@ -228,12 +229,17 @@ private void addGitLogLink(final FilesCollection files, final FileObject fileObj directory = directory.getParentFile(); if (directory == null) return; } - final String baseName = fileObject.filename.substring(fileObject.filename.lastIndexOf('/') + 1); - for (String pair : new String[] { "ij-[1-9].* ImageJA", "ij-[a-z].* imagej2", "imglib.* imglib", "TrakEM2.* TrakEM2", "mpicbg.* mpicbg" }) { + final String baseName = fileObject.filename.substring(fileObject.filename + .lastIndexOf('/') + 1); + for (String pair : new String[] { "ij-[1-9].* ImageJA", + "ij-[a-z].* imagej2", "imglib.* imglib", "TrakEM2.* TrakEM2", + "mpicbg.* mpicbg" }) + { final int space = pair.indexOf(' '); final String pattern = pair.substring(0, space); if (baseName.matches(pattern)) { - final File submodule = new File(directory, "modules/" + pair.substring(space + 1)); + final File submodule = new File(directory, "modules/" + pair.substring( + space + 1)); if (new File(submodule, ".git").isDirectory()) { directory = submodule; break; @@ -242,7 +248,8 @@ private void addGitLogLink(final FilesCollection files, final FileObject fileObj } final File gitWorkingDirectory = directory; - // now, let's find the directory where the first source of the local .jar is stored + // now, let's find the directory where the first source of the local .jar is + // stored final String relativePath = findSourceDirectory(gitWorkingDirectory, local); if (relativePath == null) return; @@ -256,25 +263,28 @@ private void addGitLogLink(final FilesCollection files, final FileObject fileObj commitRange = commitLocal; long millis = UpdaterUtil.timestamp2millis(fileObject.current.timestamp); since = "--since=" + (millis / 1000l - 5 * 60); - warning = "No precise commit information in the remote .jar;\n" - + "\tUsing timestamp from Updater instead: " + new Date(millis) + " - 5 minutes"; + warning = "No precise commit information in the remote .jar;\n" + + "\tUsing timestamp from Updater instead: " + new Date(millis) + + " - 5 minutes"; } - if (diffView.getDocument().getLength() > 0) - diffView.normal(" "); + if (diffView.getDocument().getLength() > 0) diffView.normal(" "); diffView.link("Git Log", e -> show(() -> { setTitle(title + " (Git Log)"); final PrintStream out = diffView.getPrintStream(); out.println("\n"); if (warning != null) diffView.warn(warning + "\n\n"); - final String git = System.getProperty("imagej.updater.git.command", "git"); - ProcessUtils.exec(gitWorkingDirectory, out, out, git, "log", "-M", "-p", since, commitRange, "--", relativePath); + final String git = System.getProperty("imagej.updater.git.command", + "git"); + ProcessUtils.exec(gitWorkingDirectory, out, out, git, "log", "-M", "-p", + since, commitRange, "--", relativePath); })); } /** - * Given a {@link URL} to a .jar file, extract the Implementation-Build entry from the manifest. - * + * Given a {@link URL} to a .jar file, extract the Implementation-Build + * entry from the manifest. + * * @param jarURL the URL to the .jar file */ private String getCommit(final URL jarURL) { @@ -282,29 +292,32 @@ private String getCommit(final URL jarURL) { final JarInputStream in = new JarInputStream(util.openStream(jarURL)); in.close(); Manifest manifest = in.getManifest(); - if (manifest == null) - for (;;) { - final JarEntry entry = in.getNextJarEntry(); - if (entry == null) return null; - if (entry.getName().equals("META-INF/MANIFEST.MF")) { - manifest = new Manifest(in); - break; - } + if (manifest == null) for (;;) { + final JarEntry entry = in.getNextJarEntry(); + if (entry == null) return null; + if (entry.getName().equals("META-INF/MANIFEST.MF")) { + manifest = new Manifest(in); + break; } - final Attributes attributes = manifest.getMainAttributes(); + } + final Attributes attributes = manifest.getMainAttributes(); return attributes.getValue(new Attributes.Name("Implementation-Build")); - } catch (IOException e) { + } + catch (IOException e) { return null; } } /** - * Given a {@link URL} to a .jar file, extract the path of the first .class file contained therein. - * + * Given a {@link URL} to a .jar file, extract the path of the first + * .class file contained therein. + * * @param jarURL the URL to the .jar file * @return the path stored in the .jar file */ - private String findSourceDirectory(final File gitWorkingDirectory, final URL jarURL) { + private String findSourceDirectory(final File gitWorkingDirectory, + final URL jarURL) + { try { int maxCount = 3; final JarInputStream in = new JarInputStream(util.openStream(jarURL)); @@ -317,25 +330,33 @@ private String findSourceDirectory(final File gitWorkingDirectory, final URL jar final ByteCodeAnalyzer analyzer = Diff.analyzeByteCode(in, false); final String sourceFile = analyzer.getSourceFile(); if (sourceFile == null) continue; - final String suffix = path.substring(0, path.lastIndexOf('/') + 1) + sourceFile; - final String git = System.getProperty("imagej.updater.git.command", "git"); + final String suffix = path.substring(0, path.lastIndexOf('/') + 1) + + sourceFile; + final String git = System.getProperty("imagej.updater.git.command", + "git"); try { - path = ProcessUtils.exec(gitWorkingDirectory, null, null, git, "ls-files", "*/" + suffix); + path = ProcessUtils.exec(gitWorkingDirectory, null, null, git, + "ls-files", "*/" + suffix); if (path.length() <= suffix.length()) continue; if (path.endsWith("\n")) path = path.substring(0, path.length() - 1); - } catch (RuntimeException e) { + } + catch (RuntimeException e) { /* ignore */ continue; } if (path.indexOf('\n') >= 0) continue; // ls-files found multiple files path = path.substring(0, path.length() - suffix.length()); if ("".equals(path)) path = "."; - else if (path.endsWith("/src/main/java/")) path = path.substring(0, path.length() - "/src/main/java/".length()); + else if (path.endsWith("/src/main/java/")) path = path.substring(0, path + .length() - "/src/main/java/".length()); in.close(); return path; } in.close(); - } catch (IOException e) { /* ignore */ e.printStackTrace(); } + } + catch (IOException e) { + /* ignore */ e.printStackTrace(); + } return null; } } diff --git a/src/main/java/net/imagej/ui/swing/updater/DiffView.java b/src/main/java/net/imagej/ui/swing/updater/DiffView.java index 9d60212..5245705 100644 --- a/src/main/java/net/imagej/ui/swing/updater/DiffView.java +++ b/src/main/java/net/imagej/ui/swing/updater/DiffView.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -60,16 +60,16 @@ import org.scijava.util.ProcessUtils; /** - * A scroll pane that colorizes diff output. - * - * It offers a {@link PrintStream} for use with - * {@link ProcessUtils#exec(java.io.File, PrintStream, PrintStream, String...)}. It - * can also show links that might update the view by calling an + * A scroll pane that colorizes diff output. It offers a {@link PrintStream} for + * use with + * {@link ProcessUtils#exec(java.io.File, PrintStream, PrintStream, String...)}. + * It can also show links that might update the view by calling an * {@link ActionListener}. Otherwise, this class is pretty dumb. - * + * * @author Johannes Schindelin */ public class DiffView extends JScrollPane { + private static final long serialVersionUID = 1L; protected static final String ACTION_ATTRIBUTE = "ACTION"; @@ -112,38 +112,37 @@ public DiffView() { getVerticalScrollBar().setUnitIncrement(10); textPane.addMouseListener(new MouseAdapter() { + @Override public void mouseClicked(MouseEvent event) { ActionListener action = getAction(event); - if (action != null) - action.actionPerformed(new ActionEvent(DiffView.this, 0, "action")); + if (action != null) action.actionPerformed(new ActionEvent( + DiffView.this, 0, "action")); } }); } private ActionListener getAction(final MouseEvent event) { - Element e = document.getCharacterElement(textPane.viewToModel(event.getPoint())); - ActionListener action = (ActionListener)e.getAttributes().getAttribute(ACTION_ATTRIBUTE); + Element e = document.getCharacterElement(textPane.viewToModel(event + .getPoint())); + ActionListener action = (ActionListener) e.getAttributes().getAttribute( + ACTION_ATTRIBUTE); return action; } /** * Create an attribute set for stylish text. - * - * @param color - * the color - * @param italic - * whether the text should be slanted - * @param bold - * whether the text should be bold - * @param fontName - * the name of the font to use - * @param fontSize - * the font size to use + * + * @param color the color + * @param italic whether the text should be slanted + * @param bold whether the text should be bold + * @param fontName the name of the font to use + * @param fontSize the font size to use * @return the attribute set */ public static SimpleAttributeSet getStyle(Color color, boolean italic, - boolean bold, String fontName, int fontSize) { + boolean bold, String fontName, int fontSize) + { SimpleAttributeSet style = new SimpleAttributeSet(); if (color != null) StyleConstants.setForeground(style, color); StyleConstants.setItalic(style, italic); @@ -155,11 +154,9 @@ public static SimpleAttributeSet getStyle(Color color, boolean italic, /** * Add stylish text. - * - * @param text - * the text to add - * @param set - * the formatting attributes + * + * @param text the text to add + * @param set the formatting attributes */ public void styled(String text, AttributeSet set) { styled(document.getLength(), text, set); @@ -167,18 +164,16 @@ public void styled(String text, AttributeSet set) { /** * Insert some stylish text. - * - * @param position - * the position where to insert the text - * @param text - * the text to insert - * @param set - * the formatting attributes + * + * @param position the position where to insert the text + * @param text the text to insert + * @param set the formatting attributes */ public void styled(int position, String text, AttributeSet set) { try { document.insertString(position, text, set); - } catch (BadLocationException e) { + } + catch (BadLocationException e) { e.printStackTrace(); throw new RuntimeException(e); } @@ -186,9 +181,8 @@ public void styled(int position, String text, AttributeSet set) { /** * Add some plain text. - * - * @param text - * the text to add + * + * @param text the text to add */ public void normal(String text) { styled(text, normal); @@ -196,9 +190,8 @@ public void normal(String text) { /** * Add some warnings. - * - * @param warning - * the text to add + * + * @param warning the text to add */ public void warn(String warning) { red("Warning: "); @@ -207,9 +200,8 @@ public void warn(String warning) { /** * Add some red text. - * - * @param text - * the text to add + * + * @param text the text to add */ public void red(String text) { styled(text, red); @@ -217,9 +209,8 @@ public void red(String text) { /** * Add some green text. - * - * @param text - * the text to add + * + * @param text the text to add */ public void green(String text) { styled(text, green); @@ -227,9 +218,8 @@ public void green(String text) { /** * Insert some red text. - * - * @param text - * the text to insert + * + * @param text the text to insert */ public void red(int position, String text) { styled(position, text, red); @@ -237,9 +227,8 @@ public void red(int position, String text) { /** * Insert some green text. - * - * @param text - * the text to insert + * + * @param text the text to insert */ public void green(int position, String text) { styled(position, text, green); @@ -247,9 +236,8 @@ public void green(int position, String text) { /** * Generate an attribute set for links. - * - * @param action - * the action to perform + * + * @param action the action to perform * @return the attribute set */ public static SimpleAttributeSet getActionStyle(ActionListener action) { @@ -264,11 +252,9 @@ public static SimpleAttributeSet getActionStyle(ActionListener action) { /** * Add a link. - * - * @param text - * the label of the link - * @param action - * the action to perform when the link is clicked + * + * @param text the label of the link + * @param action the action to perform when the link is clicked */ public void link(String text, ActionListener action) { final JButton button = new JButton(text); @@ -279,7 +265,7 @@ public void link(String text, ActionListener action) { /** * Get the number of added lines. - * + * * @return how many lines were added in total */ public int getAdds() { @@ -288,7 +274,7 @@ public int getAdds() { /** * Get the number of removed lines. - * + * * @return how many lines were removed in total */ public int getRemoves() { @@ -297,7 +283,7 @@ public int getRemoves() { /** * Get the number of added or removed lines. - * + * * @return how many lines were added or removed in total */ public int getChanges() { @@ -306,7 +292,7 @@ public int getChanges() { /** * Colorize one line of output. - * + * * @param line the line */ public void println(String line) { @@ -314,8 +300,8 @@ public void println(String line) { styled(line, bold); inHeader = false; } - else if (line.startsWith(" ")) - styled(line, inHeader && line.startsWith(" ") ? bigBold : normal); + else if (line.startsWith(" ")) styled(line, inHeader && line.startsWith( + " ") ? bigBold : normal); else if (line.startsWith("+")) { adds++; styled(line, green); @@ -325,8 +311,7 @@ else if (line.startsWith("-")) { styled(line, red); } else { - if (line.startsWith("commit")) - inHeader = true; + if (line.startsWith("commit")) inHeader = true; styled(line, italic); } styled("\n", normal); @@ -334,17 +319,19 @@ else if (line.startsWith("-")) { /** * Construct a {@link PrintStream} adapter to this view. - * + * * @return the print stream */ public PrintStream getPrintStream() { final OutputStream out = new LineOutputStream() { + @Override public void println(String line) { DiffView.this.println(line); } }; return new PrintStream(out) { + @Override public void println(String line) { DiffView.this.println(line); @@ -354,7 +341,7 @@ public void println(String line) { /** * Access the underlying document. - * + * * @return the document */ protected Document getDocument() { @@ -363,20 +350,24 @@ protected Document getDocument() { /** * A main method for testing. - * + * * @param args the command line */ public static void main(String[] args) { final DiffView diff = new DiffView(); final Thread thread = new Thread() { + @Override public void run() { try { - final String git = System.getProperty("imagej.updater.git.command", "git"); - ProcessUtils.exec(null, diff.getPrintStream(), diff.getPrintStream(), git, "show"); - } catch (RuntimeException e) { - if (!(e.getCause() instanceof InterruptedException)) - e.printStackTrace(); + final String git = System.getProperty("imagej.updater.git.command", + "git"); + ProcessUtils.exec(null, diff.getPrintStream(), diff.getPrintStream(), + git, "show"); + } + catch (RuntimeException e) { + if (!(e.getCause() instanceof InterruptedException)) e + .printStackTrace(); } } }; @@ -386,6 +377,7 @@ public void run() { frame.setSize(640, 480); frame.getContentPane().add(diff); frame.addWindowListener(new WindowAdapter() { + @Override public void windowClosing(WindowEvent e) { thread.interrupt(); diff --git a/src/main/java/net/imagej/ui/swing/updater/FileDetails.java b/src/main/java/net/imagej/ui/swing/updater/FileDetails.java index 61cbca2..a133146 100644 --- a/src/main/java/net/imagej/ui/swing/updater/FileDetails.java +++ b/src/main/java/net/imagej/ui/swing/updater/FileDetails.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -67,7 +67,7 @@ /** * TODO - * + * * @author Johannes Schindelin */ @SuppressWarnings("serial") @@ -86,7 +86,8 @@ public class FileDetails extends JTextPane implements UndoableEditListener { italic = getStyle(null, true, false, java.awt.Font.SANS_SERIF, size); bold = getStyle(null, false, true, java.awt.Font.SANS_SERIF, size); normal = getStyle(null, false, false, java.awt.Font.SANS_SERIF, size); - title = getStyle(null, false, false, java.awt.Font.SANS_SERIF, (int)1.5 * size); + title = getStyle(null, false, false, java.awt.Font.SANS_SERIF, (int) 1.5 * + size); hand = new Cursor(Cursor.HAND_CURSOR); defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); } @@ -103,9 +104,11 @@ public void mouseClicked(final MouseEvent e) { // UpdaterUserInterface#openURL() has no implementation!? getOrInitPlatformService().open(new URL(url)); } - } catch (final Exception exception) { + } + catch (final Exception exception) { updaterFrame.log.error(exception); - UpdaterUserInterface.get().error("Could not open " + url + ": " + exception.getMessage()); + UpdaterUserInterface.get().error("Could not open " + url + ": " + + exception.getMessage()); } } }); @@ -133,7 +136,8 @@ private PlatformService getOrInitPlatformService() { public void reset() { setEditable(false); setText(""); - final Comparator comparator = (p1, p2) -> p1.getOffset() - p2.getOffset(); + final Comparator comparator = (p1, p2) -> p1.getOffset() - p2 + .getOffset(); editables = new TreeMap<>(comparator); dummySpace = null; } @@ -154,7 +158,8 @@ protected void setCursor(final Point p) { } private AttributeSet getLinkAttribute(final String url) { - final Style style = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE); + final Style style = StyleContext.getDefaultStyleContext().getStyle( + StyleContext.DEFAULT_STYLE); StyleConstants.setForeground(style, Color.BLUE); style.addAttribute(LINK_ATTRIBUTE, url); return style; @@ -205,14 +210,15 @@ public void title(final String text) { } public void description(final String description, final FileObject file) { - if (!updaterFrame.files.hasUploadableSites() && - (description == null || description.trim().equals(""))) return; + if (!updaterFrame.files.hasUploadableSites() && (description == null || + description.trim().equals(""))) return; blankLine(); - bold("Description" + (file.descriptionFromPOM ? " (from pom.xml)" : "") + ":\n"); + bold("Description" + (file.descriptionFromPOM ? " (from pom.xml)" : "") + + ":\n"); final int offset = getCaretPosition(); normal(description); - if (!file.descriptionFromPOM) - addEditableRegion(offset, "Description", file); + if (!file.descriptionFromPOM) addEditableRegion(offset, "Description", + file); } public void executable(final FileObject file) { @@ -235,8 +241,8 @@ public void list(String label, final boolean showLinks, blankLine(); final String tag = label; - if (list.size() > 1 && label.endsWith("y")) label = - label.substring(0, label.length() - 1) + "ie"; + if (list.size() > 1 && label.endsWith("y")) label = label.substring(0, label + .length() - 1) + "ie"; bold(label + (list.size() > 1 ? "s" : "") + ":\n"); final int offset = getCaretPosition(); String delimiter = ""; @@ -268,8 +274,8 @@ public void blankLine() { String prettyPrintTimestamp(final long timestamp) { final String t = "" + timestamp + "00000000"; - return t.substring(6, 8) + " " + - months[Integer.parseInt(t.substring(4, 6))] + " " + t.substring(0, 4); + return t.substring(6, 8) + " " + months[Integer.parseInt(t.substring(4, + 6))] + " " + t.substring(0, 4); } public void showFileDetails(final FileObject file) { @@ -298,8 +304,8 @@ public void showFileDetails(final FileObject file) { list("Link", true, file.getLinks(), "\n", file); list("Dependency", false, file.getDependencies(), ",\n", file); if (file.executable) executable(file); - if (file.updateSite != null && - !file.updateSite.equals(FilesCollection.DEFAULT_UPDATE_SITE)) + if (file.updateSite != null && !file.updateSite.equals( + FilesCollection.DEFAULT_UPDATE_SITE)) { blankLine(); bold("Update site:\n"); @@ -375,8 +381,8 @@ boolean handleEdit() { final Position current = getDocument().createPosition(offset); final Position last = editables.headMap(current).lastKey(); editable = editables.get(last); - if (offset > editable.start.getOffset() && - offset > editable.end.getOffset()) return false; + if (offset > editable.start.getOffset() && offset > editable.end + .getOffset()) return false; } catch (final NoSuchElementException e) { return false; @@ -384,8 +390,7 @@ boolean handleEdit() { catch (final BadLocationException e) { return false; } - if (!editable.file.isUploadable(updaterFrame.files, true)) - return false; + if (!editable.file.isUploadable(updaterFrame.files, true)) return false; final int start = editable.start.getOffset() + 1; final int end = editable.end.getOffset(); diff --git a/src/main/java/net/imagej/ui/swing/updater/FileTable.java b/src/main/java/net/imagej/ui/swing/updater/FileTable.java index 1e47a79..f28ecd2 100644 --- a/src/main/java/net/imagej/ui/swing/updater/FileTable.java +++ b/src/main/java/net/imagej/ui/swing/updater/FileTable.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -66,7 +66,7 @@ /** * This class's role is to be in charge of how the Table should be displayed. - * + * * @author Johannes Schindelin */ @SuppressWarnings("serial") @@ -127,9 +127,10 @@ public void popupMenuCanceled(PopupMenuEvent arg0) { setModel(fileTableModel); getModel().addTableModelListener(this); setColumnWidths(); - TableRowSorter sorter = - new TableRowSorter<>(fileTableModel); - sorter.setComparator(ACTION_COLUMN, (o1, o2) -> o1.toString().compareTo(o2.toString())); + TableRowSorter sorter = new TableRowSorter<>( + fileTableModel); + sorter.setComparator(ACTION_COLUMN, (o1, o2) -> o1.toString().compareTo(o2 + .toString())); setRowSorter(sorter); setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { @@ -139,9 +140,8 @@ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { - final Component comp = - super.getTableCellRendererComponent(table, value, isSelected, - hasFocus, row, column); + final Component comp = super.getTableCellRendererComponent(table, value, + isSelected, hasFocus, row, column); setStyle(comp, row, column); return comp; } @@ -155,8 +155,8 @@ public Component getTableCellRendererComponent(final JTable table, * It also warns loudly when the file is obsolete, but locally * modified. */ - protected void - setStyle(final Component comp, final int row, final int column) + protected void setStyle(final Component comp, final int row, + final int column) { if (plain == null) { plain = comp.getFont(); @@ -166,7 +166,8 @@ public Component getTableCellRendererComponent(final JTable table, if (file == null) return; comp.setFont(file.actionSpecified() || file.isLocallyModified() ? bold : plain); - if (file.getStatus() == Status.OBSOLETE_MODIFIED) comp.setForeground(Color.RED); + if (file.getStatus() == Status.OBSOLETE_MODIFIED) comp.setForeground( + Color.RED); } private void setColumnWidths() { @@ -174,7 +175,8 @@ private void setColumnWidths() { final TableColumn actionColumn = getColumnModel().getColumn(ACTION_COLUMN); final TableColumn siteColumn = getColumnModel().getColumn(SITE_COLUMN); final FontMetrics fm = getFontMetrics(getFont()); - nameColumn.setPreferredWidth(fm.stringWidth("jars/imagej-plugins-commands")); + nameColumn.setPreferredWidth(fm.stringWidth( + "jars/imagej-plugins-commands")); nameColumn.setMinWidth(fm.stringWidth("jars/bij.jar")); nameColumn.setResizable(true); actionColumn.setPreferredWidth(fm.stringWidth("Locally modified ")); @@ -199,7 +201,8 @@ public TableCellEditor getCellEditor(final int row, final int col) { // As we follow FileTableModel, 1st column is filename if (col == NAME_COLUMN) return super.getCellEditor(row, col); - final Set actions = files.getValidActions(Collections.singleton(file)); + final Set actions = files.getValidActions(Collections + .singleton(file)); return new DefaultCellEditor(new JComboBox<>(actions.toArray())); } @@ -239,9 +242,8 @@ public Iterable getSelectedFiles() { public Iterable getSelectedFiles(final int fallbackRow) { int[] rows = getSelectedRows(); - if (fallbackRow >= 0 && getFile(fallbackRow) != null && - (rows.length == 0 || indexOf(rows, fallbackRow) < 0)) rows = - new int[] { fallbackRow }; + if (fallbackRow >= 0 && getFile(fallbackRow) != null && (rows.length == 0 || + indexOf(rows, fallbackRow) < 0)) rows = new int[] { fallbackRow }; final FileObject[] result = new FileObject[rows.length]; for (int i = 0; i < rows.length; i++) result[i] = getFile(rows[i]); @@ -274,16 +276,15 @@ public boolean chooseUpdateSite(final FilesCollection files, error("No upload site available"); return false; } - if (list.size() == 1 && - list.get(0).equals(FilesCollection.DEFAULT_UPDATE_SITE)) + if (list.size() == 1 && list.get(0).equals( + FilesCollection.DEFAULT_UPDATE_SITE)) { file.updateSite = FilesCollection.DEFAULT_UPDATE_SITE; return true; } - final String updateSite = - SwingTools.getChoice(updaterFrame, list, - "To which upload site do you want to upload " + file.filename + "?", - "Upload site"); + final String updateSite = SwingTools.getChoice(updaterFrame, list, + "To which upload site do you want to upload " + file.filename + "?", + "Upload site"); if (updateSite == null) return false; file.updateSite = updateSite; return true; @@ -358,12 +359,12 @@ public Object getValueAt(final int row, final int column) { if (row < 0 || row >= files.size()) return null; final FileObject file = rowToFile.get(row); switch (column) { - case NAME_COLUMN: - return file.getFilename(true); - case ACTION_COLUMN: - return file.getAction(); - case SITE_COLUMN: - return file.updateSite; + case NAME_COLUMN: + return file.getFilename(true); + case ACTION_COLUMN: + return file.getAction(); + case SITE_COLUMN: + return file.updateSite; } throw new RuntimeException("Unhandled column: " + column); } @@ -374,7 +375,8 @@ public boolean isCellEditable(final int rowIndex, final int columnIndex) { } @Override - public void setValueAt(final Object value, final int row, final int column) + public void setValueAt(final Object value, final int row, + final int column) { if (column == ACTION_COLUMN) { final GroupAction action = (GroupAction) value; diff --git a/src/main/java/net/imagej/ui/swing/updater/ImageJUpdater.java b/src/main/java/net/imagej/ui/swing/updater/ImageJUpdater.java index 39cd189..43b8f6c 100644 --- a/src/main/java/net/imagej/ui/swing/updater/ImageJUpdater.java +++ b/src/main/java/net/imagej/ui/swing/updater/ImageJUpdater.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -29,64 +29,87 @@ package net.imagej.ui.swing.updater; -import java.io.DataInputStream; -import java.io.File; -import java.io.IOException; +import java.io.*; import java.lang.reflect.InvocationTargetException; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.URLConnection; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; +import java.net.*; +import java.util.*; +import java.util.concurrent.ExecutionException; import net.imagej.ui.swing.updater.ViewOptions.Option; import net.imagej.updater.*; import net.imagej.updater.Conflicts.Conflict; import net.imagej.updater.util.*; +import org.apache.commons.compress.archivers.ArchiveEntry; +import org.apache.commons.compress.archivers.ArchiveInputStream; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; +import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.scijava.app.StatusService; import org.scijava.command.CommandService; +import org.scijava.download.Download; +import org.scijava.download.DownloadService; import org.scijava.event.ContextDisposingEvent; import org.scijava.event.EventHandler; +import org.scijava.io.location.LocationService; import org.scijava.log.LogService; import org.scijava.log.Logger; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; +import org.scijava.task.Task; +import org.scijava.task.TaskService; +import org.scijava.ui.DialogPrompt; +import org.scijava.ui.UIService; import org.scijava.util.AppUtils; +import org.scijava.util.PropertiesHelper; import javax.swing.*; +import static org.scijava.ui.DialogPrompt.MessageType.QUESTION_MESSAGE; +import static org.scijava.ui.DialogPrompt.OptionType.YES_NO_OPTION; + /** * The Updater. As a command. *

* Incidentally, this class can be used as an out-of-ImageJ entry point to the * updater, as it does not *require* a StatusService to run. - * + * * @author Johannes Schindelin */ -@Plugin(type = UpdaterUI.class, menu = { @Menu(label = "Help"), - @Menu(label = "Update...") }) +@Plugin(type = UpdaterUI.class, menu = { @Menu(label = "Help"), @Menu( + label = "Update...") }) public class ImageJUpdater implements UpdaterUI { + private UpdaterFrame main; @Parameter private StatusService statusService; + @Parameter + private DownloadService downloadService; + + @Parameter + private TaskService taskService; + + @Parameter + private LocationService locationService; + @Parameter private LogService log; + @Parameter + private UIService uiService; + @Parameter private UploaderService uploaderService; @Parameter private CommandService commandService; - private final static String UPDATER_UPDATING_THREAD_NAME = "Updating the Updater itself!"; + private final static String UPDATER_UPDATING_THREAD_NAME = + "Updating the Updater itself!"; @Override public void run() { @@ -100,42 +123,53 @@ public void run() { if (errorIfNetworkInaccessible(log)) return; String imagejDirProperty = System.getProperty("imagej.dir"); - final File imagejRoot = imagejDirProperty != null ? new File(imagejDirProperty) : - AppUtils.getBaseDirectory("ij.dir", FilesCollection.class, "updater"); + final File imagejRoot = imagejDirProperty != null ? new File( + imagejDirProperty) : AppUtils.getBaseDirectory("ij.dir", + FilesCollection.class, "updater"); + + // -- Check for HTTPs support in Java -- + HTTPSUtil.checkHTTPSSupport(log); + if (!HTTPSUtil.supportsHTTPS()) { + main.warn( + "Your Java might be too old to handle updates via HTTPS. This is a security risk!\n" + + "Please download a recent version of this software.\n"); + } + + // check if there is a new Java update available + updateJavaIfNecessary(imagejRoot); + + // -- Determine which files are governed by the updater -- final FilesCollection files = new FilesCollection(log, imagejRoot); UpdaterUserInterface.set(new SwingUserInterface(log, statusService)); if (!areWeUpdatingTheUpdater() && new File(imagejRoot, "update").exists()) { - if (!UpdaterUserInterface.get().promptYesNo("It is suggested that you restart ImageJ, then continue the update.\n" - + "Alternately, you can attempt to continue the upgrade without\n" - + "restarting, but ImageJ might crash.\n\n" - + "Do you want to try it?", - "Restart required to finalize update")) - return; + if (!UpdaterUserInterface.get().promptYesNo( + "It is suggested that you restart ImageJ, then continue the update.\n" + + "Alternately, you can attempt to continue the upgrade without\n" + + "restarting, but ImageJ might crash.\n\n" + "Do you want to try it?", + "Restart required to finalize update")) return; try { new Installer(files, null).moveUpdatedIntoPlace(); - } catch (IOException e) { + } + catch (IOException e) { log.debug(e); - UpdaterUserInterface.get().error("Could not move files into place: " + e); + UpdaterUserInterface.get().error("Could not move files into place: " + + e); return; } } UpdaterUtil.useSystemProxies(); Authenticator.setDefault(new SwingAuthenticator()); - SwingTools.invokeOnEDT(() -> main = new UpdaterFrame(log, uploaderService, files)); + SwingTools.invokeOnEDT(() -> main = new UpdaterFrame(log, uploaderService, + files)); main.setEasyMode(true); Progress progress = main.getProgress("Starting up..."); try { files.tryLoadingCollection(); - HTTPSUtil.checkHTTPSSupport(log); - if(!HTTPSUtil.supportsHTTPS()) { - main.warn("Your Java might be too old to handle updates via HTTPS. This is a security risk!\n" + - "Please download a recent version of this software.\n"); - } refreshUpdateSites(files); main.updateFilesTable(); String warnings = files.reloadCollectionAndChecksum(progress); @@ -143,16 +177,17 @@ public void run() { main.addCustomViewOptions(); if (!warnings.equals("")) main.warn(warnings); final List conflicts = files.getConflicts(); - if (conflicts != null && conflicts.size() > 0 && - !new ConflictDialog(main, "Conflicting Versions") { - private static final long serialVersionUID = 1L; + if (conflicts != null && conflicts.size() > 0 && !new ConflictDialog(main, + "Conflicting Versions") + { - @Override - protected void updateConflictList() { - conflictList = conflicts; - } - }.resolve()) - return; + private static final long serialVersionUID = 1L; + + @Override + protected void updateConflictList() { + conflictList = conflicts; + } + }.resolve()) return; } catch (final UpdateCanceledException e) { main.error("Canceled"); @@ -168,10 +203,13 @@ protected void updateConflictList() { return; } - if (!areWeUpdatingTheUpdater() && Installer.isTheUpdaterUpdateable(files, commandService)) { + if (!areWeUpdatingTheUpdater() && Installer.isTheUpdaterUpdateable(files, + commandService)) + { try { // download just the updater - Installer.updateTheUpdater(files, main.getProgress("Installing the updater..."), commandService); + Installer.updateTheUpdater(files, main.getProgress( + "Installing the updater..."), commandService); } catch (final UpdateCanceledException e) { main.error("Canceled"); @@ -184,46 +222,56 @@ protected void updateConflictList() { // make a class path using the updated files final List classPath = new ArrayList<>(); - for (FileObject component : Installer.getUpdaterFiles(files, commandService, false)) { + for (FileObject component : Installer.getUpdaterFiles(files, + commandService, false)) + { final File updated = files.prefixUpdate(component.getFilename(false)); if (updated.exists()) try { classPath.add(updated.toURI().toURL()); continue; - } catch (MalformedURLException e) { + } + catch (MalformedURLException e) { log.error(e); } final String name = component.getLocalFilename(false); File file = files.prefix(name); try { classPath.add(file.toURI().toURL()); - } catch (MalformedURLException e) { + } + catch (MalformedURLException e) { log.error(e); } } try { log.info("Trying to install and execute the new updater"); final URL[] urls = classPath.toArray(new URL[classPath.size()]); - URLClassLoader remoteClassLoader = new URLClassLoader(urls, getClass().getClassLoader().getParent()); - Class runnable = remoteClassLoader.loadClass(ImageJUpdater.class.getName()); - final Thread thread = new Thread((Runnable)runnable.newInstance()); + URLClassLoader remoteClassLoader = new URLClassLoader(urls, getClass() + .getClassLoader().getParent()); + Class runnable = remoteClassLoader.loadClass(ImageJUpdater.class + .getName()); + final Thread thread = new Thread((Runnable) runnable.newInstance()); thread.setName(UPDATER_UPDATING_THREAD_NAME); thread.start(); thread.join(); return; - } catch (Throwable t) { + } + catch (Throwable t) { log.error(t); } - main.info("Please restart ImageJ and call Help>Update to continue with the update"); + main.info( + "Please restart ImageJ and call Help>Update to continue with the update"); return; } try { - final String missingUploaders = main.files.protocolsMissingUploaders(main.getUploaderService(), main.getProgress(null)); + final String missingUploaders = main.files.protocolsMissingUploaders(main + .getUploaderService(), main.getProgress(null)); if (missingUploaders != null) { main.warn(missingUploaders); } - } catch (final IllegalArgumentException e) { + } + catch (final IllegalArgumentException e) { e.printStackTrace(); } @@ -245,19 +293,270 @@ protected void updateConflictList() { main.updateFilesTable(); } + /** + * Helper method to download and extract the appropriate JDK for this platform + * to the corresponding ImageJ java subdirectory. + */ + private boolean updateJava(final Map jdkVersions, + final File imagejRoot) + { + // Download and unzip the new JDK + final String platform = UpdaterUtil.getPlatform(); + final String jdkUrl = jdkVersions.get(platform); + final String jdkName = jdkUrl.substring(jdkUrl.lastIndexOf("/") + 1); + final File jdkDir = new File(imagejRoot + File.separator + "java" + + File.separator + platform); + + if (!jdkDir.exists() && !jdkDir.mkdirs()) { + log.error("Unable to create platform Java directory: " + jdkDir); + return false; + } + + // Download the JDK + final File jdkDlLoc = new File(jdkDir.getAbsolutePath() + File.separator + + jdkName); + jdkDlLoc.deleteOnExit(); + try { + log.debug("Downloading " + locationService.resolve(jdkUrl) + " to " + + locationService.resolve(jdkDlLoc.toURI())); + Download download = downloadService.download(locationService.resolve( + jdkUrl), locationService.resolve(jdkDlLoc.toURI())); + download.task().waitFor(); + } + catch (URISyntaxException | ExecutionException | InterruptedException e) { + log.error(e); + return false; + } + + String javaLoc = jdkDlLoc.getAbsolutePath(); + int extensionLength = 0; + int entryCount = 0; + + // Extract the JDK + if (jdkDlLoc.toString().endsWith("tar.gz")) { + extensionLength = 7; + // sadly this is the only way to determine how long extraction + try (FileInputStream fis = new FileInputStream(jdkDlLoc); + GzipCompressorInputStream gzIn = new GzipCompressorInputStream(fis); + TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn)) + { + entryCount = countArchiveEntries(tarIn); + } + catch (IOException e) { + log.error(e); + return false; + } + // Do the actual extraction + try (FileInputStream fis = new FileInputStream(jdkDlLoc); + GzipCompressorInputStream gzIn = new GzipCompressorInputStream(fis); + TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn)) + { + doExtraction(jdkDir, tarIn, entryCount); + } + catch (ExecutionException | InterruptedException | IOException e) { + log.error(e); + return false; + } + } + else if (jdkDlLoc.toString().endsWith("zip")) { + extensionLength = 4; + // sadly this is the only way to determine how long extraction will take + try (FileInputStream fis = new FileInputStream(jdkDlLoc); + ZipArchiveInputStream zis = new ZipArchiveInputStream(fis)) + { + entryCount = countArchiveEntries(zis); + } + catch (IOException e) { + log.error(e); + return false; + } + // Do the actual extraction + try (FileInputStream fis = new FileInputStream(jdkDlLoc); + ZipArchiveInputStream zis = new ZipArchiveInputStream(fis)) + { + doExtraction(jdkDir, zis, entryCount); + } + catch (ExecutionException | InterruptedException | IOException e) { + log.error(e); + return false; + } + } + + // Notify user of success + uiService.showDialog("Java version updated!" + + " Please restart to take advantage of the new Java.", + DialogPrompt.MessageType.INFORMATION_MESSAGE); + + // Update the app configuration file to use the newly downloaded JDK + javaLoc = javaLoc.substring(0, javaLoc.length() - extensionLength); + String exeName = System.getProperty("ij.executable"); + if (exeName != null && !exeName.trim().isEmpty()) { + exeName = exeName.substring(exeName.lastIndexOf(File.separator)); + exeName = exeName.substring(0, exeName.indexOf("-")); + final File appCfg = new File(imagejRoot + File.separator + "config" + + File.separator + "jaunch" + File.separator + exeName + ".cfg"); + Map appProps = appCfg.exists() ? PropertiesHelper.get( + appCfg) : new HashMap<>(); + appProps.put("jvm.app-configured", javaLoc); + PropertiesHelper.put(appProps, appCfg); + } + return true; + } + + /** + * Helper method to count the entries in an archive + */ + private int countArchiveEntries(final ArchiveInputStream ais) + throws IOException + { + int entryCount = 0; + ArchiveEntry entry; + while ((entry = ais.getNextEntry()) != null) { + entryCount++; + } + return entryCount; + } + + /** + * Helper method to extract an archive + */ + private void doExtraction(final File jdkDir, final ArchiveInputStream ais, + final int entryCount) throws IOException, ExecutionException, + InterruptedException + { + Task task = taskService.createTask("Extracting JDK"); + task.setProgressMaximum(entryCount); + task.setProgressValue(0); + task.start(); + task.run(() -> { + try { + int currentEntry = 0; + ArchiveEntry entry; + while ((entry = ais.getNextEntry()) != null) { + if (task != null && task.isCanceled()) break; + if (entry.isDirectory()) { + new File(jdkDir, entry.getName()).mkdirs(); + } + else { + byte[] buffer = new byte[1024]; + File outputFile = new File(jdkDir, entry.getName()); + OutputStream fos = new FileOutputStream(outputFile); + int len; + while ((len = ais.read(buffer)) != -1) { + fos.write(buffer, 0, len); + } + fos.close(); + } + task.setProgressValue(++currentEntry); + } + } + catch (IOException e) { + task.setStatusMessage("Java extraction failed!"); + } + }); + task.waitFor(); + task.finish(); + } + + /** + * Helper method that checks the remote JDK list and compares to a locally + * cached version. If the remote list is newer an available Java update is + * indicated. If the user agrees, the new JDK is downloaded and extracted to + * the appropriate directory. + */ + private void updateJavaIfNecessary(final File imagejRoot) { + final File configDir = new File(imagejRoot.getAbsolutePath() + + File.separator + "config" + File.separator + "jaunch"); + final File jdkUrlConf = new File(configDir.getAbsolutePath() + + File.separator + "jdk-urls.cfg"); + final String modifiedKey = "LAST_MODIFIED"; + final String jdkUrl = "https://downloads.imagej.net/java/jdk-urls.txt"; + long lastModifiedRemote; + + // Get the last modified time on the remote JDK list + try { + HttpURLConnection connection = (HttpURLConnection) new URL(jdkUrl) + .openConnection(); + connection.setRequestMethod("HEAD"); + lastModifiedRemote = connection.getLastModified(); + } + catch (IOException e) { + log.error("Unable to read remote JDK list", e); + return; + } + + // Make the config dir if it doesn't already exist + if (!configDir.exists() && !configDir.mkdirs()) { + log.error("Unable to create configuration directory: " + configDir); + return; + } + + // Check if we've already cached a local version of the JDK list + if (jdkUrlConf.exists()) { + // check when the remote was last modified + Map jdkVersionProps = PropertiesHelper.get(jdkUrlConf); + if (lastModifiedRemote == 0) { // 0 means "not provided" + log.error("No modification date found in jdk-urls.txt"); + return; + } + long lastModifiedLocal = Long.parseLong(jdkVersionProps.getOrDefault( + modifiedKey, "0")); + + // return if up to date + if (lastModifiedLocal == lastModifiedRemote) return; + + // Otherwise delete the conf file and re-download + jdkUrlConf.delete(); + } + + // Download the new properties file + try { + Download dl = downloadService.download(locationService.resolve(jdkUrl), + locationService.resolve(jdkUrlConf.toURI())); + dl.task().waitFor(); + } + catch (URISyntaxException e) { + log.error("Failed to download the remote JDK url list: bad URI"); + return; + } + catch (ExecutionException | InterruptedException e) { + log.error( + "Failed to download the remote JDK url list: download task failed"); + return; + } + + // Inject the last modification date to the JDK list + Map jdkUrlMap = PropertiesHelper.get(jdkUrlConf); + jdkUrlMap.put(modifiedKey, Long.toString(lastModifiedRemote)); + + // Ask the user if they would like to proceed with a Java update + DialogPrompt.Result result = uiService.showDialog( + "A newer version of Java is recommended.\n" + + "Downloading this may take longer than normal updates, but will " + + "eventually be required for continued updates.\n" + + "Would you like to update now?", QUESTION_MESSAGE, YES_NO_OPTION); + + // Do the update, if desired + if (result == DialogPrompt.Result.YES_OPTION && updateJava(jdkUrlMap, + imagejRoot)) + { + // Store the current url list if we updated Java + PropertiesHelper.put(jdkUrlMap, jdkUrlConf); + } + } + private void refreshUpdateSites(FilesCollection files) - throws InterruptedException, InvocationTargetException + throws InterruptedException, InvocationTargetException { - List - changes = AvailableSites.initializeAndAddSites(files, (Logger) log); - if(ReviewSiteURLsDialog.shouldBeDisplayed(changes)) { + List changes = AvailableSites.initializeAndAddSites(files, + (Logger) log); + if (ReviewSiteURLsDialog.shouldBeDisplayed(changes)) { ReviewSiteURLsDialog dialog = new ReviewSiteURLsDialog(main, changes); SwingUtilities.invokeAndWait(() -> dialog.setVisible(true)); - if(dialog.isOkPressed()) - AvailableSites.applySitesURLUpdates(files, changes); + if (dialog.isOkPressed()) AvailableSites.applySitesURLUpdates(files, + changes); } - else - AvailableSites.applySitesURLUpdates(files, changes); + else AvailableSites.applySitesURLUpdates(files, changes); } @EventHandler @@ -269,7 +568,8 @@ protected boolean overwriteWithUpdated(final FilesCollection files, final FileObject file) { File downloaded = files.prefix("update/" + file.filename); - if (!downloaded.exists()) return true; // assume all is well if there is no updated file + if (!downloaded.exists()) return true; // assume all is well if there is no + // updated file final File jar = files.prefix(file.filename); if (!jar.delete() && !moveOutOfTheWay(jar)) return false; if (!downloaded.renameTo(jar)) return false; @@ -345,7 +645,7 @@ public static boolean errorIfNetworkInaccessible(final LogService log) { /** * Check whether we can connect to the Internet. If we cannot connect, we will * not be able to update. - * + * * @throws IOException if anything goes wrong. */ private static void testNetworkConnection() throws IOException { @@ -358,7 +658,7 @@ private static void testNetworkConnection() throws IOException { final URLConnection urlConn = url.openConnection(); if (!(urlConn instanceof HttpURLConnection)) { throw new IOException("Unexpected connection type: " + // - urlConn.getClass().getName()); + urlConn.getClass().getName()); } final HttpURLConnection httpConn = (HttpURLConnection) urlConn; @@ -379,16 +679,16 @@ private static void testNetworkConnection() throws IOException { // Header looks reasonable; now let's check the content to be sure. final byte[] content = new byte[(int) length]; try (final DataInputStream din = // - new DataInputStream(httpConn.getInputStream())) + new DataInputStream(httpConn.getInputStream())) { din.readFully(content); } final String s = new String(content, "UTF-8"); if (!s.matches("(?s).*.*" + - ".*301 Moved Permanently.*.*" + // - ".*

Moved Permanently

.*" + // - "" + // - ".*.*")) + ".*301 Moved Permanently.*.*" + // + ".*

Moved Permanently

.*" + // + "
" + // + ".*.*")) { throw new IOException("Unexpected response:\n" + s); } @@ -415,7 +715,8 @@ protected static boolean moveOutOfTheWay(final File file) { } private boolean areWeUpdatingTheUpdater() { - return UPDATER_UPDATING_THREAD_NAME.equals(Thread.currentThread().getName()); + return UPDATER_UPDATING_THREAD_NAME.equals(Thread.currentThread() + .getName()); } public static void main(String[] args) { diff --git a/src/main/java/net/imagej/ui/swing/updater/ProgressDialog.java b/src/main/java/net/imagej/ui/swing/updater/ProgressDialog.java index 16421ae..3060d15 100644 --- a/src/main/java/net/imagej/ui/swing/updater/ProgressDialog.java +++ b/src/main/java/net/imagej/ui/swing/updater/ProgressDialog.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -51,7 +51,7 @@ /** * TODO - * + * * @author Johannes Schindelin */ @SuppressWarnings("serial") @@ -95,21 +95,21 @@ public ProgressDialog(final Frame owner, final String title) { root.add(buttons); details = new Details(); - detailsScrollPane = - new JScrollPane(details, - ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - detailsScrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { - - @Override - public void adjustmentValueChanged(AdjustmentEvent e) { - final int value = e.getValue(); - final Adjustable adjustable = e.getAdjustable(); - final int maximum = adjustable.getMaximum(); - if (value != maximum) - adjustable.setValue(maximum); - } - }); + detailsScrollPane = new JScrollPane(details, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + detailsScrollPane.getVerticalScrollBar().addAdjustmentListener( + new AdjustmentListener() + { + + @Override + public void adjustmentValueChanged(AdjustmentEvent e) { + final int value = e.getValue(); + final Adjustable adjustable = e.getAdjustable(); + final int maximum = adjustable.getMaximum(); + if (value != maximum) adjustable.setValue(maximum); + } + }); detailsScrollPane.setVisible(false); root.add(detailsScrollPane); @@ -203,7 +203,8 @@ public void setItemCount(final int count, final int total) { public void itemDone(final Object item) { checkIfCanceled(); if (itemUpdatesTooFast() && !detailsScrollPane.isVisible()) return; - SwingTools.invokeOnEDT(() -> latestDetail.setValue(latestDetail.getMaximum())); + SwingTools.invokeOnEDT(() -> latestDetail.setValue(latestDetail + .getMaximum())); } @Override diff --git a/src/main/java/net/imagej/ui/swing/updater/ResolveDependencies.java b/src/main/java/net/imagej/ui/swing/updater/ResolveDependencies.java index 929fa5d..05968a2 100644 --- a/src/main/java/net/imagej/ui/swing/updater/ResolveDependencies.java +++ b/src/main/java/net/imagej/ui/swing/updater/ResolveDependencies.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -37,7 +37,7 @@ /** * This dialog displays the update or upload conflicts for resolution. - * + * * @author Johannes Schindelin */ @SuppressWarnings("serial") diff --git a/src/main/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialog.java b/src/main/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialog.java index aa8e713..e37fec0 100644 --- a/src/main/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialog.java +++ b/src/main/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialog.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -26,6 +26,7 @@ * POSSIBILITY OF SUCH DAMAGE. * #L% */ + package net.imagej.ui.swing.updater; import net.imagej.updater.URLChange; @@ -53,14 +54,14 @@ import static net.imagej.ui.swing.updater.SitesDialog.escapeCancels; /** - * The dialog in which updated URLs of available update sites will be shown - * and the user can chose to accept these updates. + * The dialog in which updated URLs of available update sites will be shown and + * the user can chose to accept these updates. * * @author Deborah Schmidt */ public class ReviewSiteURLsDialog extends JDialog implements ActionListener { - List< URLChange > urlChanges; + List urlChanges; private UpdatableTableDataModel tableModel; private JTable table; @@ -71,32 +72,38 @@ public class ReviewSiteURLsDialog extends JDialog implements ActionListener { JCheckBox stopAsking; private ButtonGroup generalChoiceGroup = new ButtonGroup(); private final static int nameCol = 0, urlCol = 1; - private final static String appendOld = " (keep URL)", appendNew = " (update URL)"; + private final static String appendOld = " (keep URL)", appendNew = + " (update URL)"; private boolean okPressed; /** * @param owner The frame that this dialog will be placed relative to * @param urlChanges The urlChanges */ - public ReviewSiteURLsDialog(final UpdaterFrame owner, final List< URLChange > urlChanges) + public ReviewSiteURLsDialog(final UpdaterFrame owner, + final List urlChanges) { - super(owner, "Changes to Available Update Sites", ModalityType.DOCUMENT_MODAL); + super(owner, "Changes to Available Update Sites", + ModalityType.DOCUMENT_MODAL); this.urlChanges = urlChanges; final JPanel contentPane = new JPanel(); contentPane.setLayout(new MigLayout("fill, gap 0")); - this.urlChanges.forEach( change -> change.setApproved(change.isRecommended())); + this.urlChanges.forEach(change -> change.setApproved(change + .isRecommended())); - if( this.urlChanges.size() > 0) { - //setMinimumSize(new Dimension(900, 0)); + if (this.urlChanges.size() > 0) { + // setMinimumSize(new Dimension(900, 0)); contentPane.add(createHeader(), "span, grow"); - contentPane.add(createUpdateSiteScrollPane(), "newline, span, grow, push"); + contentPane.add(createUpdateSiteScrollPane(), + "newline, span, grow, push"); contentPane.add(createButtonsPanel(), "dock south"); updateGeneralChoices(); - } else { - //setMinimumSize(new Dimension(0, 0)); + } + else { + // setMinimumSize(new Dimension(0, 0)); contentPane.add(createOkPanel(), "dock south"); contentPane.add(createOkIcon()); contentPane.add(createEverythingIsFineMessage()); @@ -109,9 +116,9 @@ public ReviewSiteURLsDialog(final UpdaterFrame owner, final List< URLChange > ur setLocationRelativeTo(owner); } - static boolean shouldBeDisplayed(final List changes ) { - for(URLChange change : changes) { - if(change.isRecommended() && !change.isApproved()) { + static boolean shouldBeDisplayed(final List changes) { + for (URLChange change : changes) { + if (change.isRecommended() && !change.isApproved()) { return true; } } @@ -123,17 +130,19 @@ boolean isOkPressed() { } private Component createEverythingIsFineMessage() { - JEditorPane text = createHTMLText("

Software package sources up to date

" + + JEditorPane text = createHTMLText( + "

Software package sources up to date

" + "No updated URLs found for activated update sites."); text.setBorder(BorderFactory.createEmptyBorder(10, 10, 20, 25)); - //text.setMinimumSize(new Dimension(0,0)); + // text.setMinimumSize(new Dimension(0,0)); return text; } private Component createOkPanel() { JPanel panel = new JPanel(); ok = new JButton("OK"); - //panel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.darkGray)); + // panel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, + // Color.darkGray)); panel.add(ok); ok.addActionListener(this); getRootPane().setDefaultButton(ok); @@ -146,7 +155,7 @@ private Component createHeader() { panel.add(createUpdatesAvailableMessage(), "span, wrap, wmax 600px"); panel.add(createAttentionIcon(), "w 100px!"); panel.add(createGeneralChoices(), "wrap, w 300px!, bottom, left"); - if(HTTPSUtil.supportsHTTPS()) { + if (HTTPSUtil.supportsHTTPS()) { panel.add(createHTTPSInfo(), "wmax 250px, dock east"); } return panel; @@ -162,42 +171,44 @@ private static Component createAttentionIcon() { private static Component createOkIcon() { JLabel label = new JLabel("

:-)

", SwingConstants.CENTER); label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - //label.setFont(new Font(label.getFont().getName(), Font.BOLD, (int) (label.getFont().getSize() * 2.5))); - //label.setForeground(new Color(114, 200, 218)); + // label.setFont(new Font(label.getFont().getName(), Font.BOLD, (int) + // (label.getFont().getSize() * 2.5))); + // label.setForeground(new Color(114, 200, 218)); return label; // return new JLabel(javax.swing.UIManager.getIcon("OptionPane.informationIcon")); } private static Component createUpdatesAvailableMessage() { return createHTMLText("

Updated software package sources

" + - "

Please review the following update site URL changes.
" + - "If you have never heard of update sites," + - " just click OK at the bottom.

"); + "

Please review the following update site URL changes.
" + + "If you have never heard of update sites," + + " just click OK at the bottom.

"); } private static Component createHTTPSInfo() { // TODO remove note in Updater V2 - JEditorPane text = createHTMLText("

ImageJ is improving
data security!

" + + JEditorPane text = createHTMLText( + "

ImageJ is improving
data security!

" + "From now on ImageJ updates more securely via HTTPS. " + "Therefore addresses of update sites currently in use by your ImageJ installation " + "need to be updated."); - //text.setBackground(new Color(250,250,250)); - //text.setBorder(BorderFactory.createEmptyBorder(25,15,25,25)); - //String bodyRule = "body { color: #404042; }"; - //((HTMLDocument)text.getDocument()).getStyleSheet().addRule(bodyRule); - //text.setOpaque(true); + // text.setBackground(new Color(250,250,250)); + // text.setBorder(BorderFactory.createEmptyBorder(25,15,25,25)); + // String bodyRule = "body { color: #404042; }"; + // ((HTMLDocument)text.getDocument()).getStyleSheet().addRule(bodyRule); + // text.setOpaque(true); return text; } private static JEditorPane createHTMLText(String text) { - JEditorPane component = - new JEditorPane(new HTMLEditorKit().getContentType(), text); + JEditorPane component = new JEditorPane(new HTMLEditorKit() + .getContentType(), text); component.setEditable(false); component.setOpaque(false); Font font = UIManager.getFont("Label.font"); String bodyRule = "body { font-family: " + font.getFamily() + "; " + - "font-size: " + font.getSize() + "pt; }"; - ((HTMLDocument)component.getDocument()).getStyleSheet().addRule(bodyRule); + "font-size: " + font.getSize() + "pt; }"; + ((HTMLDocument) component.getDocument()).getStyleSheet().addRule(bodyRule); return component; } @@ -207,7 +218,8 @@ private Component createGeneralChoices() { updateAll = createGeneralChoiceButton("Update all URLs (recommended)"); keepAll = createGeneralChoiceButton("Keep the current URLs"); manualChoice = createGeneralChoiceButton("Adjust manually:"); - manualChoice.setFont(manualChoice.getFont().deriveFont(manualChoice.getFont().getStyle() & ~Font.BOLD)); + manualChoice.setFont(manualChoice.getFont().deriveFont(manualChoice + .getFont().getStyle() & ~Font.BOLD)); generalChoices.add(updateAll); generalChoices.add(keepAll); generalChoices.add(manualChoice); @@ -226,8 +238,10 @@ private Component createButtonsPanel() { buttons.setLayout(new MigLayout("", "[]push[][]", "")); stopAsking = new JCheckBox("Remember to not update these URLs"); buttons.add(stopAsking); - cancel = SwingTools.button("Cancel", "Do not update software package sources", this, buttons); - submit = SwingTools.button("OK", "Continue with updated software package sources", this, buttons); + cancel = SwingTools.button("Cancel", + "Do not update software package sources", this, buttons); + submit = SwingTools.button("OK", + "Continue with updated software package sources", this, buttons); getRootPane().setDefaultButton(submit); return buttons; } @@ -235,7 +249,7 @@ private Component createButtonsPanel() { private Component createUpdateSiteScrollPane() { JScrollPane scrollPane = new JScrollPane(createUpdatableSitesTable()); scrollPane.setPreferredSize(new Dimension(tableModel.tableWidth, 150)); - //scrollPane.setMinimumSize(new Dimension(0,0)); + // scrollPane.setMinimumSize(new Dimension(0,0)); return scrollPane; } @@ -244,10 +258,10 @@ private JTable createUpdatableSitesTable() { table = new UpdatableSitesTable(tableModel); table.setColumnSelectionAllowed(false); table.setRowSelectionAllowed(false); - table.setRowHeight((int) (table.getRowHeight()*1.5)); + table.setRowHeight((int) (table.getRowHeight() * 1.5)); table.setShowVerticalLines(false); - ((DefaultTableCellRenderer)table.getTableHeader().getDefaultRenderer()) - .setHorizontalAlignment(JLabel.LEFT); + ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()) + .setHorizontalAlignment(JLabel.LEFT); table.setDefaultRenderer(URLChange.class, new URLRenderer()); TableColumn urlColumn = table.getColumnModel().getColumn(urlCol); urlColumn.setCellEditor(new URLComboBoxEditor()); @@ -255,15 +269,17 @@ private JTable createUpdatableSitesTable() { return table; } - private static String wrapToolTip(final String description, final String maintainer) { + private static String wrapToolTip(final String description, + final String maintainer) + { if (description == null) return null; - return "

" + description.replaceAll("\n", "
") - + (maintainer != null ? "

Maintainer: " + maintainer + "

": "") - + "

"; + return "

" + description.replaceAll("\n", "
") + + (maintainer != null ? "

Maintainer: " + maintainer + "

" : "") + + "

"; } private String getUpdateSiteName(int row) { - return getUpdateSite( row ).getName(); + return getUpdateSite(row).getName(); } private UpdateSite getUpdateSite(int row) { @@ -277,19 +293,22 @@ private URLChange getUrlChange(int row) { private void updateGeneralChoices() { int updated = 0; int kept = 0; - for(URLChange change : urlChanges ) { - if(change.isApproved()) { + for (URLChange change : urlChanges) { + if (change.isApproved()) { updated++; - } else { + } + else { kept++; } } - if(kept == 0) { + if (kept == 0) { updateAll.setSelected(true); - }else { - if(updated == 0) { + } + else { + if (updated == 0) { keepAll.setSelected(true); - } else { + } + else { manualChoice.setSelected(true); } } @@ -298,10 +317,10 @@ private void updateGeneralChoices() { private void submitAndDispose() { okPressed = true; - if(stopAsking.isSelected()) { + if (stopAsking.isSelected()) { // stop trying to update the URLs urlChanges.forEach(change -> { - if(!change.isApproved()) { + if (!change.isApproved()) { change.updateSite().setKeepURL(true); } }); @@ -322,21 +341,21 @@ private void updateAll() { } private void updateTable() { - tableModel.fireTableRowsUpdated(0, tableModel.getRowCount()-1); + tableModel.fireTableRowsUpdated(0, tableModel.getRowCount() - 1); } @Override public void actionPerformed(ActionEvent e) { - if(e.getSource().equals(ok)) super.dispose(); - else if(e.getSource().equals(cancel)) dispose(); - else if(e.getSource().equals(submit)) submitAndDispose(); - else if(e.getSource().equals(updateAll)) updateAll(); - else if(e.getSource().equals(keepAll)) keepAll(); + if (e.getSource().equals(ok)) super.dispose(); + else if (e.getSource().equals(cancel)) dispose(); + else if (e.getSource().equals(submit)) submitAndDispose(); + else if (e.getSource().equals(updateAll)) updateAll(); + else if (e.getSource().equals(keepAll)) keepAll(); } @Override public void dispose() { - //reset choices, don't save available updated URLs and continue update + // reset choices, don't save available updated URLs and continue update urlChanges.forEach(change -> change.setApproved(false)); super.dispose(); } @@ -349,7 +368,8 @@ private class UpdatableTableDataModel extends DefaultTableModel { void setColumnWidths() { final TableColumnModel columnModel = table.getColumnModel(); - for (int i = 0; i < tableModel.widths.length && i < getColumnCount(); i++) + for (int i = 0; i < tableModel.widths.length && + i < getColumnCount(); i++) { final TableColumn column = columnModel.getColumn(i); column.setPreferredWidth(tableModel.widths[i]); @@ -371,7 +391,7 @@ public String getColumnName(final int column) { @Override public Class getColumnClass(final int column) { - if(column != nameCol) return URLChange.class; + if (column != nameCol) return URLChange.class; return String.class; } @@ -393,7 +413,7 @@ private String keepChoiceString(URLChange site) { } private String updateChoiceString(URLChange site) { - return "" + site.getNewURL() + "" + appendNew; + return "" + site.getNewURL() + "" + appendNew; } private class URLComboBoxEditor extends DefaultCellEditor { @@ -404,14 +424,22 @@ private class URLComboBoxEditor extends DefaultCellEditor { URLComboBoxEditor() { super(new JComboBox()); box.addPopupMenuListener(new PopupMenuListener() { + @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) {} + @Override - public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {stopCellEditing();} + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + stopCellEditing(); + } + @Override - public void popupMenuCanceled(PopupMenuEvent e) {stopCellEditing();} + public void popupMenuCanceled(PopupMenuEvent e) { + stopCellEditing(); + } }); - box.setFont(box.getFont().deriveFont(box.getFont().getStyle() & ~Font.BOLD)); + box.setFont(box.getFont().deriveFont(box.getFont().getStyle() & + ~Font.BOLD)); } @Override @@ -420,17 +448,21 @@ public Object getCellEditorValue() { } @Override - public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { + public Component getTableCellEditorComponent(JTable table, Object value, + boolean isSelected, int row, int column) + { URLChange change = getUrlChange(row); box.removeAllItems(); - box.addItem(keepChoiceString( change )); - box.addItem(updateChoiceString( change )); - box.setSelectedIndex( change.isApproved() ? 1 : 0); - return editor.getTableCellEditorComponent(table, value, isSelected, row, column); + box.addItem(keepChoiceString(change)); + box.addItem(updateChoiceString(change)); + box.setSelectedIndex(change.isApproved() ? 1 : 0); + return editor.getTableCellEditorComponent(table, value, isSelected, row, + column); } } private class UpdatableSitesTable extends JTable { + UpdatableSitesTable(UpdatableTableDataModel tableModel) { super(tableModel); } @@ -446,14 +478,15 @@ public boolean isCellEditable(final int row, final int column) { } @Override - public void setValueAt(final Object value, final int row, final int column) + public void setValueAt(final Object value, final int row, + final int column) { URLChange change = getUrlChange(row); - if(column == urlCol) { - if(value.equals(keepChoiceString( change ))) { + if (column == urlCol) { + if (value.equals(keepChoiceString(change))) { change.setApproved(false); } - if(value.equals(updateChoiceString( change ))) { + if (value.equals(updateChoiceString(change))) { change.setApproved(true); } tableModel.fireTableRowsUpdated(row, row); @@ -462,13 +495,16 @@ public void setValueAt(final Object value, final int row, final int column) } @Override - public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { + public Component prepareRenderer(TableCellRenderer renderer, int row, + int column) + { Component component = super.prepareRenderer(renderer, row, column); if (component instanceof JComponent) { final UpdateSite site = getUpdateSite(row); if (site != null) { JComponent jcomponent = (JComponent) component; - jcomponent.setToolTipText(wrapToolTip(site.getDescription(), site.getMaintainer())); + jcomponent.setToolTipText(wrapToolTip(site.getDescription(), site + .getMaintainer())); } } return component; @@ -480,10 +516,11 @@ private class URLRenderer extends JLabel implements TableCellRenderer { URLPanel panel = new URLPanel(); @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, - boolean hasFocus, int rowIndex, int vColIndex) { - if(value == null) return null; - panel.update( (URLChange) value ); + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) + { + if (value == null) return null; + panel.update((URLChange) value); return panel; } } @@ -497,15 +534,17 @@ private class URLPanel extends JPanel { setOpaque(false); urlLabel = new JLabel(); choiceLabel = new JLabel(); - choiceLabel.setFont(choiceLabel.getFont().deriveFont(choiceLabel.getFont().getStyle() & ~Font.BOLD)); - choiceLabel.setBorder(BorderFactory.createEmptyBorder(0,0,0,10)); + choiceLabel.setFont(choiceLabel.getFont().deriveFont(choiceLabel.getFont() + .getStyle() & ~Font.BOLD)); + choiceLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); add(urlLabel, "dock west"); add(choiceLabel, "dock east"); } - public void update(URLChange change ) { - urlLabel.setText( change.isApproved() ? change.getNewURL() : change.updateSite().getURL()); - choiceLabel.setText( change.isApproved() ? appendNew : appendOld ); + public void update(URLChange change) { + urlLabel.setText(change.isApproved() ? change.getNewURL() : change + .updateSite().getURL()); + choiceLabel.setText(change.isApproved() ? appendNew : appendOld); } } diff --git a/src/main/java/net/imagej/ui/swing/updater/SitesDialog.java b/src/main/java/net/imagej/ui/swing/updater/SitesDialog.java index 61eaeb5..0c3389f 100644 --- a/src/main/java/net/imagej/ui/swing/updater/SitesDialog.java +++ b/src/main/java/net/imagej/ui/swing/updater/SitesDialog.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -90,7 +90,7 @@ /** * The dialog in which the user can choose which update sites to follow. - * + * * @author Johannes Schindelin */ @SuppressWarnings("serial") @@ -108,8 +108,7 @@ public class SitesDialog extends JDialog implements ActionListener { private boolean searchDescription, searchURL; private TableRowSorter sorter; - public SitesDialog(final UpdaterFrame owner, final FilesCollection files) - { + public SitesDialog(final UpdaterFrame owner, final FilesCollection files) { super(owner, "Manage Update Sites"); updaterFrame = owner; this.files = files; @@ -130,7 +129,8 @@ public void valueChanged(final ListSelectionEvent e) { @Override public boolean isCellEditable(final int row, final int column) { - return column >= 0 && column < getColumnCount() && row >= 0 && row < getRowCount(); + return column >= 0 && column < getColumnCount() && row >= 0 && + row < getRowCount(); } @Override @@ -138,73 +138,86 @@ public TableCellEditor getCellEditor(final int row, final int column) { if (column == 0) return super.getCellEditor(row, column); final JTextField field = new JTextField(); return new DefaultCellEditor(field) { + @Override public boolean stopCellEditing() { if (row >= sites.size()) { - // In case of stopping after a row has been removed, properly stop editing + // In case of stopping after a row has been removed, properly stop + // editing return super.stopCellEditing(); } String value = field.getText(); - if ((column == 2 || column == 4) && !value.equals("") && !value.endsWith("/")) { + if ((column == 2 || column == 4) && !value.equals("") && !value + .endsWith("/")) + { value += "/"; } if (column == 1) { - if (value.equals(getUpdateSiteName(row))) return super.stopCellEditing(); + if (value.equals(getUpdateSiteName(row))) + return super.stopCellEditing(); if (files.getUpdateSite(value, true) != null) { error("Update site '" + value + "' exists already!"); return false; } - } else if (column == 2) { + } + else if (column == 2) { if ("/".equals(value)) value = ""; final UpdateSite site = getUpdateSite(row); if (value.equals(site.getURL())) return super.stopCellEditing(); - if(!HTTPSUtil.supportsURLProtocol(value)) { - if(showYesNoQuestion("Convert HTTPS URL to HTTP?", - "Your installation cannot handle secure communication (HTTPS).\n" + - "Please download a recent version of this software.\n\n" + - "Do you want to use the insecure URL of this update site (HTTP)?")) { + if (!HTTPSUtil.supportsURLProtocol(value)) { + if (showYesNoQuestion("Convert HTTPS URL to HTTP?", + "Your installation cannot handle secure communication (HTTPS).\n" + + "Please download a recent version of this software.\n\n" + + "Do you want to use the insecure URL of this update site (HTTP)?")) + { value = HTTPSUtil.userSiteConvertToHTTP(value); field.setText(value); - } else return false; + } + else return false; } if (validURL(value)) { site.setURL(value); boolean wasActive = site.isActive(); activateUpdateSite(site); if (!wasActive && site.isActive()) tableModel.rowChanged(row); - } else { + } + else { if (site.getHost() == null || site.getHost().equals("")) { - error("URL does not refer to an update site: " + value + "\n" - + "If you want to initialize that site, you need to provide upload information first."); + error("URL does not refer to an update site: " + value + + "\n" + + "If you want to initialize that site, you need to provide upload information first."); return false; } if (!showYesNoQuestion("Initialize upload site?", - "It appears that the URL\n" - + "\t" + value + "\n" - + "is not (yet) valid. " - + "Do you want to initialize it (host: " - + site.getHost() + "; directory: " - + site.getUploadDirectory() + ")?")) - return false; - if (!initializeUpdateSite(site.getName(), - value, site.getHost(), site.getUploadDirectory())) + "It appears that the URL\n" + "\t" + value + "\n" + + "is not (yet) valid. " + + "Do you want to initialize it (host: " + site.getHost() + + "; directory: " + site.getUploadDirectory() + ")?")) return false; + if (!initializeUpdateSite(site.getName(), value, site.getHost(), + site.getUploadDirectory())) return false; } - } else if (column == 3) { + } + else if (column == 3) { final UpdateSite site = getUpdateSite(row); if (value.equals(site.getHost())) return super.stopCellEditing(); final int colon = value.indexOf(':'); if (colon > 0) { final String protocol = value.substring(0, colon); - final UploaderService uploaderService = updaterFrame.getUploaderService(); - if (null == uploaderService.installUploader(protocol, files, updaterFrame.getProgress(null))) { + final UploaderService uploaderService = updaterFrame + .getUploaderService(); + if (null == uploaderService.installUploader(protocol, files, + updaterFrame.getProgress(null))) + { error("Unknown upload protocol: " + protocol); return false; } } - } else if (column == 4) { + } + else if (column == 4) { final UpdateSite site = getUpdateSite(row); - if (value.equals(site.getUploadDirectory())) return super.stopCellEditing(); + if (value.equals(site.getUploadDirectory())) + return super.stopCellEditing(); } updaterFrame.enableApplyOrUpload(); return super.stopCellEditing(); @@ -213,7 +226,8 @@ public boolean stopCellEditing() { } @Override - public void setValueAt(final Object value, final int row, final int column) + public void setValueAt(final Object value, final int row, + final int column) { if (row < sites.size()) { final UpdateSite site = getUpdateSite(row); @@ -222,38 +236,41 @@ public void setValueAt(final Object value, final int row, final int column) if (column == 0 || column == 2) { activateUpdateSite(site); } - } else { + } + else { deactivateUpdateSite(site); } - } else { - final String string = (String)value; + } + else { + final String string = (String) value; // if the name changed, or if we auto-fill the name from the URL switch (column) { - case 1: - final String name = site.getName(); - if (name.equals(string)) return; - files.renameUpdateSite(name, string); - break; - case 2: - if (site.getURL().equals(string)) return; - boolean active = site.isActive(); - if (active) deactivateUpdateSite(site); - site.setURL(string); - if (active && validURL(string)) activateUpdateSite(site); - break; - case 3: - if (string.equals(site.getHost())) return; - site.setHost(string); - break; - case 4: - if (string.equals(site.getUploadDirectory())) return; - site.setUploadDirectory(string); - break; - case 5: - // do nothing: description column - break; - default: - updaterFrame.log.error("Whoa! Column " + column + " is not handled!"); + case 1: + final String name = site.getName(); + if (name.equals(string)) return; + files.renameUpdateSite(name, string); + break; + case 2: + if (site.getURL().equals(string)) return; + boolean active = site.isActive(); + if (active) deactivateUpdateSite(site); + site.setURL(string); + if (active && validURL(string)) activateUpdateSite(site); + break; + case 3: + if (string.equals(site.getHost())) return; + site.setHost(string); + break; + case 4: + if (string.equals(site.getUploadDirectory())) return; + site.setUploadDirectory(string); + break; + case 5: + // do nothing: description column + break; + default: + updaterFrame.log.error("Whoa! Column " + column + + " is not handled!"); } } } @@ -261,16 +278,19 @@ public void setValueAt(final Object value, final int row, final int column) } @Override - public Component prepareRenderer(TableCellRenderer renderer,int row, int column) { + public Component prepareRenderer(TableCellRenderer renderer, int row, + int column) + { Component component = super.prepareRenderer(renderer, row, column); if (component instanceof JComponent) { final UpdateSite site = getUpdateSite(row); if (site != null) { JComponent jcomponent = (JComponent) component; - jcomponent.setToolTipText(wrapToolTip(site.getDescription(), site.getMaintainer())); + jcomponent.setToolTipText(wrapToolTip(site.getDescription(), site + .getMaintainer())); } } - return component; + return component; } }; table.setColumnSelectionAllowed(false); @@ -301,9 +321,11 @@ public void insertUpdate(final DocumentEvent e) { }); // Add all components to dialog - final JPanel labeledSearchField = SwingTools.labelComponentRigid(" Search:", searchTerm); - scrollpane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + final JPanel labeledSearchField = SwingTools.labelComponentRigid(" Search:", + searchTerm); + scrollpane = new JScrollPane(table, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); final JPanel buttons = new JPanel(); final GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; @@ -326,24 +348,31 @@ public void insertUpdate(final DocumentEvent e) { // Adjust table size, column widths and scrollbars tableModel.setColumnWidths(); - scrollpane.setPreferredSize(new Dimension(tableModel.tableWidth, 12 * table.getRowHeight())); + scrollpane.setPreferredSize(new Dimension(tableModel.tableWidth, 12 * table + .getRowHeight())); contentPane.addComponentListener(new ComponentAdapter() { + @Override public void componentResized(final ComponentEvent e) { if (table.getPreferredSize().width < getWidth()) { // unlikely to happen given current column widths table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); - } else { + } + else { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); } } }); - addNewSite = SwingTools.button("Add Unlisted Site", "Add a new entry for a site not listed", this, buttons); - remove = SwingTools.button("Remove", "Remove highlighted site from list", this, buttons); + addNewSite = SwingTools.button("Add Unlisted Site", + "Add a new entry for a site not listed", this, buttons); + remove = SwingTools.button("Remove", "Remove highlighted site from list", + this, buttons); remove.setEnabled(false); - checkForUpdates = SwingTools.button("Validate URLs", "Check whether update sites are using outdated URLs", this, buttons); - close = SwingTools.button("Apply and Close", "Confirm activations and dismiss [ESC]", this, buttons); + checkForUpdates = SwingTools.button("Validate URLs", + "Check whether update sites are using outdated URLs", this, buttons); + close = SwingTools.button("Apply and Close", + "Confirm activations and dismiss [ESC]", this, buttons); getRootPane().setDefaultButton(close); escapeCancels(this); @@ -354,24 +383,28 @@ public void componentResized(final ComponentEvent e) { private JButton searchOptionsButton() { final JPopupMenu popup = new JPopupMenu(); - final JCheckBoxMenuItem jcbmi0 = new JCheckBoxMenuItem("Search Site Names", true); + final JCheckBoxMenuItem jcbmi0 = new JCheckBoxMenuItem("Search Site Names", + true); jcbmi0.setToolTipText("Site names are always searched"); jcbmi0.setEnabled(false); // dummy checkbox: Site names are always searched popup.add(jcbmi0); - final JCheckBoxMenuItem jcbmi1 = new JCheckBoxMenuItem("Search Site URLs", isSearchURL()); + final JCheckBoxMenuItem jcbmi1 = new JCheckBoxMenuItem("Search Site URLs", + isSearchURL()); jcbmi1.addItemListener(e -> { setSearchURL(jcbmi1.isSelected()); filterTable(); }); popup.add(jcbmi1); - final JCheckBoxMenuItem jcbmi2 = new JCheckBoxMenuItem("Search Site Descriptions", isSearchDescription()); + final JCheckBoxMenuItem jcbmi2 = new JCheckBoxMenuItem( + "Search Site Descriptions", isSearchDescription()); jcbmi2.addItemListener(e -> { setSearchDescription(jcbmi2.isSelected()); filterTable(); }); popup.add(jcbmi2); final JButton options = optionsButton(searchTerm); - options.addActionListener(e -> popup.show(options, options.getWidth() / 2, options.getHeight() / 2)); + options.addActionListener(e -> popup.show(options, options.getWidth() / 2, + options.getHeight() / 2)); return options; } @@ -380,11 +413,13 @@ private JButton optionsButton(final JComponent main) { b.setToolTipText("Search options"); final float factor = .5f; final Insets insets = b.getMargin(); - if (insets != null) - b.setMargin(new Insets((int) (insets.top * factor), (int) (insets.left * factor), - (int) (insets.bottom * factor), (int) (insets.right * factor))); - b.setPreferredSize(new Dimension(b.getPreferredSize().width, (int) main.getPreferredSize().getHeight())); - b.setMaximumSize(new Dimension(b.getMaximumSize().width, (int) main.getPreferredSize().getHeight())); + if (insets != null) b.setMargin(new Insets((int) (insets.top * factor), + (int) (insets.left * factor), (int) (insets.bottom * factor), + (int) (insets.right * factor))); + b.setPreferredSize(new Dimension(b.getPreferredSize().width, (int) main + .getPreferredSize().getHeight())); + b.setMaximumSize(new Dimension(b.getMaximumSize().width, (int) main + .getPreferredSize().getHeight())); return b; } @@ -412,9 +447,10 @@ private void filterTable() { final String query = Pattern.quote(searchTerm.getText()); SwingTools.invokeOnEDT(() -> { try { - sorter.setRowFilter(RowFilter.regexFilter("(?i)" + query, - cols.stream().mapToInt(i -> i).toArray())); - } catch (final java.util.regex.PatternSyntaxException e) { + sorter.setRowFilter(RowFilter.regexFilter("(?i)" + query, cols.stream() + .mapToInt(i -> i).toArray())); + } + catch (final java.util.regex.PatternSyntaxException e) { // do nothing if expression doesn't parse return; } @@ -428,14 +464,16 @@ private static String inlineSynopsis(final UpdateSite site) { if (s != null) sb.append(s.replace("\n", " ")); s = site.getMaintainer(); if (s != null) sb.append(" Maintainer:").append(s); - return sb.toString(); + return sb.toString(); } - private static String wrapToolTip(final String description, final String maintainer) { + private static String wrapToolTip(final String description, + final String maintainer) + { if (description == null) return null; - return "

" + description.replaceAll("\n", "
") - + (maintainer != null ? "

Maintainer: " + maintainer + "

": "") - + "

"; + return "

" + description.replaceAll("\n", "
") + + (maintainer != null ? "

Maintainer: " + maintainer + "

" : "") + + "

"; } /* @@ -457,14 +495,14 @@ protected UpdateSite getUpdateSite(int row) { } private void addNew() { - searchTerm.setText(""); // Reset filtering so that displayed rows match row model + searchTerm.setText(""); // Reset filtering so that displayed rows match row + // model table.requestFocusInWindow(); add(new UpdateSite(makeUniqueSiteName("New"), "", "", "", null, null, 0l)); - table.changeSelection( table.getRowCount()-1, 2, false, false); + table.changeSelection(table.getRowCount() - 1, 2, false, false); - if (table.editCellAt(table.getRowCount()-1, 2)) - { + if (table.editCellAt(table.getRowCount() - 1, 2)) { Component editor = table.getEditorComponent(); editor.requestFocusInWindow(); } @@ -482,9 +520,10 @@ private void add(final UpdateSite site) { private String makeUniqueSiteName(final String prefix) { final Set names = new HashSet<>(); - for (final UpdateSite site : sites) names.add(site.getName()); + for (final UpdateSite site : sites) + names.add(site.getName()); if (!names.contains(prefix)) return prefix; - for (int i = 2; ; i++) { + for (int i = 2;; i++) { if (!names.contains(prefix + "-" + i)) return prefix + "-" + i; } } @@ -493,9 +532,8 @@ protected void delete(final int row) { final UpdateSite site = getUpdateSite(row); final String name = site.getName(); if (!showYesNoQuestion("Remove " + name + "?", - "Do you really want to remove the site '" + name + "' from the list?\n" - + "URL: " + getUpdateSite(row).getURL())) - return; + "Do you really want to remove the site '" + name + "' from the list?\n" + + "URL: " + getUpdateSite(row).getURL())) return; files.removeUpdateSite(site.getName()); sites.remove(row); tableModel.rowChanged(row); @@ -511,19 +549,17 @@ protected void delete(final int row) { private void deactivateUpdateSite(final UpdateSite site) { int count = files.deactivateUpdateSite(site); if (count > 0) { - info("" + - count + (count == 1 ? " file is" : " files are") + - " installed from the site '" + - site.getName() + - "' and will be updated/uninstalled\n"); + info("" + count + (count == 1 ? " file is" : " files are") + + " installed from the site '" + site.getName() + + "' and will be updated/uninstalled\n"); updaterFrame.updateFilesTable(); } } private void updateAvailableUpdateSites() { new Thread(() -> { - List - changes = AvailableSites.initializeAndAddSites(files, (Logger) null); + List changes = AvailableSites.initializeAndAddSites(files, + (Logger) null); boolean reviewChanges = ReviewSiteURLsDialog.shouldBeDisplayed(changes); AtomicBoolean changesApproved = new AtomicBoolean(!reviewChanges); try { @@ -532,22 +568,22 @@ private void updateAvailableUpdateSites() { dialog.setVisible(true); changesApproved.set(dialog.isOkPressed()); }); - } catch (InterruptedException | InvocationTargetException e) { + } + catch (InterruptedException | InvocationTargetException e) { e.printStackTrace(); } - if(changesApproved.get()) { + if (changesApproved.get()) { searchTerm.setText(""); // Reset filtering AvailableSites.applySitesURLUpdates(files, changes); } - tableModel.rowsChanged(0, tableModel.getRowCount()-1); + tableModel.rowsChanged(0, tableModel.getRowCount() - 1); }).start(); } @Override public void setVisible(boolean b) { - if (b) - searchTerm.requestFocusInWindow(); + if (b) searchTerm.requestFocusInWindow(); super.setVisible(b); } @@ -565,15 +601,21 @@ else if (source == close) { protected class DataModel extends DefaultTableModel { protected int tableWidth; - protected String[] headers = { "Active", "Name", "URL", "Host", "Directory on Host", "Description" }; - private String[] canonicalRows = { "Active", "Fuzzy logic and artificial neural", - "sites.imagej.net/Fiji-Legacy/", "webdav:User", "/path", " Large description with maintainer name" }; + protected String[] headers = { "Active", "Name", "URL", "Host", + "Directory on Host", "Description" }; + private String[] canonicalRows = { "Active", + "Fuzzy logic and artificial neural", "sites.imagej.net/Fiji-Legacy/", + "webdav:User", "/path", " Large description with maintainer name" }; public void setColumnWidths() { - table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // otherwise horizontal scrollbar is not displayed + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // otherwise horizontal + // scrollbar is not + // displayed final TableColumnModel columnModel = table.getColumnModel(); final FontMetrics fm = table.getFontMetrics(table.getFont()); - for (int i = 0; i < tableModel.headers.length && i < getColumnCount(); i++) { + for (int i = 0; i < tableModel.headers.length && + i < getColumnCount(); i++) + { final TableColumn column = columnModel.getColumn(i); column.setPreferredWidth(fm.stringWidth(canonicalRows[i])); tableWidth += column.getPreferredWidth(); @@ -627,12 +669,12 @@ public void rowsChanged(final int firstRow, final int lastRow) { } protected boolean validURL(String url) { - if (!url.endsWith("/")) - url += "/"; + if (!url.endsWith("/")) url += "/"; try { - return files.util.getLastModified(new URL(url - + UpdaterUtil.XML_COMPRESSED)) != -1; - } catch (MalformedURLException e) { + return files.util.getLastModified(new URL(url + + UpdaterUtil.XML_COMPRESSED)) != -1; + } + catch (MalformedURLException e) { updaterFrame.log.error(e); return false; } @@ -641,7 +683,8 @@ protected boolean validURL(String url) { protected boolean activateUpdateSite(final UpdateSite updateSite) { try { files.activateUpdateSite(updateSite, updaterFrame.getProgress(null)); - } catch (final Exception e) { + } + catch (final Exception e) { e.printStackTrace(); error("Not a valid URL: " + updateSite.getURL()); return false; @@ -650,30 +693,28 @@ protected boolean activateUpdateSite(final UpdateSite updateSite) { return true; } - protected boolean initializeUpdateSite(final String siteName, - String url, final String host, String uploadDirectory) { - if (!url.endsWith("/")) - url += "/"; - if (!uploadDirectory.endsWith("/")) - uploadDirectory += "/"; + protected boolean initializeUpdateSite(final String siteName, String url, + final String host, String uploadDirectory) + { + if (!url.endsWith("/")) url += "/"; + if (!uploadDirectory.endsWith("/")) uploadDirectory += "/"; boolean result; try { - result = updaterFrame.initializeUpdateSite(url, host, - uploadDirectory) && validURL(url); - } catch (final InstantiationException e) { + result = updaterFrame.initializeUpdateSite(url, host, uploadDirectory) && + validURL(url); + } + catch (final InstantiationException e) { updaterFrame.log.error(e); result = false; } - if (result) - info("Initialized update site '" + siteName + "'"); - else - error("Could not initialize update site '" + siteName + "'"); + if (result) info("Initialized update site '" + siteName + "'"); + else error("Could not initialize update site '" + siteName + "'"); return result; } @Override public void dispose() { - table.editCellAt(0,0); + table.editCellAt(0, 0); super.dispose(); updaterFrame.updateFilesTable(); updaterFrame.enableApplyOrUpload(); diff --git a/src/main/java/net/imagej/ui/swing/updater/SwingAuthenticator.java b/src/main/java/net/imagej/ui/swing/updater/SwingAuthenticator.java index c0c1c3d..2560311 100644 --- a/src/main/java/net/imagej/ui/swing/updater/SwingAuthenticator.java +++ b/src/main/java/net/imagej/ui/swing/updater/SwingAuthenticator.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -43,7 +43,7 @@ /** * TODO - * + * * @author Johannes Schindelin */ public class SwingAuthenticator extends Authenticator { @@ -53,7 +53,8 @@ protected PasswordAuthentication getPasswordAuthentication() { final JPanel panel = new JPanel(); panel.setLayout(new MigLayout("wrap 2")); - panel.add(new JLabel(getRequestingHost() + " asks for authentication:"), "span 2"); + panel.add(new JLabel(getRequestingHost() + " asks for authentication:"), + "span 2"); panel.add(new JLabel(" " + getRequestingPrompt()), "span 2"); panel.add(new JLabel("User:")); @@ -71,11 +72,13 @@ protected PasswordAuthentication getPasswordAuthentication() { final byte[] bytes; try { bytes = string.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { + } + catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } final char[] chars = new char[bytes.length]; - for (int i = 0; i < bytes.length; i++) chars[i] = (char)(bytes[i] & 0xff); + for (int i = 0; i < bytes.length; i++) + chars[i] = (char) (bytes[i] & 0xff); return new PasswordAuthentication(user.getText(), chars); } diff --git a/src/main/java/net/imagej/ui/swing/updater/SwingTools.java b/src/main/java/net/imagej/ui/swing/updater/SwingTools.java index 67d6786..dcf2316 100644 --- a/src/main/java/net/imagej/ui/swing/updater/SwingTools.java +++ b/src/main/java/net/imagej/ui/swing/updater/SwingTools.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -62,7 +62,7 @@ /** * Helper functions to instantiated Swing components. - * + * * @author Johannes Schindelin */ @SuppressWarnings("serial") @@ -88,8 +88,8 @@ public static JScrollPane scrollPane(final Component component, { final JScrollPane scroll = new JScrollPane(component); scroll.getViewport().setBackground(component.getBackground()); - if (width > -1 && height > -1) - scroll.setPreferredSize(new Dimension(width, height)); + if (width > -1 && height > -1) scroll.setPreferredSize(new Dimension(width, + height)); if (addTo != null) addTo.add(scroll); return scroll; } @@ -202,8 +202,8 @@ public static void addAccelerator(final Component source, final JComponent container, final ActionListener listener, final int key, final int modifiers) { - container.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( - KeyStroke.getKeyStroke(key, modifiers), source); + container.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke + .getKeyStroke(key, modifiers), source); if (container.getActionMap().get(source) != null) return; container.getActionMap().put(source, new AbstractAction() { @@ -220,34 +220,34 @@ public static boolean showQuestion(final Component owner, final String title, final String question) { return JOptionPane.showConfirmDialog(owner, question, title, - JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION; + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION; } public static boolean showYesNoQuestion(final Component owner, final String title, final String question) { return JOptionPane.showConfirmDialog(owner, question, title, - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION; + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION; } - public static void showMessageBox(final Component owner, - final String message, final int type) + public static void showMessageBox(final Component owner, final String message, + final int type) { SwingTools.invokeOnEDT(() -> { - final String title = - type == JOptionPane.ERROR_MESSAGE ? "Error" - : type == JOptionPane.WARNING_MESSAGE ? "Warning" : "Information"; + final String title = type == JOptionPane.ERROR_MESSAGE ? "Error" + : type == JOptionPane.WARNING_MESSAGE ? "Warning" : "Information"; JOptionPane.showMessageDialog(owner, message, title, type); }); } - public static String getChoice(final Component owner, - final List list, final String question, final String title) + public static String getChoice(final Component owner, final List list, + final String question, final String title) { final String[] array = list.toArray(new String[list.size()]); - final JOptionPane pane = - new JOptionPane(question, JOptionPane.QUESTION_MESSAGE, - JOptionPane.OK_CANCEL_OPTION, null, array); + final JOptionPane pane = new JOptionPane(question, + JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, array); pane.createDialog(owner, title).setVisible(true); return (String) pane.getValue(); } @@ -279,7 +279,8 @@ public void dispose() { public static int defaultFontSize() { try { return UIManager.getDefaults().getFont("TextPane.font").getSize(); - } catch (final NullPointerException ignored) { + } + catch (final NullPointerException ignored) { return 12; } } @@ -288,9 +289,11 @@ public static void invokeOnEDT(final Runnable job) { if (SwingUtilities.isEventDispatchThread()) job.run(); else try { SwingUtilities.invokeAndWait(job); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { return; - } catch (InvocationTargetException e) { + } + catch (InvocationTargetException e) { throw new RuntimeException(e); } } diff --git a/src/main/java/net/imagej/ui/swing/updater/SwingUserInterface.java b/src/main/java/net/imagej/ui/swing/updater/SwingUserInterface.java index 9b07809..0def303 100644 --- a/src/main/java/net/imagej/ui/swing/updater/SwingUserInterface.java +++ b/src/main/java/net/imagej/ui/swing/updater/SwingUserInterface.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,7 +49,7 @@ /** * TODO - * + * * @author Johannes Schindelin */ public class SwingUserInterface extends UpdaterUserInterface { @@ -57,7 +57,9 @@ public class SwingUserInterface extends UpdaterUserInterface { protected final LogService log; protected final StatusService statusService; - public SwingUserInterface(final LogService log, final StatusService statusService) { + public SwingUserInterface(final LogService log, + final StatusService statusService) + { this.log = log; this.statusService = statusService; } @@ -169,6 +171,7 @@ public String getString(final String title) { panel.add(new JLabel("User")); final JTextField user = new JTextField() { + private static final long serialVersionUID = 1L; int counter = 5; @@ -185,7 +188,8 @@ public void paint(Graphics g) { panel.add(user); if (JOptionPane.showConfirmDialog(null, panel, title, - JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { + JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) + { return user.getText(); } return null; @@ -199,6 +203,7 @@ public String getPassword(final String title) { panel.add(new JLabel("Password:")); final JPasswordField password = new JPasswordField() { + private static final long serialVersionUID = 1L; int counter = 15; @@ -215,7 +220,7 @@ public void paint(Graphics g) { panel.add(password); int option = JOptionPane.showConfirmDialog(null, panel, title, - JOptionPane.OK_CANCEL_OPTION); + JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.CANCEL_OPTION || option < 0) return null; return new String(password.getPassword()); diff --git a/src/main/java/net/imagej/ui/swing/updater/UpdaterFrame.java b/src/main/java/net/imagej/ui/swing/updater/UpdaterFrame.java index b118d4f..cb4b8ce 100644 --- a/src/main/java/net/imagej/ui/swing/updater/UpdaterFrame.java +++ b/src/main/java/net/imagej/ui/swing/updater/UpdaterFrame.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -96,7 +96,7 @@ /** * TODO - * + * * @author Johannes Schindelin */ @SuppressWarnings("serial") @@ -130,17 +130,18 @@ public UpdaterFrame(final LogService log, final UploaderService uploaderService, final FilesCollection files) { super("ImageJ Updater"); - //setPreferredSize(new Dimension((easyMode) ? 700 : 900, 560)); + // setPreferredSize(new Dimension((easyMode) ? 700 : 900, 560)); this.log = log; this.uploaderService = uploaderService; this.files = files; // make sure that sezpoz finds the classes when triggered from the EDT - final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + final ClassLoader contextClassLoader = Thread.currentThread() + .getContextClassLoader(); SwingTools.invokeOnEDT(() -> { - if (contextClassLoader != null) - Thread.currentThread().setContextClassLoader(contextClassLoader); + if (contextClassLoader != null) Thread.currentThread() + .setContextClassLoader(contextClassLoader); }); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); @@ -188,8 +189,8 @@ public void insertUpdate(final DocumentEvent e) { viewOptions = new ViewOptions(); viewOptions.addActionListener(e -> updateFilesTable()); - viewOptionsPanel = - SwingTools.labelComponentRigid("View Options:", viewOptions); + viewOptionsPanel = SwingTools.labelComponentRigid("View Options:", + viewOptions); c.gridy = 2; gb.setConstraints(viewOptionsPanel, c); leftPanel.add(viewOptionsPanel); @@ -200,9 +201,8 @@ public void insertUpdate(final DocumentEvent e) { leftPanel.add(box); // Create labels to annotate table - chooseLabel = - SwingTools.label("Please choose what you want to install/uninstall:", - null); + chooseLabel = SwingTools.label( + "Please choose what you want to install/uninstall:", null); c.gridy = 4; gb.setConstraints(chooseLabel, c); leftPanel.add(chooseLabel); @@ -282,8 +282,8 @@ public void insertUpdate(final DocumentEvent e) { fileDetails = new FileDetails(this); fileDetails.setBackground(table.getBackground()); JTabbedPane tabbedPane = new JTabbedPane(); - tabbedPane.addTab("Details", null, SwingTools.scrollPane(fileDetails, -1, -1, null), - "Individual file information"); + tabbedPane.addTab("Details", null, SwingTools.scrollPane(fileDetails, -1, + -1, null), "Individual file information"); c.gridy = 6; c.weightx = 1; @@ -327,54 +327,58 @@ public void insertUpdate(final DocumentEvent e) { bottomPanel.add(Utils.hSpace()); bottomPanel.add(new FileActionButton(new Uninstall())); bottomPanel.add(Utils.hSpace()); - showChanges = - SwingTools.button("Diff", - "Show the differences to the uploaded version", e -> new Thread() { + showChanges = SwingTools.button("Diff", + "Show the differences to the uploaded version", e -> new Thread() + { + + @Override + public void run() { + for (final FileObject file : table.getSelectedFiles()) + try { + final DiffFile diff = new DiffFile(files, file, Mode.LIST_FILES); + diff.setLocationRelativeTo(UpdaterFrame.this); + diff.setVisible(true); + } + catch (MalformedURLException e) { + files.log.error(e); + UpdaterUserInterface.get().error( + "There was a problem obtaining the remote version of " + file + .getLocalFilename(true)); + } + } + }.start(), bottomPanel); + bottomPanel.add(Box.createHorizontalGlue()); + // Button to start actions + applyOrUpload = SwingTools.button("Apply Changes", + "Start installing/uninstalling/uploading files", e -> { + if (files.hasUploadOrRemove()) { + new Thread() { @Override public void run() { - for (final FileObject file : table.getSelectedFiles()) try { - final DiffFile diff = new DiffFile(files, file, Mode.LIST_FILES); - diff.setLocationRelativeTo(UpdaterFrame.this); - diff.setVisible(true); - } catch (MalformedURLException e) { - files.log.error(e); - UpdaterUserInterface.get().error("There was a problem obtaining the remote version of " + file.getLocalFilename(true)); + try { + upload(); } - } - }.start(), bottomPanel); - bottomPanel.add(Box.createHorizontalGlue()); - // Button to start actions - applyOrUpload = - SwingTools.button("Apply Changes", "Start installing/uninstalling/uploading files", - e -> { - if (files.hasUploadOrRemove()) { - new Thread() { - - @Override - public void run() { - try { - upload(); - } - catch (final InstantiationException e) { - log.error(e); - error("Could not upload (possibly unknown protocol)"); - } + catch (final InstantiationException e) { + log.error(e); + error("Could not upload (possibly unknown protocol)"); } - }.start(); - } - else if (files.hasChanges()) { - applyChanges(); - } - }, bottomPanel); + } + }.start(); + } + else if (files.hasChanges()) { + applyChanges(); + } + }, bottomPanel); enableApplyOrUpload(); bottomPanel.add(Utils.hSpace()); - cancel = SwingTools.button("Close", "Exit Updater [Esc]", e -> quit(), bottomPanel); + cancel = SwingTools.button("Close", "Exit Updater [Esc]", e -> quit(), + bottomPanel); // ======== End: BOTTOM PANEL ======== - getContentPane().setLayout( - new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); + getContentPane().setLayout(new BoxLayout(getContentPane(), + BoxLayout.Y_AXIS)); getContentPane().add(topPanel); getContentPane().add(summaryPanel); getContentPane().add(bottomPanel); @@ -392,9 +396,11 @@ public void setVisible(final boolean visible) { if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeAndWait(() -> setVisible(visible)); - } catch (final InterruptedException e) { + } + catch (final InterruptedException e) { // ignore - } catch (final InvocationTargetException e) { + } + catch (final InvocationTargetException e) { log.error(e); } return; @@ -418,11 +424,9 @@ public Progress getProgress(final String title) { } /** - * Sets the context class loader if necessary. - * - * If the current class cannot be found by the current Thread's context - * class loader, we should tell the Thread about the class loader that - * loaded this class. + * Sets the context class loader if necessary. If the current class cannot be + * found by the current Thread's context class loader, we should tell the + * Thread about the class loader that loaded this class. */ private void setClassLoaderIfNecessary() { ClassLoader thisLoader = getClass().getClassLoader(); @@ -494,8 +498,8 @@ public void addCustomViewOptions() { final Collection names = files.getUpdateSiteNames(false); if (names.size() > 1) for (final String name : names) - viewOptions.addCustomOption("View files of the '" + name + "' site", - files.forUpdateSite(name)); + viewOptions.addCustomOption("View files of the '" + name + "' site", files + .forUpdateSite(name)); } public void setViewOption(final ViewOptions.Option option) { @@ -519,8 +523,8 @@ public void updateFilesTable() { // Directly update the table for display table.setFiles(view); for (int i = 0; i < table.getRowCount(); i++) - if (selected.contains(table.getFile(i))) table.addRowSelectionInterval(i, - i); + if (selected.contains(table.getFile(i))) table.addRowSelectionInterval( + i, i); }); } @@ -558,8 +562,8 @@ public void setEasyMode(final boolean easyMode) { protected void showOrHide() { // make sure that *some* files are shown in advanced mode - if (!easyMode && table.getRowCount() == 0 && - viewOptions.getSelectedItem() == ViewOptions.Option.UPDATEABLE) + if (!easyMode && table.getRowCount() == 0 && viewOptions + .getSelectedItem() == ViewOptions.Option.UPDATEABLE) { viewOptions.setSelectedItem(ViewOptions.Option.ALL); final List keys = new ArrayList<>(); @@ -590,8 +594,8 @@ public void toggleEasyMode() { } public void install() { - final Installer installer = - new Installer(files, getProgress("Installing...")); + final Installer installer = new Installer(files, getProgress( + "Installing...")); try { installer.start(); updateFilesTable(); @@ -636,17 +640,18 @@ private void filesChangedWorker() { fileDetails.reset(); for (final FileObject file : table.getSelectedFiles()) fileDetails.showFileDetails(file); - if (fileDetails.getDocument().getLength() > 0 && - table.areAllSelectedFilesUploadable()) fileDetails - .setEditableForDevelopers(); + if (fileDetails.getDocument().getLength() > 0 && table + .areAllSelectedFilesUploadable()) fileDetails.setEditableForDevelopers(); for (final FileActionButton button : fileActions) button.enableIfValid(); - if (showChanges != null) showChanges.setEnabled(table.getSelectedFiles().iterator().hasNext()); + if (showChanges != null) showChanges.setEnabled(table.getSelectedFiles() + .iterator().hasNext()); enableApplyOrUpload(); - cancel.setText(files.hasChanges() || files.hasUpdateSitesChanges() ? "Cancel" : "Close"); + cancel.setText(files.hasChanges() || files.hasUpdateSitesChanges() + ? "Cancel" : "Close"); int install = 0, uninstall = 0, upload = 0; long bytesToDownload = 0, bytesToUpload = 0; @@ -674,12 +679,11 @@ private void filesChangedWorker() { bytesToUpload += file.filesize; } String text = ""; - if (install > 0) text += - " Install/update: " + install + (implicated > 0 ? "+" + implicated : "") + - " (" + sizeToString(bytesToDownload) + ")"; + if (install > 0) text += " Install/update: " + install + (implicated > 0 + ? "+" + implicated : "") + " (" + sizeToString(bytesToDownload) + ")"; if (uninstall > 0) text += " uninstall: " + uninstall; - if (files.hasUploadableSites() && upload > 0) text += - " upload: " + upload + " (" + sizeToString(bytesToUpload) + ")"; + if (files.hasUploadableSites() && upload > 0) text += " upload: " + upload + + " (" + sizeToString(bytesToUpload) + ")"; fileSummary.setText(text); } @@ -706,7 +710,8 @@ public void tableChanged(final TableModelEvent e) { // checkWritable() is guaranteed to be called after Checksummer ran public void checkWritable() { if (UpdaterUtil.isProtectedLocation(files.prefix(""))) { - error("

Windows' security model for the directory '" + files.prefix("") + "' is incompatible with the ImageJ updater.

" + + error("

Windows' security model for the directory '" + + files.prefix("") + "' is incompatible with the ImageJ updater.

" + "

Please install ImageJ into a user-writable directory, e.g. onto the Desktop.

"); return; } @@ -739,8 +744,8 @@ void enableApplyOrUpload() { } protected void upload() throws InstantiationException { - final ResolveDependencies resolver = - new ResolveDependencies(this, files, true); + final ResolveDependencies resolver = new ResolveDependencies(this, files, + true); if (!resolver.resolve()) return; final String errors = files.checkConsistency(); @@ -749,8 +754,8 @@ protected void upload() throws InstantiationException { return; } - final List possibleSites = - new ArrayList<>(files.getSiteNamesToUpload()); + final List possibleSites = new ArrayList<>(files + .getSiteNamesToUpload()); if (possibleSites.size() == 0) { error("Huh? No upload site?"); return; @@ -758,12 +763,12 @@ protected void upload() throws InstantiationException { String updateSiteName; if (possibleSites.size() == 1) updateSiteName = possibleSites.get(0); else { - updateSiteName = - SwingTools.getChoice(this, possibleSites, - "Which site do you want to upload to?", "Update site"); + updateSiteName = SwingTools.getChoice(this, possibleSites, + "Which site do you want to upload to?", "Update site"); if (updateSiteName == null) return; } - final FilesUploader uploader = new FilesUploader(uploaderService, files, updateSiteName, getProgress(null)); + final FilesUploader uploader = new FilesUploader(uploaderService, files, + updateSiteName, getProgress(null)); Progress progress = null; try { @@ -797,12 +802,11 @@ protected void upload() throws InstantiationException { } } - protected boolean initializeUpdateSite(final String url, - final String sshHost, final String uploadDirectory) - throws InstantiationException + protected boolean initializeUpdateSite(final String url, final String sshHost, + final String uploadDirectory) throws InstantiationException { - final FilesUploader uploader = - FilesUploader.initialUploader(uploaderService, url, sshHost, uploadDirectory, getProgress(null)); + final FilesUploader uploader = FilesUploader.initialUploader( + uploaderService, url, sshHost, uploadDirectory, getProgress(null)); Progress progress = null; try { if (!uploader.login()) return false; @@ -838,14 +842,16 @@ public void info(final String message) { } JButton easyButton() { - return SwingTools.button("Easy Mode", "Toggle between simplified and advanced view", e -> toggleEasyMode(), - null); + return SwingTools.button("Easy Mode", + "Toggle between simplified and advanced view", e -> toggleEasyMode(), + null); } JButton manageButton() { - return SwingTools.button("Manage Update Sites", - "Manage subscriptions of update sites for updating and uploading", - e -> new SitesDialog(UpdaterFrame.this, UpdaterFrame.this.files).setVisible(true), null); + return SwingTools.button("Manage Update Sites", + "Manage subscriptions of update sites for updating and uploading", + e -> new SitesDialog(UpdaterFrame.this, UpdaterFrame.this.files) + .setVisible(true), null); } private class CollapsibleLeftRightSplitPane extends JSplitPane { @@ -855,7 +861,9 @@ private class CollapsibleLeftRightSplitPane extends JSplitPane { int lastVisibleDividerLocation; private Dimension rightComponentPreferredSize; - CollapsibleLeftRightSplitPane(final Component leftComponent, final Component rightComponent) { + CollapsibleLeftRightSplitPane(final Component leftComponent, + final Component rightComponent) + { super(HORIZONTAL_SPLIT, leftComponent, rightComponent); defDividerSize = getDividerSize(); setDividerLocation(DEF_DIVIDER_LOCATION); @@ -866,22 +874,24 @@ private class CollapsibleLeftRightSplitPane extends JSplitPane { void setResizable(final boolean resizable) { if (resizable) { setDividerSize(defDividerSize); - } else { + } + else { setDividerSize(0); } setEnabled(resizable); - //((BasicSplitPaneUI) getUI()).getDivider().setEnabled(resizable); + // ((BasicSplitPaneUI) getUI()).getDivider().setEnabled(resizable); } void setRightPaneVisible(final boolean visible) { if (visible) { setDividerLocation(lastVisibleDividerLocation); getRightComponent().setPreferredSize(rightComponentPreferredSize); - } else { + } + else { lastVisibleDividerLocation = getDividerLocation(); rightComponentPreferredSize = getRightComponent().getPreferredSize(); setDividerLocation(1d); - getRightComponent().setPreferredSize(new Dimension(0,0)); + getRightComponent().setPreferredSize(new Dimension(0, 0)); } getRightComponent().setVisible(visible); setResizable(visible); @@ -905,17 +915,19 @@ static Component vSpace() { static GridBagConstraints gbConstraints() { return new GridBagConstraints(// - 0, 0, // x, y - 9, 1, // rows, cols - 0, 0, // weightx, weighty - GridBagConstraints.NORTHWEST, // anchor - GridBagConstraints.HORIZONTAL, // fill - new Insets(0, 0, 0, 0), // insets - 0, 0 // ipadx, ipady + 0, 0, // x, y + 9, 1, // rows, cols + 0, 0, // weightx, weighty + GridBagConstraints.NORTHWEST, // anchor + GridBagConstraints.HORIZONTAL, // fill + new Insets(0, 0, 0, 0), // insets + 0, 0 // ipadx, ipady ); } - static void equalizeDimensions(final JComponent source, final JComponent target) { + static void equalizeDimensions(final JComponent source, + final JComponent target) + { source.setMinimumSize(target.getMinimumSize()); source.setPreferredSize(target.getPreferredSize()); source.setMaximumSize(target.getMaximumSize()); diff --git a/src/main/java/net/imagej/ui/swing/updater/ViewOptions.java b/src/main/java/net/imagej/ui/swing/updater/ViewOptions.java index dfcd007..2829303 100644 --- a/src/main/java/net/imagej/ui/swing/updater/ViewOptions.java +++ b/src/main/java/net/imagej/ui/swing/updater/ViewOptions.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -36,19 +36,19 @@ /** * TODO - * + * * @author Johannes Schindelin */ @SuppressWarnings("serial") public class ViewOptions extends JComboBox { public static enum Option { - ALL("all files"), INSTALLED("installed files only"), UNINSTALLED( - "uninstalled files only"), UPTODATE("only up-to-date files"), UPDATEABLE( - "updateable files only"), - LOCALLY_MODIFIED("locally modified files only"), MANAGED( - "downloaded files only"), OTHERS("local-only files"), - CHANGES("changes"), SELECTED("selected"); + + ALL("all files"), INSTALLED("installed files only"), UNINSTALLED( + "uninstalled files only"), UPTODATE("only up-to-date files"), + UPDATEABLE("updateable files only"), LOCALLY_MODIFIED( + "locally modified files only"), MANAGED("downloaded files only"), + OTHERS("local-only files"), CHANGES("changes"), SELECTED("selected"); String label; @@ -100,11 +100,11 @@ public Iterable getIterable() { } public Iterable getView(final FileTable table) { - if (getSelectedIndex() >= customOptionStart) return ((CustomOption) getSelectedItem()) - .getIterable(); + if (getSelectedIndex() >= customOptionStart) + return ((CustomOption) getSelectedItem()).getIterable(); - final FilesCollection files = - table.files.clone(table.getAllFiles().notHidden()); + final FilesCollection files = table.files.clone(table.getAllFiles() + .notHidden()); files.sort(); switch ((Option) getSelectedItem()) { case INSTALLED: diff --git a/src/main/java/net/imagej/ui/swing/viewer/image/AbstractSwingImageDisplayViewer.java b/src/main/java/net/imagej/ui/swing/viewer/image/AbstractSwingImageDisplayViewer.java index 35070cd..4c3d7cf 100644 --- a/src/main/java/net/imagej/ui/swing/viewer/image/AbstractSwingImageDisplayViewer.java +++ b/src/main/java/net/imagej/ui/swing/viewer/image/AbstractSwingImageDisplayViewer.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -46,7 +46,7 @@ * A Swing image display viewer, which displays 2D planes in grayscale or * composite color. Intended to be subclassed by a concrete implementation that * provides a {@link DisplayWindow} in which the display should be housed. - * + * * @author Curtis Rueden * @author Lee Kamentsky * @author Grant Harris @@ -76,8 +76,8 @@ public JHotDrawImageCanvas getCanvas() { @Override public void view(final DisplayWindow w, final Display d) { super.view(w, d); - - // NB: resolve the racing condition when other consumer are looking up the + + // NB: resolve the racing condition when other consumer are looking up the // active display getContext().service(DisplayService.class).setActiveDisplay(getDisplay()); @@ -109,7 +109,7 @@ public Dataset capture() { } // -- Disposable methods -- - + /** * NB: a reference to the imgCanvas is held, ultimately, by a finalizable * parent of a javax.swing.JViewport. This means that the entire resource diff --git a/src/main/java/net/imagej/ui/swing/viewer/image/DatasetFigureView.java b/src/main/java/net/imagej/ui/swing/viewer/image/DatasetFigureView.java index 2cf4c7e..602ca8a 100644 --- a/src/main/java/net/imagej/ui/swing/viewer/image/DatasetFigureView.java +++ b/src/main/java/net/imagej/ui/swing/viewer/image/DatasetFigureView.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,11 +49,12 @@ /** * A figure view that links an ImageJ {@link DatasetView} to a JHotDraw * {@link ImageFigure}. - * + * * @author Curtis Rueden * @author Lee Kamentsky */ -public class DatasetFigureView extends AbstractContextual implements FigureView +public class DatasetFigureView extends AbstractContextual implements + FigureView { private final DatasetView datasetView; @@ -92,8 +93,8 @@ public void update() { log.debug("Updating image figure: " + this); final Image image = datasetView.getScreenImage().image(); final BufferedImage bufImage = AWTImageTools.makeBuffered(image); - figure.setBounds(new Rectangle2D.Double(0, 0, bufImage.getWidth(), - bufImage.getHeight())); + figure.setBounds(new Rectangle2D.Double(0, 0, bufImage.getWidth(), bufImage + .getHeight())); figure.setBufferedImage(bufImage); } diff --git a/src/main/java/net/imagej/ui/swing/viewer/image/FigureView.java b/src/main/java/net/imagej/ui/swing/viewer/image/FigureView.java index 359929f..e686825 100644 --- a/src/main/java/net/imagej/ui/swing/viewer/image/FigureView.java +++ b/src/main/java/net/imagej/ui/swing/viewer/image/FigureView.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -33,11 +33,10 @@ import org.jhotdraw.draw.Figure; - /** * A figure view renders a {@link DataView} with a linked JHotDraw * {@link Figure}. - * + * * @author Lee Kamentsky */ public interface FigureView { diff --git a/src/main/java/net/imagej/ui/swing/viewer/image/JHotDrawImageCanvas.java b/src/main/java/net/imagej/ui/swing/viewer/image/JHotDrawImageCanvas.java index 73be363..9ba8dc9 100644 --- a/src/main/java/net/imagej/ui/swing/viewer/image/JHotDrawImageCanvas.java +++ b/src/main/java/net/imagej/ui/swing/viewer/image/JHotDrawImageCanvas.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -103,7 +103,7 @@ /** * A renderer of an {@link ImageCanvas}, which uses JHotDraw's * {@link DefaultDrawingView} component to do most of the work. - * + * * @author Curtis Rueden * @author Lee Kamentsky */ @@ -213,7 +213,8 @@ public void addEventDispatcher(final AWTInputEventDispatcher dispatcher) { dispatcher.register(drawingView, true, true); } - public void addEventDispatcher(final AWTDropTargetEventDispatcher dispatcher) + public void addEventDispatcher( + final AWTDropTargetEventDispatcher dispatcher) { dispatcher.register(drawingView); } @@ -225,8 +226,8 @@ public void addEventDispatcher(final AWTDropTargetEventDispatcher dispatcher) public Dataset capture() { final ImageDisplay display = getDisplay(); if (display == null) return null; - final DatasetView datasetView = - imageDisplayService.getActiveDatasetView(display); + final DatasetView datasetView = imageDisplayService.getActiveDatasetView( + display); if (datasetView == null) return null; final ARGBScreenImage screenImage = datasetView.getScreenImage(); @@ -236,8 +237,8 @@ public Dataset capture() { final int h = pixels.getHeight(null); // draw the backdrop image info - final BufferedImage outputImage = - new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); + final BufferedImage outputImage = new BufferedImage(w, h, + BufferedImage.TYPE_INT_ARGB); final Graphics2D outputGraphics = outputImage.createGraphics(); outputGraphics.drawImage(pixels, 0, 0, null); @@ -247,9 +248,9 @@ public Dataset capture() { } // create a dataset that has view data with overlay info on top - final Dataset dataset = - datasetService.create(new long[] { w, h, 3 }, "Captured view", - new AxisType[] { Axes.X, Axes.Y, Axes.CHANNEL }, 8, false, false); + final Dataset dataset = datasetService.create(new long[] { w, h, 3 }, + "Captured view", new AxisType[] { Axes.X, Axes.Y, Axes.CHANNEL }, 8, + false, false); dataset.setRGBMerged(true); final RandomAccess> accessor = dataset.randomAccess(); for (int x = 0; x < w; x++) { @@ -283,7 +284,7 @@ public void adjustmentValueChanged(final AdjustmentEvent e) { /** * Responds to the JHotDraw figure selection event by selecting and * deselecting views whose state has changed. - * + * * @param event Event indicating that the figure selections have changed. */ @Override @@ -403,8 +404,8 @@ protected void onEvent(final FigureCreatedEvent event) { if (drawingView.getSelectedFigures().contains(event.getFigure())) { overlay.setSelected(true); } - final OverlayFigureView figureView = - new OverlayFigureView(displayViewer, overlay, event.getFigure()); + final OverlayFigureView figureView = new OverlayFigureView(displayViewer, + overlay, event.getFigure()); figureViews.add(figureView); display.add(overlay); display.update(); @@ -417,16 +418,16 @@ void rebuild() { FigureView figureView = getFigureView(dataView); if (figureView == null) { if (dataView instanceof DatasetView) { - figureView = - new DatasetFigureView(this.displayViewer, (DatasetView) dataView); + figureView = new DatasetFigureView(this.displayViewer, + (DatasetView) dataView); } else if (dataView instanceof OverlayView) { - figureView = - new OverlayFigureView(this.displayViewer, (OverlayView) dataView); + figureView = new OverlayFigureView(this.displayViewer, + (OverlayView) dataView); } else { - log.error("Don't know how to make a figure view for " + - dataView.getClass().getName()); + log.error("Don't know how to make a figure view for " + dataView + .getClass().getName()); continue; } figureViews.add(figureView); @@ -494,24 +495,24 @@ private void sync(final boolean updateCanvas) { final double canvasZoom = canvas.getZoomFactor(); final IntCoords canvasOffset = canvas.getPanOffset(); - final boolean sizeChanged = - uiSize.width != canvasWidth || uiSize.height != canvasHeight; - final boolean offsetChanged = - uiOffset.x != canvasOffset.x || uiOffset.y != canvasOffset.y; + final boolean sizeChanged = uiSize.width != canvasWidth || + uiSize.height != canvasHeight; + final boolean offsetChanged = uiOffset.x != canvasOffset.x || + uiOffset.y != canvasOffset.y; final boolean zoomChanged = uiZoom != canvasZoom; if (!sizeChanged && !offsetChanged && !zoomChanged) return; if (log.isDebug()) { - log.debug(getClass().getSimpleName() + " " + - (updateCanvas ? "syncCanvas: " : "syncUI: ") + "\n\tUI size = " + - uiSize.width + " x " + uiSize.height + "\n\tUI offset = " + uiOffset.x + - ", " + uiOffset.y + "\n\tUI zoom = " + uiZoom + "\n\tCanvas size = " + + log.debug(getClass().getSimpleName() + " " + (updateCanvas + ? "syncCanvas: " : "syncUI: ") + "\n\tUI size = " + uiSize.width + + " x " + uiSize.height + "\n\tUI offset = " + uiOffset.x + ", " + + uiOffset.y + "\n\tUI zoom = " + uiZoom + "\n\tCanvas size = " + canvasWidth + " x " + canvasHeight + "\n\tCanvas offset = " + canvasOffset.x + ", " + canvasOffset.y + "\n\tCanvas zoom = " + canvasZoom + "\n\t" + (sizeChanged ? "sizeChanged " : "") + - (offsetChanged ? "offsetChanged " : "") + - (zoomChanged ? "zoomChanged " : "")); + (offsetChanged ? "offsetChanged " : "") + (zoomChanged ? "zoomChanged " + : "")); } if (updateCanvas) { @@ -550,11 +551,10 @@ private void maybeResizeWindow() { final Rectangle bounds = StaticSwingUtils.getWorkSpaceBounds(); final RealRect imageBounds = getDisplay().getPlaneExtents(); final ImageCanvas canvas = getDisplay().getCanvas(); - final IntCoords topLeft = - canvas.dataToPanelCoords(new RealCoords(imageBounds.x, imageBounds.y)); - final IntCoords bottomRight = - canvas.dataToPanelCoords(new RealCoords( - imageBounds.x + imageBounds.width, imageBounds.y + imageBounds.height)); + final IntCoords topLeft = canvas.dataToPanelCoords(new RealCoords( + imageBounds.x, imageBounds.y)); + final IntCoords bottomRight = canvas.dataToPanelCoords(new RealCoords( + imageBounds.x + imageBounds.width, imageBounds.y + imageBounds.height)); if (bottomRight.x - topLeft.x > bounds.width) return; if (bottomRight.y - topLeft.y > bounds.height) return; @@ -579,8 +579,8 @@ private void activateTool(final Tool tool) { /** * Clears any resources associated with this canvas. This is necessary to * avoid deadlocks where finalization-dependent cleanup operations (e.g. - * PhantomReference queueing) are unable to proceed because this object - * is being held by a hard reference by the Finalizer (which the downstream + * PhantomReference queueing) are unable to proceed because this object is + * being held by a hard reference by the Finalizer (which the downstream * resources are waiting on) implicit in upstream {@link JViewport} use. */ @Override diff --git a/src/main/java/net/imagej/ui/swing/viewer/image/OverlayFigureView.java b/src/main/java/net/imagej/ui/swing/viewer/image/OverlayFigureView.java index 7acfe1b..697e049 100644 --- a/src/main/java/net/imagej/ui/swing/viewer/image/OverlayFigureView.java +++ b/src/main/java/net/imagej/ui/swing/viewer/image/OverlayFigureView.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -46,11 +46,12 @@ /** * A figure view that links an ImageJ {@link OverlayView} to a JHotDraw * {@link Figure}. - * + * * @author Curtis Rueden * @author Lee Kamentsky */ -public class OverlayFigureView extends AbstractContextual implements FigureView +public class OverlayFigureView extends AbstractContextual implements + FigureView { private final SwingImageDisplayViewer displayViewer; @@ -70,7 +71,7 @@ public class OverlayFigureView extends AbstractContextual implements FigureView /** * Constructor to use to discover the figure to use for an overlay - * + * * @param displayViewer - hook to this display viewer * @param overlayView - represent this overlay */ @@ -83,7 +84,7 @@ public OverlayFigureView(final SwingImageDisplayViewer displayViewer, /** * Constructor to use if the figure already exists, for instance if it was * created using the CreationTool - * + * * @param displayViewer - hook to this display viewer * @param overlayView - represent this overlay * @param figure - draw using this figure diff --git a/src/main/java/net/imagej/ui/swing/viewer/image/SwingImageDisplayPanel.java b/src/main/java/net/imagej/ui/swing/viewer/image/SwingImageDisplayPanel.java index 6053cb1..9213c35 100644 --- a/src/main/java/net/imagej/ui/swing/viewer/image/SwingImageDisplayPanel.java +++ b/src/main/java/net/imagej/ui/swing/viewer/image/SwingImageDisplayPanel.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -75,12 +75,14 @@ * pane containing an {@link ImageCanvas}, and panel containing dimensional * controllers. This panel is added to a top-level {@link DisplayWindow} display * container. - * + * * @author Curtis Rueden * @author Grant Harris * @author Barry DeZonia */ -public class SwingImageDisplayPanel extends JPanel implements ImageDisplayPanel { +public class SwingImageDisplayPanel extends JPanel implements + ImageDisplayPanel +{ private final SwingImageDisplayViewer displayViewer; private final ImageDisplay display; @@ -94,8 +96,7 @@ public class SwingImageDisplayPanel extends JPanel implements ImageDisplayPanel private final Map axisSliders = new ConcurrentHashMap<>(); - private final Map axisLabels = - new HashMap<>(); + private final Map axisLabels = new HashMap<>(); @Parameter private ImageDisplayService imageDisplayService; @@ -197,7 +198,8 @@ public void setLabel(final String s) { @Override public void redraw() { final DatasetView view = imageDisplayService.getActiveDatasetView(display); - if (view == null || view.getProjector() == null) return; // no active dataset + if (view == null || view.getProjector() == null) return; // no active + // dataset view.getProjector().map(); displayViewer.getCanvas().update(); } @@ -251,8 +253,8 @@ private void createSliders() { label.setHorizontalAlignment(SwingConstants.RIGHT); axisLabels.put(axis, label); - final JScrollBar slider = - new JScrollBar(Adjustable.HORIZONTAL, value, 1, min, max); + final JScrollBar slider = new JScrollBar(Adjustable.HORIZONTAL, value, + 1, min, max); slider.addAdjustmentListener(new AdjustmentListener() { @Override @@ -304,7 +306,7 @@ private void doInitialSizing() { // calling display.update() by testing such. We need to make the display // update mechanism smarter if possible. Perhaps by giving it hints about // the changes being made. - + private void updateAxis(final AxisType axis) { final int value = (int) display.getLongPosition(axis); if (axis == Axes.CHANNEL) updateColorBar(value); @@ -329,8 +331,8 @@ private double findFullyVisibleScale() { final int extraSpace = 0; // determine largest viewable panel sizes - final int maxViewHeight = - deskBounds.height - labelHeight - sliderHeight - extraSpace; + final int maxViewHeight = deskBounds.height - labelHeight - sliderHeight - + extraSpace; final int maxViewWidth = deskBounds.width - extraSpace; // is canvas bigger than largest viewable panel? diff --git a/src/main/java/net/imagej/ui/swing/viewer/image/SwingImageDisplayViewer.java b/src/main/java/net/imagej/ui/swing/viewer/image/SwingImageDisplayViewer.java index 93927c5..aa20f3b 100644 --- a/src/main/java/net/imagej/ui/swing/viewer/image/SwingImageDisplayViewer.java +++ b/src/main/java/net/imagej/ui/swing/viewer/image/SwingImageDisplayViewer.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -31,10 +31,9 @@ import net.imagej.ui.viewer.image.ImageDisplayViewer; - /** * Interface for Swing-based image display viewers. - * + * * @author Curtis Rueden */ public interface SwingImageDisplayViewer extends ImageDisplayViewer { diff --git a/src/main/java/net/imagej/ui/swing/widget/DimSelectionWidget.java b/src/main/java/net/imagej/ui/swing/widget/DimSelectionWidget.java index 442e2d2..2a84dd9 100644 --- a/src/main/java/net/imagej/ui/swing/widget/DimSelectionWidget.java +++ b/src/main/java/net/imagej/ui/swing/widget/DimSelectionWidget.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -37,7 +37,7 @@ /** * Widget interface for dimension selectors. - * + * * @author Curtis Rueden */ public interface DimSelectionWidget extends InputWidget { diff --git a/src/main/java/net/imagej/ui/swing/widget/SwingColorTableWidget.java b/src/main/java/net/imagej/ui/swing/widget/SwingColorTableWidget.java index 1e96be4..1d36426 100644 --- a/src/main/java/net/imagej/ui/swing/widget/SwingColorTableWidget.java +++ b/src/main/java/net/imagej/ui/swing/widget/SwingColorTableWidget.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -48,7 +48,7 @@ /** * Render a {@link ColorTable} in Swing. - * + * * @author Barry DeZonia */ @Plugin(type = InputWidget.class) @@ -116,8 +116,10 @@ private void fillImage(ColorTable cTable) { private static int colorBarHeight() { try { final Insets insets = UIManager.getInsets("TextPane.margin"); - return UIManager.getFont("TextField.font").getSize() + insets.top + insets.bottom; - } catch (final Exception ignored) { + return UIManager.getFont("TextField.font").getSize() + insets.top + + insets.bottom; + } + catch (final Exception ignored) { // do nothing } return 24; diff --git a/src/main/java/net/imagej/ui/swing/widget/SwingDimSelectionWidget.java b/src/main/java/net/imagej/ui/swing/widget/SwingDimSelectionWidget.java index d0050bb..8ce18bb 100644 --- a/src/main/java/net/imagej/ui/swing/widget/SwingDimSelectionWidget.java +++ b/src/main/java/net/imagej/ui/swing/widget/SwingDimSelectionWidget.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -56,7 +56,7 @@ /** * Default Swing implementation of dimension selector widget. - * + * * @author Daniel Seebacher * @author Curtis Rueden */ @@ -117,7 +117,8 @@ public void set(final WidgetModel model) { m_minNumDims = getMinDims(); m_maxNumDims = getMaxDims(); if (m_minNumDims > m_maxNumDims) { - throw new IllegalArgumentException("Minimum can't be larger than maximum"); + throw new IllegalArgumentException( + "Minimum can't be larger than maximum"); } buildUI(); @@ -148,8 +149,8 @@ private void buildUI() { m_activeToogleButtonsQueue = new LinkedList<>(); for (final TypedAxis m_typedAxi : m_typedAxis) { - final JToggleButton button = - new DimensionSelectionToggleButton(m_typedAxi.type().getLabel()); + final JToggleButton button = new DimensionSelectionToggleButton(m_typedAxi + .type().getLabel()); button.addActionListener(e -> toogleButtonChanged(e)); @@ -158,7 +159,8 @@ private void buildUI() { } // activate m_maxNumDims number of dimensions - for (int i = 0; i < Math.min(m_dimLabelButtonList.size(), m_maxNumDims); i++) + for (int i = 0; i < Math.min(m_dimLabelButtonList.size(), + m_maxNumDims); i++) { final JToggleButton button = m_dimLabelButtonList.get(i); button.setSelected(true); @@ -187,7 +189,7 @@ private int getMaxDims() { * button must be added or removed from the activeToggleButtonsQueue. Also it * is ensured that no more than {@link #getMaxDims() getMaxDims} and no less * than {@link #getMinDims() getMinsDims} are selected. - * + * * @param e the ActionEvent of the pressed ToggleButton. */ private void toogleButtonChanged(final ActionEvent e) { @@ -220,7 +222,7 @@ private void toogleButtonChanged(final ActionEvent e) { /** * Extract the Axis from the {@link Dataset}. - * + * * @param model A {@link WidgetModel} * @return The Axis of the {@link Dataset} or null if no {@link Dataset} was * found. @@ -257,7 +259,7 @@ public void doRefresh() { /** * Better looking dimension selection button. Changes color on click. - * + * * @author Christian Dietz * @author Martin Horn * @author Michael diff --git a/src/main/java/net/imagej/ui/swing/widget/SwingHistogramWidget.java b/src/main/java/net/imagej/ui/swing/widget/SwingHistogramWidget.java index 95b0c0b..dd18370 100644 --- a/src/main/java/net/imagej/ui/swing/widget/SwingHistogramWidget.java +++ b/src/main/java/net/imagej/ui/swing/widget/SwingHistogramWidget.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -64,7 +64,7 @@ /** * Render a {@link HistogramBundle} in Swing. - * + * * @author Barry DeZonia */ @Plugin(type = InputWidget.class) @@ -124,12 +124,12 @@ private JFreeChart getChart(final String title, final HistogramBundle bund) { } final JFreeChart chart = createChart(title, series); if (bund.getMinBin() != -1) { - chart.getXYPlot().addDomainMarker( - new ValueMarker(bund.getMinBin(), Color.black, new BasicStroke(1))); + chart.getXYPlot().addDomainMarker(new ValueMarker(bund.getMinBin(), + Color.black, new BasicStroke(1))); } if (bund.getMaxBin() != -1) { - chart.getXYPlot().addDomainMarker( - new ValueMarker(bund.getMaxBin(), Color.black, new BasicStroke(1))); + chart.getXYPlot().addDomainMarker(new ValueMarker(bund.getMaxBin(), + Color.black, new BasicStroke(1))); } if (displaySlopeLine(bund)) { chart.getXYPlot().addAnnotation(slopeLine()); @@ -137,16 +137,15 @@ private JFreeChart getChart(final String title, final HistogramBundle bund) { return chart; } - private JFreeChart - createChart(final String title, final List series) + private JFreeChart createChart(final String title, + final List series) { final XYSeriesCollection data = new XYSeriesCollection(); for (XYSeries xys : series) { data.addSeries(xys); } - final JFreeChart chart = - ChartFactory.createXYBarChart(title, null, false, null, data, - PlotOrientation.VERTICAL, false, true, false); + final JFreeChart chart = ChartFactory.createXYBarChart(title, null, false, + null, data, PlotOrientation.VERTICAL, false, true, false); setTheme(chart); // chart.getXYPlot().setForegroundAlpha(0.50f); return chart; @@ -172,9 +171,8 @@ private final void setTheme(final JFreeChart chart) { } private final void setBackgroundDefault(final JFreeChart chart) { - final BasicStroke gridStroke = - new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, - 1.0f, new float[] { 2.0f, 1.0f }, 0.0f); + final BasicStroke gridStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND, + BasicStroke.JOIN_ROUND, 1.0f, new float[] { 2.0f, 1.0f }, 0.0f); final XYPlot plot = (XYPlot) chart.getPlot(); plot.setRangeGridlineStroke(gridStroke); plot.setDomainGridlineStroke(gridStroke); @@ -210,7 +208,8 @@ private XYAnnotation slopeLine() { private double x1, y1, x2, y2; @Override - public void removeChangeListener(final AnnotationChangeListener listener) + public void removeChangeListener( + final AnnotationChangeListener listener) { // ignore } @@ -286,7 +285,7 @@ private void calcLineCoords(final Rectangle2D rect) { /* * OLD code for calcing line coords from slope/intercept data. Note that * it is not stretched to the correct aspect ratio here yet. - * + * @SuppressWarnings("synthetic-access") @Override public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, diff --git a/src/test/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialogDemo.java b/src/test/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialogDemo.java index 1e30083..c0ffc9c 100644 --- a/src/test/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialogDemo.java +++ b/src/test/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialogDemo.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -26,6 +26,7 @@ * POSSIBILITY OF SUCH DAMAGE. * #L% */ + package net.imagej.ui.swing.updater; import net.imagej.updater.URLChange; @@ -37,16 +38,17 @@ public class ReviewSiteURLsDialogDemo { - public static void main(String... args) { + public static void main(String... args) { List changes = new ArrayList<>(); - changes.add(URLChange.create(createUpdateSite("a", "https://downloads.micron.ox.ac.uk"), - "https://better.a.com").get()); + changes.add(URLChange.create(createUpdateSite("a", + "https://downloads.micron.ox.ac.uk"), "https://better.a.com").get()); changes.add(URLChange.create(createUpdateSite("b", "https://b.com"), - "https://better.a.com").get()); + "https://better.a.com").get()); new ReviewSiteURLsDialog(null, changes).setVisible(true); } private static UpdateSite createUpdateSite(String b, String url) { - return new UpdateSite(b, url, "", "", "Great Update Site", "Best Maintainer in the World", 0); + return new UpdateSite(b, url, "", "", "Great Update Site", + "Best Maintainer in the World", 0); } } diff --git a/src/test/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialogTest.java b/src/test/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialogTest.java index 42fe1b8..660a5a5 100644 --- a/src/test/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialogTest.java +++ b/src/test/java/net/imagej/ui/swing/updater/ReviewSiteURLsDialogTest.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -26,6 +26,7 @@ * POSSIBILITY OF SUCH DAMAGE. * #L% */ + package net.imagej.ui.swing.updater; import static org.junit.Assert.assertEquals; @@ -68,13 +69,14 @@ public void deactivatedSitesTest() { files.addUpdateSite(siteA); // this will propose a change to the URL - Optional< URLChange > urlChange = - URLChange.create(siteA, "http://sites.imagej.net/b/"); + Optional urlChange = URLChange.create(siteA, + "http://sites.imagej.net/b/"); assertTrue(urlChange.isPresent()); assertEquals("http://sites.imagej.net/b/", urlChange.get().getNewURL()); - // the change should be accepted without showing a user interface since the site is deactivated - List< URLChange > changes = Collections.singletonList(urlChange.get()); + // the change should be accepted without showing a user interface since the + // site is deactivated + List changes = Collections.singletonList(urlChange.get()); assertFalse(ReviewSiteURLsDialog.shouldBeDisplayed(changes)); // apply the change to the URL @@ -96,18 +98,18 @@ public void cancelBtnTest() { files.addUpdateSite(siteA); // propose a change to the site URL - Optional< URLChange > change = - URLChange.create(siteA, "http://sites.imagej.net/b/"); + Optional change = URLChange.create(siteA, + "http://sites.imagej.net/b/"); - // this change should be approved by the user since the update site is active - List< URLChange > changes = Collections.singletonList(change.get()); + // this change should be approved by the user since the update site is + // active + List changes = Collections.singletonList(change.get()); assertTrue(ReviewSiteURLsDialog.shouldBeDisplayed(changes)); assumeFalse(GraphicsEnvironment.isHeadless()); // create review dialog - ReviewSiteURLsDialog - dialog = new ReviewSiteURLsDialog(null, changes); + ReviewSiteURLsDialog dialog = new ReviewSiteURLsDialog(null, changes); // trigger cancel button dialog.actionPerformed(createActionEvent(dialog.cancel)); @@ -130,15 +132,14 @@ public void submitBtnTest() { files.addUpdateSite(siteA); // propose a change to the site URL - Optional< URLChange > urlChange = - URLChange.create(siteA, "http://sites.imagej.net/b/"); - List< URLChange > urlChanges = Collections.singletonList(urlChange.get()); + Optional urlChange = URLChange.create(siteA, + "http://sites.imagej.net/b/"); + List urlChanges = Collections.singletonList(urlChange.get()); assumeFalse(GraphicsEnvironment.isHeadless()); // create review dialog - ReviewSiteURLsDialog - dialog = new ReviewSiteURLsDialog(null, urlChanges); + ReviewSiteURLsDialog dialog = new ReviewSiteURLsDialog(null, urlChanges); // trigger submit button dialog.actionPerformed(createActionEvent(dialog.submit)); @@ -163,9 +164,10 @@ public void keepAllTest() { // add automated change to the URL URLChange change = URLChange.create(siteA, "http://newdomain.net/a/").get(); - List< URLChange > changes = Collections.singletonList(change); + List changes = Collections.singletonList(change); - // since the update site is active, the change needs to be approved, therefore the dialog should be displayed + // since the update site is active, the change needs to be approved, + // therefore the dialog should be displayed assertTrue(change.isRecommended()); assertTrue(ReviewSiteURLsDialog.shouldBeDisplayed(changes)); @@ -207,7 +209,7 @@ public void rememberKeptChoicesTest() { // add automated change to the URL URLChange change = URLChange.create(siteA, "http://newdomain.net/a/").get(); - List< URLChange > changes = Collections.singletonList(change); + List changes = Collections.singletonList(change); assumeFalse(GraphicsEnvironment.isHeadless()); @@ -224,18 +226,20 @@ public void rememberKeptChoicesTest() { dialog.actionPerformed(createActionEvent(dialog.submit)); // apply changes - AvailableSites.applySitesURLUpdates(files,changes); + AvailableSites.applySitesURLUpdates(files, changes); // test whether the old update site URL is still in use assertEquals("http://sites.imagej.net/a/", siteA.getURL()); assertTrue(siteA.shouldKeepURL()); // again add automated change to URL - URLChange change2 = URLChange.create(siteA, "http://newdomain.net/a/").get(); + URLChange change2 = URLChange.create(siteA, "http://newdomain.net/a/") + .get(); // test whether the choice of keeping the old URL is remembered assertFalse(change2.isRecommended()); assertFalse(change2.isApproved()); - assertFalse(ReviewSiteURLsDialog.shouldBeDisplayed(Collections.singletonList(change2))); + assertFalse(ReviewSiteURLsDialog.shouldBeDisplayed(Collections + .singletonList(change2))); } @Test @@ -250,21 +254,26 @@ public void httpsUpgradeTest() { // add an official update site UpdateSite siteA = createOfficialSite("a", "http://sites.imagej.net/a/"); - URLChange changeInactiveSite = - URLChange.create(siteA, "https://sites.imagej.net/a/").get(); + URLChange changeInactiveSite = URLChange.create(siteA, + "https://sites.imagej.net/a/").get(); - // the change should be accepted without showing a user interface since the site is deactivated - assertFalse(ReviewSiteURLsDialog.shouldBeDisplayed(Collections.singletonList(changeInactiveSite))); + // the change should be accepted without showing a user interface since the + // site is deactivated + assertFalse(ReviewSiteURLsDialog.shouldBeDisplayed(Collections + .singletonList(changeInactiveSite))); // add another official update site, activate it UpdateSite siteB = createOfficialSite("b", "http://sites.imagej.net/b/"); siteB.setActive(true); - URLChange changeActiveSite = - URLChange.create(siteB, "https://sites.imagej.net/b/").get(); + URLChange changeActiveSite = URLChange.create(siteB, + "https://sites.imagej.net/b/").get(); - // the change should be accepted after showing a user interface since one site is activated - List changes = Arrays.asList(changeActiveSite, changeInactiveSite); - assertTrue(ReviewSiteURLsDialog.shouldBeDisplayed(Collections.singletonList(changeActiveSite))); + // the change should be accepted after showing a user interface since one + // site is activated + List changes = Arrays.asList(changeActiveSite, + changeInactiveSite); + assertTrue(ReviewSiteURLsDialog.shouldBeDisplayed(Collections.singletonList( + changeActiveSite))); assumeFalse(GraphicsEnvironment.isHeadless()); @@ -300,11 +309,12 @@ public void httpDowngradeTest() { List urlChanges = new ArrayList<>(); // check if update site URL has to be changed - Optional< URLChange > changeA = URLChange.create(siteA, - HTTPSUtil.fixImageJUserSiteProtocol(siteA.getURL())); - changeA.ifPresent( urlChanges::add ); + Optional changeA = URLChange.create(siteA, HTTPSUtil + .fixImageJUserSiteProtocol(siteA.getURL())); + changeA.ifPresent(urlChanges::add); - // the change should be accepted without showing a user interface since the site is deactivated + // the change should be accepted without showing a user interface since the + // site is deactivated assertFalse(ReviewSiteURLsDialog.shouldBeDisplayed(urlChanges)); // add another official update site, activate it @@ -313,11 +323,12 @@ public void httpDowngradeTest() { files.addUpdateSite(siteB); // check if update site URL has to be changed - Optional< URLChange > changeB = URLChange.create(siteB, - HTTPSUtil.fixImageJUserSiteProtocol(siteB.getURL())); - changeB.ifPresent( urlChanges::add ); + Optional changeB = URLChange.create(siteB, HTTPSUtil + .fixImageJUserSiteProtocol(siteB.getURL())); + changeB.ifPresent(urlChanges::add); - // the change should be accepted after showing a user interface since one site is activated + // the change should be accepted after showing a user interface since one + // site is activated assertTrue(ReviewSiteURLsDialog.shouldBeDisplayed(urlChanges)); assumeFalse(GraphicsEnvironment.isHeadless()); diff --git a/src/test/java/net/imagej/ui/swing/updater/UpdaterGUITest.java b/src/test/java/net/imagej/ui/swing/updater/UpdaterGUITest.java index 3e79096..88259bd 100644 --- a/src/test/java/net/imagej/ui/swing/updater/UpdaterGUITest.java +++ b/src/test/java/net/imagej/ui/swing/updater/UpdaterGUITest.java @@ -2,17 +2,17 @@ * #%L * ImageJ software for multidimensional image processing and analysis. * %% - * Copyright (C) 2009 - 2023 ImageJ developers. + * Copyright (C) 2009 - 2024 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -55,20 +55,19 @@ /** * This class is meant for interactive debugging of GUI issues in the Updater. - * * Issues such as problems with the password dialog are often tested much more * efficiently when run outside of the Updater, without having to start ImageJ - * over and over again. This class helps with such issues. - * - * It is not meant to be run unattendedly, ie. with JUnit. - * + * over and over again. This class helps with such issues. It is not meant to be + * run unattendedly, ie. with JUnit. + * * @author Johannes Schindelin */ public class UpdaterGUITest { + public static void main(String[] args) throws Exception { - //testProgressDialog(); + // testProgressDialog(); testStringDialog(); - //testPassword(); + // testPassword(); testUpdateTheUpdater(); } @@ -106,7 +105,8 @@ protected static void testProgressDialog() { int millis = random.nextInt(500); if (millis > 0) try { Thread.sleep(millis); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { // we've been asked to stop progress.done(); return; @@ -118,27 +118,26 @@ protected static void testProgressDialog() { } protected static void testStringDialog() { - SwingUserInterface ui = new SwingUserInterface(UpdaterUtil.getLogService(), null); + SwingUserInterface ui = new SwingUserInterface(UpdaterUtil.getLogService(), + null); System.err.println(ui.getString("Login for blub")); } protected static void testPassword() { - SwingUserInterface ui = new SwingUserInterface(UpdaterUtil.getLogService(), null); + SwingUserInterface ui = new SwingUserInterface(UpdaterUtil.getLogService(), + null); System.err.println(ui.getPassword("Enter password")); } /** - * Test the "update-the-updater" functionality manually - * - * This method sets up a minimal ImageJ directory, an update site. - * Then it sets up a second minimal ImageJ directory, modifies the - * updater so that the first update site will want to update. - * - * To be able to verify that it actually works, we remove the pom.xml - * -- from which the Updater can infer the metadata like description, - * author, etc -- from the originally "uploaded" updater. If things - * work alright, the updater will have correct metadata from the update. - * If not, it will be blank. + * Test the "update-the-updater" functionality manually This method sets up a + * minimal ImageJ directory, an update site. Then it sets up a second minimal + * ImageJ directory, modifies the updater so that the first update site will + * want to update. To be able to verify that it actually works, we remove the + * pom.xml -- from which the Updater can infer the metadata like description, + * author, etc -- from the originally "uploaded" updater. If things work + * alright, the updater will have correct metadata from the update. If not, it + * will be blank. */ protected static void testUpdateTheUpdater() throws Exception { File ijRoot = createTempDirectory("testUpdaterIJRoot"); @@ -152,12 +151,15 @@ protected static void testUpdateTheUpdater() throws Exception { writeDbXml(ij2Root, webRoot); writeDbXml(webRoot, null); - File[] updaterJar = new File(ijRoot, "jars/").listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.startsWith("ij-updater-core"); - } - }); + File[] updaterJar = new File(ijRoot, "jars/").listFiles( + new FilenameFilter() + { + + @Override + public boolean accept(File dir, String name) { + return name.startsWith("ij-updater-core"); + } + }); assertTrue(updaterJar.length == 1); deletePomFromJarFiles(updaterJar[0]); @@ -170,9 +172,9 @@ public boolean accept(File dir, String name) { /** * Call the updater to upload all local files - * + * * @param ijRoot the ImageJ root - * @throws Exception + * @throws Exception */ private static void uploadAll(File ijRoot) throws Exception { String updateSite = FilesCollection.DEFAULT_UPDATE_SITE; @@ -184,26 +186,31 @@ private static void uploadAll(File ijRoot) throws Exception { file.stageForUpload(files, updateSite); } } - final FilesUploader uploader = new FilesUploader(null, files, updateSite, progress); + final FilesUploader uploader = new FilesUploader(null, files, updateSite, + progress); assertTrue(uploader.login()); uploader.upload(progress); - System.err.println("description in " + ijRoot + ": " + files.get("jars/ij-updater-core.jar").getDescription()); + System.err.println("description in " + ijRoot + ": " + files.get( + "jars/ij-updater-core.jar").getDescription()); files.write(); } /** * Delete any pom.xml file from a given .jar file - * + * * @param jar the jar to be modified - * @throws IOException - * @throws FileNotFoundException + * @throws IOException + * @throws FileNotFoundException */ - private static void deletePomFromJarFiles(File jar) throws FileNotFoundException, IOException { + private static void deletePomFromJarFiles(File jar) + throws FileNotFoundException, IOException + { JarInputStream in = new JarInputStream(new FileInputStream(jar)); Manifest manifest = in.getManifest(); File newJar = new File(jar.getAbsolutePath() + ".new"); - JarOutputStream out = new JarOutputStream(new FileOutputStream(newJar), manifest); + JarOutputStream out = new JarOutputStream(new FileOutputStream(newJar), + manifest); for (;;) { JarEntry entry = in.getNextJarEntry(); if (entry == null) break; @@ -217,31 +224,33 @@ private static void deletePomFromJarFiles(File jar) throws FileNotFoundException assertTrue(newJar.renameTo(jar)); } - private static void writeDbXml(File ijRoot, File webRoot) throws FileNotFoundException, IOException { - PrintStream writer = new PrintStream(new GZIPOutputStream(new FileOutputStream(new File(ijRoot, "db.xml.gz")))); + private static void writeDbXml(File ijRoot, File webRoot) + throws FileNotFoundException, IOException + { + PrintStream writer = new PrintStream(new GZIPOutputStream( + new FileOutputStream(new File(ijRoot, "db.xml.gz")))); writer.println(""); if (webRoot != null) { - writer.println("\t"); + writer.println("\t"); } writer.println(""); writer.close(); } - private static void copyClassPathComponentsTo(File destination) throws FileNotFoundException, IOException { + private static void copyClassPathComponentsTo(File destination) + throws FileNotFoundException, IOException + { if (!destination.isDirectory()) assertTrue(destination.mkdirs()); String classPath = System.getProperty("java.class.path"); for (String component : classPath.split(File.pathSeparator)) { File file = new File(component); assertTrue(file.exists()); if (file.isDirectory()) { - if (file.getName().equals("test-classes")) - continue; + if (file.getName().equals("test-classes")) continue; assertTrue(file.getName().equals("classes")); file = findSingleJarFile(file.getParentFile()); } @@ -250,11 +259,15 @@ private static void copyClassPathComponentsTo(File destination) throws FileNotFo } } - private static void copy(File from, File to) throws FileNotFoundException, IOException { + private static void copy(File from, File to) throws FileNotFoundException, + IOException + { copy(new FileInputStream(from), new FileOutputStream(to), true); } - private static void copy(InputStream in, OutputStream out, boolean closeAtEnd) throws IOException { + private static void copy(InputStream in, OutputStream out, boolean closeAtEnd) + throws IOException + { byte[] buffer = new byte[65536]; for (;;) { int count = in.read(buffer); @@ -267,6 +280,7 @@ private static void copy(InputStream in, OutputStream out, boolean closeAtEnd) t private static File findSingleJarFile(File directory) { File[] list = directory.listFiles(new FilenameFilter() { + @Override public boolean accept(File dir, String name) { return name.endsWith(".jar"); @@ -284,12 +298,14 @@ private static void assertTrue(boolean condition) { /** * Create a temporary directory - * + * * @param prefix the prefix as for {@link File#createTempFile} * @return the File object describing the directory * @throws IOException */ - protected static File createTempDirectory(final String prefix) throws IOException { + protected static File createTempDirectory(final String prefix) + throws IOException + { final File file = File.createTempFile(prefix, ""); file.delete(); file.mkdir();