Navigator.java 17.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
/*
 * ESO Archive
 *
 * $Id: Navigator.java,v 1.5 2009/03/17 22:56:43 abrighto Exp $
 *
 * who             when        what
 * --------------  ----------  ----------------------------------------
 * Allan Brighton  1999/06/02  Created
 */

package jsky.navigator;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Stack;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import jsky.catalog.Catalog;
import jsky.catalog.TableQueryResult;
import jsky.catalog.vo.VoTable;
import jsky.catalog.vo.VoCatalog;
import jsky.catalog.gui.*;
import jsky.catalog.skycat.SkycatTable;
import jsky.image.gui.MainImageDisplay;
import jsky.image.gui.PickObjectStatistics;
import jsky.util.Preferences;
import jsky.util.I18N;
import jsky.util.gui.DialogUtil;
import jsky.util.gui.ExampleFileFilter;
import jsky.util.gui.ProgressBarFilterInputStream;
import jsky.util.gui.ProgressException;
import jsky.util.gui.ProgressPanel;
import jsky.util.gui.SwingUtil;
import uk.ac.starlink.table.formats.CsvStarTable;
import uk.ac.starlink.table.StarTable;
import uk.ac.starlink.util.URLDataSource;


/**
 * Extends CatalogNavigator to include support for displaying images and plotting catalog data in
 * images.
 * Imported from Jsky Library to resolve catalogs problems. 
 * 
 * 
 */
public class Navigator extends CatalogNavigator implements CatalogNavigatorOpener {

    // Used to access internationalized strings (see i18n/gui*.proprties)
    private static final I18N _I18N = I18N.getInstance(Navigator.class);

    // Used for message logging
    private static Logger LOG = Logger.getLogger(Navigator.class.getName());

    // An optional object that can be used to create the image display frame when needed.
    private NavigatorImageDisplayManager _imageDisplayMgr;

    // Top level image frame
    private JFrame _imageDisplayControlFrame;

    // Used to display images
    private NavigatorImageDisplay _imageDisplay;

    // Supports the pick-object features
    private NavigatorPickObjectSupport _pickObjectSupport;  

    // Action to use to show the image window.
    private AbstractAction _imageDisplayAction = new AbstractAction("Image") {
        {
            putValue(SHORT_DESCRIPTION, _I18N.getString("showImageWin"));
        }
        @Override
		public void actionPerformed(ActionEvent evt) {
            showImageDisplay();
        }
    };

    /**
     * Construct a Navigator using the given CatalogTree widget (call setQueryResult to set the
     * catalog or data to display).
     *
     * @param catalogTree  a CatalogTree (normally a subclass of CatalogTree that knows about
     *                     certain types of catalogs)
     * @param plotter      the object to use to plot catalog table data (when the plot button is
     *                     pressed)
     * @param imageDisplay optional widget to use to display images (if not specified, or null, a
     *                     new window will be created)
     */
    public Navigator(CatalogTree catalogTree,
                     TablePlotter plotter, MainImageDisplay imageDisplay) {
        super(catalogTree, plotter);

        if (imageDisplay != null) {
            _imageDisplay = (NavigatorImageDisplay) imageDisplay;
            _imageDisplayControlFrame = SwingUtil.getFrame((Component) imageDisplay);
            initSymbolPlotter();
        }
    }

    /**
     * Construct a Navigator using the given CatalogTree widget (call setQueryResult to set the
     * catalog or data to display).
     *
     * @param catalogTree a CatalogTree (normally a subclass of CatalogTree that knows about certain
     *                    types of catalogs)
     * @param plotter     the object to use to plot catalog table data (when the plot button is
     *                    pressed)
     */
    public Navigator(CatalogTree catalogTree, TablePlotter plotter) {
        this(catalogTree, plotter, null);
    }


    /**
     * @param imageDisplayMgr an (optional) object that can be used to create the image display
     *                        frame when needed.
     */
    public void setImageDisplayManager(NavigatorImageDisplayManager imageDisplayMgr) {
        _imageDisplayMgr = imageDisplayMgr;
    }


    /**
     * @return the image display widget.
     */
    public MainImageDisplay getImageDisplay() {
        return _imageDisplay;
    }

    /**
     * @param imageDisplay the image display to use for plotting catalog objects.
     */
    protected void setImageDisplay(NavigatorImageDisplay imageDisplay) {
        _imageDisplay = imageDisplay;
        setImageDisplayControlFrame(imageDisplay.getParentFrame());
        notifyNewImageDisplay();
        initSymbolPlotter();
    }


    /**
     * @param imageDisplayControlFrame the frame belonging to the image display widget.
     */
    protected void setImageDisplayControlFrame(JFrame imageDisplayControlFrame) {
        _imageDisplayControlFrame = imageDisplayControlFrame;
    }

    /**
     * @param navigator the instance of the catalog navigator to use with this image display.
     */
    public void setImageDisplayNavigator(Navigator navigator) {
        _imageDisplay.setNavigator(navigator);
    }


    /**
     * @return the action to use to show the image window.
     */
    public Action getImageDisplayAction() {
        return _imageDisplayAction;
    }


    /**
     * Make a panel for querying a catalog (Redefined from the parent class to use a
     * CatalogQueryTool subclass).
     */
    @Override
	protected CatalogQueryTool makeCatalogQueryTool(Catalog catalog) {
        return new NavigatorQueryTool(catalog, this, _imageDisplay);
    }

    /**
     * Makes an ImageDisplayControlFrame
     */
    protected void makeImageDisplayControlFrame() {
        if (_imageDisplayMgr != null) {
            _imageDisplay = _imageDisplayMgr.getImageDisplay();
            _imageDisplayControlFrame = _imageDisplayMgr.getImageDisplayControlFrame();
        } else {
            _imageDisplayControlFrame = new NavigatorImageDisplayFrame();
            _imageDisplayControlFrame.setVisible(true);
            _imageDisplay = (NavigatorImageDisplay)
                    ((NavigatorImageDisplayFrame) _imageDisplayControlFrame).getImageDisplayControl().getImageDisplay();
        }

        _imageDisplay.setNavigator(this);
    }

    /**
     * Load and display the given image file. The URL is only needed for the image history, in case
     * the file is deleted.
     *
     * @param filename the image file
     * @param url      only needed for the image history
     */
    protected void loadImage(String filename, URL url) {
        showImageDisplay();
        _imageDisplay.setFilename(filename, url);
    }


    /**
     * Show the image display window.
     */
    public void showImageDisplay() {
        if (_imageDisplay == null) {
            // create the image display frame
            makeImageDisplayControlFrame();
            notifyNewImageDisplay();
            initSymbolPlotter();
        } else {
            SwingUtil.showFrame(_imageDisplayControlFrame);
        }
    }

    /**
     * Download the given image URL to a temporary file and then display the image file when done.
     * This method is called in a background thread.
     *
     * @param url         the image URL
     * @param contentType the content type of the URL connection
     * @throws java.io.IOException on error
     */
    protected void loadImage(URL url, String contentType) throws IOException {
        if (url.getProtocol().equals("file")) {
            SwingUtilities.invokeLater(new NavigatorImageLoader(url.getPath(), url));
        } else {
            String dir = Preferences.getPreferences().getCacheDir().getPath();

            // Try to determine the correct suffix for the file, for later reference
            String suffix;
            if (contentType.endsWith("hfits")) {
                suffix = ".hfits"; // H-compressed FITS
            } else if (contentType.endsWith("zfits") || contentType.equals("image/x-fits")) {
                // XX hack: caltech/oasis returns this with gzipped FITS!
                suffix = ".fits.gz"; // gzipped FITS (other contentTypes?)
            } else if (contentType.endsWith("fits")) {
                suffix = ".fits"; // plain FITS
            } else if (contentType.startsWith("image/")) {
                suffix = "." + contentType.substring(6); // jpeg, etc.
            } else {
                suffix = ".tmp";  // other image formats...
            }

            File file = File.createTempFile("jsky", suffix, new File(dir));
            ProgressPanel progressPanel = getProgressPanel();
            ProgressBarFilterInputStream in = progressPanel.getLoggedInputStream(url);
            FileOutputStream out = new FileOutputStream(file);

            // copy the data
            byte[] buffer = new byte[8 * 1024];
            while (true) {
                int bytesRead = in.read(buffer);
                if (bytesRead == -1) {
                    break;
                }
                if (progressPanel.isInterrupted()) {
                    throw new ProgressException("Interrupted");
                }
                out.write(buffer, 0, bytesRead);
            }

            in.close();
            out.flush();
            out.close();

            if (!progressPanel.isInterrupted()) {
                SwingUtilities.invokeLater(new NavigatorImageLoader(file.toString(), url));
            }
        }
    }


    /**
     * Notify any panels that need to know about the new image display window.
     */
    protected void notifyNewImageDisplay() {
        notifyNewImageDisplay(getBackStack());
        notifyNewImageDisplay(getForwStack());

        JComponent queryComponent = getQueryComponent();
        if (queryComponent instanceof NavigatorQueryTool) {
            ((NavigatorQueryTool) queryComponent).setImageDisplay(_imageDisplay);
        }
    }

    /**
     * Notify any panels in the given stack that need to know about the new image display window.
     *
     * @param stack the stack of panels
     */
    protected void notifyNewImageDisplay(Stack<CatalogHistoryItem> stack) {
        int n = stack.size();
        for (int i = 0; i < n; i++) {
            CatalogHistoryItem item = stack.get(i);
            JComponent comp = item.getQueryComponent();
            if (comp instanceof NavigatorQueryTool) {
                ((NavigatorQueryTool) comp).setImageDisplay(_imageDisplay);
            }
        }
    }


    /**
     * initialize the symbol plotter
     */
    protected void initSymbolPlotter() {
        // initialize the symbol plotter
        TablePlotter plotter = getPlotter();
        if (plotter != null) {
            plotter.setCanvasGraphics(_imageDisplay.getCanvasGraphics());
            plotter.setCoordinateConverter(_imageDisplay.getCoordinateConverter());
            _imageDisplay.getNavigatorPane().setPlotter(plotter);
        }
    }


    /**
     * Return a new JComponent displaying the contents of the given URL.
     */
    @Override
	protected JComponent makeURLComponent(URL url, String contentType, String format) throws IOException {
        String filename = url.getFile();
        String protocol = url.getProtocol();

        LOG.info("Display URL: ContentType = " + contentType
                + ", format = " + format
                + ", URL = " + url
                + ", protocol = " + protocol
                + ", filename = " + filename
        );

        if (format != null && format.startsWith("image/")) {
            // Image to display
            loadImage(url, format);
            return getResultComponent(); // keep displaying same component
        }

        if ("spectrum/votable".equalsIgnoreCase(format)
                || "spectrum/fits".equalsIgnoreCase(format)
                || "text/xml".equalsIgnoreCase(contentType)
                || filename.endsWith(".xml")
                || filename.endsWith(".vot")) {
            // VOTable XML file or FITS table
            VoTable table = VoTable.createVoTable(url, null, format);
            table.setCatalog(new VoCatalog(table));
            return makeCatalogComponent(table.getCatalog());
        }

        if ("text/csv".equalsIgnoreCase(format)) {
            // CSV formatted table
            StarTable starTable = new CsvStarTable(new URLDataSource(url));
            VoTable table = VoTable.createVoTable(starTable, null, Integer.MAX_VALUE);
            table.setCatalog(new VoCatalog(table));
            return makeCatalogComponent(table.getCatalog());
        }

        if (filename.toLowerCase().endsWith(".fits") && !"application/xml".equalsIgnoreCase(contentType)) {
            // Local FITS table file
            try {
//              NavigatorFITSTable table = NavigatorFITSTable.getFitsTable(filename);
                VoTable table = VoTable.createVoTable(url, null, format);
                table.setCatalog(new VoCatalog(table));
                return makeCatalogComponent(table.getCatalog());
            } catch (Exception e) {
                // ignore: might be an image file, which is handled below
            }
        }

        if ("file".equals(protocol)
                && (filename.endsWith(".table") || filename.endsWith(".scat") || filename.endsWith(".cat"))) {
            // skycat local catalog file?
            SkycatTable table = new SkycatTable(filename);
            return makeCatalogComponent(table.getCatalog());
        }

        // XXX some servers return text/html even for FITS images
        if (contentType.startsWith("text/")) {
            return super.makeURLComponent(url, contentType, format);
        }

        // Otherwise assume it is an image and display in the image window
        loadImage(url, contentType);
        return getResultComponent();
    }

    /**
     * Open the catalog navigator window (in this case, it is already open).
     *
     * @see CatalogNavigatorOpener
     */
    @Override
	public void openCatalogWindow() {
    }


    /**
     * Open the catalog navigator window and display the interface for the given catalog, if not
     * null (in this case, the window is already open).
     *
     * @see CatalogNavigatorOpener
     */
    @Override
	public void openCatalogWindow(Catalog cat) {
        if (cat != null) {
            setAutoQuery(false);
            setQueryResult(cat);
        }
    }

    /**
     * Open a catalog window for the named catalog, if found.
     *
     * @see CatalogNavigatorOpener
     */
    @Override
	public void openCatalogWindow(String name) {
        Catalog cat = getCatalogDirectory(false).findCatalog(name);
        if (cat != null) {
            openCatalogWindow(cat);
        }
    }


    /**
     * Pop up a file browser to select a local catalog file to open.
     *
     * @see CatalogNavigatorOpener
     */
    @Override
	public void openLocalCatalog() {
        open();
    }

    /**
     * Save the current table as a FITS table in the current FITS image.
     */
    @Override
	public void saveWithImage() {
        JComponent resultComponent = getResultComponent();
        if (!(resultComponent instanceof TableDisplayTool)) {
            DialogUtil.error("This operation is only supported for tables");
        } else if (_imageDisplay == null) {
            DialogUtil.error("No current FITS image.");
        } else {
            TableQueryResult table = ((TableDisplayTool) resultComponent).getTable();
            _imageDisplay.saveFITSTable(table);
        }
    }

    /**
     * Create and return a new file chooser to be used to select a local catalog file to open.
     */
    @Override
	public JFileChooser makeFileChooser() {
        JFileChooser fileChooser = new JFileChooser(new File("."));

        ExampleFileFilter xmlFilter = new ExampleFileFilter(new String[]{
                "xml", "vot"}, "VOTable XML File");
        fileChooser.addChoosableFileFilter(xmlFilter);

        ExampleFileFilter fitsFilter = new ExampleFileFilter(new String[]{
                "fit", "fits", "fts"}, "FITS File (with Table Extensions)");
        fileChooser.addChoosableFileFilter(fitsFilter);

        ExampleFileFilter skycatLocalCatalogFilter = new ExampleFileFilter(new String[]{
                "table", "scat", "cat"}, "Skycat Local Catalog File");
        fileChooser.addChoosableFileFilter(skycatLocalCatalogFilter);

        fileChooser.setFileFilter(xmlFilter);

        return fileChooser;
    }


    /**
     * This local class is used to load an image in the event dispatching thread. Doing it in the
     * calling thread could cause the window to hang, since it needs to create and show a top level
     * window and the calling thread (from CatalogNavigator) is already a background thread. The url
     * is only needed for the image history, in case the file is deleted.
     */
    protected class NavigatorImageLoader implements Runnable {

        String filename;
        URL url;

        public NavigatorImageLoader(String filename, URL url) {
            this.filename = filename;
            this.url = url;
        }

        @Override
		public void run() {
            loadImage(filename, url);
            showImageDisplay();
        }
    }

    /**
     * Add the object described by stats to the currently displayed table, or create a new table if
     * none is being displayed.
     *
     * @param stats    describes the selected object
     * @param isUpdate set to true if this is just an update of the previously selected position
     */
    public void addPickedObjectToTable(PickObjectStatistics stats, boolean isUpdate) {
        if (_pickObjectSupport == null) {
            _pickObjectSupport = new NavigatorPickObjectSupport(this);
        }
        _pickObjectSupport.addToTable(stats, isUpdate);
    }
}