001/*
002 * $Id: ArgumentManager.java,v 1.21 2011/03/29 21:44:38 jbeavers Exp $
003 *
004 * This file is part of McIDAS-V
005 *
006 * Copyright 2007-2011
007 * Space Science and Engineering Center (SSEC)
008 * University of Wisconsin - Madison
009 * 1225 W. Dayton Street, Madison, WI 53706, USA
010 * https://www.ssec.wisc.edu/mcidas
011 * 
012 * All Rights Reserved
013 * 
014 * McIDAS-V is built on Unidata's IDV and SSEC's VisAD libraries, and
015 * some McIDAS-V source code is based on IDV and VisAD source code.  
016 * 
017 * McIDAS-V is free software; you can redistribute it and/or modify
018 * it under the terms of the GNU Lesser Public License as published by
019 * the Free Software Foundation; either version 3 of the License, or
020 * (at your option) any later version.
021 * 
022 * McIDAS-V is distributed in the hope that it will be useful,
023 * but WITHOUT ANY WARRANTY; without even the implied warranty of
024 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
025 * GNU Lesser Public License for more details.
026 * 
027 * You should have received a copy of the GNU Lesser Public License
028 * along with this program.  If not, see http://www.gnu.org/licenses.
029 */
030
031package edu.wisc.ssec.mcidasv;
032
033import java.util.ArrayList;
034import java.util.Collections;
035import java.util.List;
036
037import edu.wisc.ssec.mcidasv.startupmanager.StartupManager;
038
039import ucar.unidata.idv.ArgsManager;
040import ucar.unidata.idv.IntegratedDataViewer;
041import ucar.unidata.util.IOUtil;
042import ucar.unidata.util.LogUtil;
043import ucar.unidata.util.PatternFileFilter;
044
045/**
046 * McIDAS-V needs to handle a few command line flags/options that the IDV does
047 * not. Only the ability to force the Aqua look and feel currently exists.
048 * 
049 * @author McIDAS-V Developers
050 */
051public class ArgumentManager extends ArgsManager {
052
053    /** usage message */
054    public static final String USAGE_MESSAGE =
055        "Usage: runMcV [OPTIONS] <bundle/script files, e.g., .mcv, .mcvz, .py>";
056
057    /**
058     *  Given by the "-user" argument. Alternative user path for bundles,  resources, etc.
059     */
060    String defaultUserDirectory = StartupManager.INSTANCE.getPlatform().getUserDirectory();
061
062    /**
063     * Just bubblin' on up the inheritance hierarchy.
064     * 
065     * @param idv The IDV instance.
066     * @param args The command line arguments that were given.
067     */
068    public ArgumentManager(IntegratedDataViewer idv, String[] args) {
069        super(idv, args);
070    }
071
072    /**
073     * Currently we're only handling the {@code -forceaqua} flag so we can
074     * mitigate some overlay issues we've been seeing on OS X Leopard.
075     * 
076     * @param arg The current argument we're examining.
077     * @param args The actual array of arguments.
078     * @param idx The index of {@code arg} within {@code args}.
079     * 
080     * @return The idx of the last value in the args array we look at. i.e., 
081     * if the flag arg does not require any further values in the args array 
082     * then don't increment idx.  If arg requires one more value then 
083     * increment idx by one. etc.
084     * 
085     * @throws Exception Throw bad things off to something that can handle 'em!
086     */
087    protected int parseArg(String arg, String[] args, int idx) 
088        throws Exception {
089
090        if ("-forceaqua".equals(arg)) {
091            // unfortunately we can't simply set the look and feel here. If I
092            // were to do so, the loadLookAndFeel in the IdvUIManager would 
093            // eventually get loaded and then set the look and feel to whatever
094            // the preferences dictate.
095            // instead I use the boolean toggle to signal to McV's 
096            // UIManager.loadLookAndFeel that it should simply ignore the user's
097            // preference is and load the Aqua L&F from there.
098            McIDASV.useAquaLookAndFeel = true;
099        } else if (ARG_HELP.equals(arg)) {
100            System.err.println(USAGE_MESSAGE);
101            System.err.println(getUsageMessage());
102            ((McIDASV)getIdv()).exit(1);
103        } else if (checkArg(arg, "-pyfile", args, idx, 1)) {
104            scriptingFiles.add(args[idx++]);
105            if (!getIslInteractive()) {
106                setIsOffScreen(true);
107            }
108        } else {
109            if (ARG_ISLINTERACTIVE.equals(arg) || ARG_B64ISL.equals(arg) || ARG_ISLFILE.equals(arg) || isIslFile(arg)) {
110                System.err.println("*** WARNING: ISL is being deprecated!");
111            }
112            return super.parseArg(arg, args, idx);
113        }
114        return idx;
115    }
116
117    /**
118     * Print out the command line usage message and exit
119     * 
120     * @param err The usage message
121     */
122    @Override public void usage(String err) {
123        String msg = USAGE_MESSAGE;
124        msg = msg + '\n' + getUsageMessage();
125        LogUtil.userErrorMessage(err + '\n' + msg);
126        ((McIDASV)getIdv()).exit(1);
127    }
128
129    /**
130     * Append some McIDAS-V specific command line options to the default IDV
131     * usage message.
132     *
133     * @return Usage message.
134     */
135    protected String getUsageMessage() {
136        return msg(ARG_HELP, "(this message)")
137            + msg("-forceaqua", "Forces the Aqua look and feel on OS X")
138            + msg(ARG_PROPERTIES, "<property file>")
139            + msg("-Dpropertyname=value", "(Define the property value)")
140            + msg(ARG_INSTALLPLUGIN, "<plugin jar file or url to install>")
141            + msg(ARG_PLUGIN, "<plugin jar file, directory, url for this run>")
142            + msg(ARG_NOPLUGINS, "Don't load plugins")
143            + msg(ARG_CLEARDEFAULT, "(Clear the default bundle)")
144            + msg(ARG_NODEFAULT, "(Don't read in the default bundle file)")
145            + msg(ARG_DEFAULT, "<.mcv/.mcvz file>")
146            + msg(ARG_BUNDLE, "<bundle file or url>")
147            + msg(ARG_B64BUNDLE, "<base 64 encoded inline bundle>")
148            + msg(ARG_SETFILES, "<datasource pattern> <semi-colon delimited list of files> (Use the list of files for the bundled datasource)")
149            + msg(ARG_ONEINSTANCEPORT, "<port number> (Check if another version of McIDAS-V is running. If so pass command line arguments to it and shutdown)")
150            + msg(ARG_NOONEINSTANCE, "(Don't do the one instance port)")
151            + msg(ARG_NOPREF, "(Don't read in the user preferences)")
152            + msg(ARG_USERPATH, "<user directory to use>")
153            + msg(ARG_SITEPATH, "<url path to find site resources>")
154            + msg(ARG_NOGUI, "(Don't show the main window gui)")
155            + msg(ARG_DATA, "<data source> (Load the data source)")
156            + msg(ARG_DISPLAY, "<parameter> <display>")
157//            + msg("<scriptfile.isl>", "(Run the IDV script in batch mode)")
158            + msg("-pyfile", "<jython script file to evaluate>")
159//            + msg(ARG_B64ISL, "<base64 encoded inline isl> This will run the isl in interactive mode")
160//            + msg(ARG_ISLINTERACTIVE, "run any isl files in interactive mode")
161            + msg(ARG_IMAGE, "<image file name> (create a jpeg image and then exit)")
162            + msg(ARG_MOVIE, "<movie file name> (create a quicktime movie and then exit)")
163            + msg(ARG_IMAGESERVER, "<port number or .properties file> (run McIDAS-V in image generation server mode. Support http requests on the given port)")
164            + msg(ARG_CATALOG, "<url to a chooser catalog>")
165            + msg(ARG_CONNECT, "<collaboration hostname to connect to>")
166            + msg(ARG_SERVER, "(Should McIDAS-V run in collaboration server mode)")
167            + msg(ARG_PORT, "<Port number collaboration server should listen on>")
168            + msg(ARG_CHOOSER, "(show the data chooser on start up) ")
169            + msg(ARG_PRINTJNLP, "(Print out any embedded bundles from jnlp files)")
170            + msg(ARG_CURRENTTIME, "<dttm> (Override current time for background processing)")
171//            + msg(ARG_CURRENTTIME, "<dttm> (Override current time for ISL processing)")
172            + msg(ARG_LISTRESOURCES, "<list out the resource types")
173            + msg(ARG_DEBUG, "(Turn on debug print)")
174            + msg(ARG_MSG_DEBUG, "(Turn on language pack debug)")
175            + msg(ARG_MSG_RECORD, "<Language pack file to write missing entries to>")
176            + msg(ARG_TRACE, "(Print out trace messages)")
177            + msg(ARG_NOERRORSINGUI, "(Don't show errors in gui)")
178            + msg(ARG_TRACEONLY, "<trace pattern> (Print out trace messages that match the pattern)");
179    }
180
181    /**
182     * @see ArgsManager#getBundleFileFilters()
183     */
184    @Override public List<PatternFileFilter> getBundleFileFilters() {
185        List<PatternFileFilter> filters = new ArrayList<PatternFileFilter>(); 
186        Collections.addAll(filters, getXidvFileFilter(), getZidvFileFilter(), FILTER_JNLP, FILTER_ISL, super.getXidvFileFilter(), super.getZidvFileFilter());
187        return filters;
188    }
189
190    /**
191     * Returns a list of {@link PatternFileFilter}s that can be used to determine
192     * if a file is a bundle. 
193     * 
194     * <p>If {@code fromOpen} is {@code true}, the 
195     * returned list will contain {@code PatternFileFilter}s for bundles as 
196     * well as JNLP and ISL files. If {@code false}, the returned list will
197     * only contain filters for XML and zipped bundles.
198     * 
199     * @param fromOpen Whether or not this has been called from an 
200     * {@literal "open file"} dialog. 
201     * 
202     * @return Filters for bundles.
203     */
204    public List<PatternFileFilter> getBundleFilters(final boolean fromOpen) {
205        List<PatternFileFilter> filters = new ArrayList<PatternFileFilter>();
206
207        if (fromOpen)
208            Collections.addAll(filters, getXidvZidvFileFilter(), FILTER_JNLP, FILTER_ISL, super.getXidvZidvFileFilter());
209        else
210            filters.addAll(getBundleFileFilters());
211
212        return filters;
213    }
214
215    /**
216     * @see ArgsManager#getXidvFileFilter()
217     */
218    @Override public PatternFileFilter getXidvFileFilter() {
219        return Constants.FILTER_MCV;
220    }
221
222    /**
223     * @see ArgsManager#getZidvFileFilter()
224     */
225    @Override public PatternFileFilter getZidvFileFilter() {
226        return Constants.FILTER_MCVZ;
227    }
228
229    /**
230     * @see ArgsManager#getXidvZidvFileFilter()
231     */
232    @Override public PatternFileFilter getXidvZidvFileFilter() {
233        return Constants.FILTER_MCVMCVZ;
234    }
235
236    /*
237     * There's some internal IDV file opening code that relies on this method.
238     * We've gotta override if we want to use .zidv bundles.
239     */
240    @Override public boolean isZidvFile(final String name) {
241        return isZippedBundle(name);
242    }
243
244    /* same story as isZidvFile! */
245    @Override public boolean isXidvFile(final String name) {
246        return isXmlBundle(name);
247    }
248
249    /**
250     * Tests to see if <code>name</code> has a known XML bundle extension.
251     * 
252     * @param name Name of the bundle.
253     * 
254     * @return Whether or not <code>name</code> has an XML bundle suffix.
255     */
256    public static boolean isXmlBundle(final String name) {
257        return IOUtil.hasSuffix(name, Constants.FILTER_MCV.getPreferredSuffix())
258            || IOUtil.hasSuffix(name, Constants.FILTER_XIDV.getPreferredSuffix());
259    }
260
261    /**
262     * Tests to see if <code>name</code> has a known zipped bundle extension.
263     * 
264     * @param name Name of the bundle.
265     * 
266     * @return Whether or not <code>name</code> has zipped bundle suffix.
267     */
268    public static boolean isZippedBundle(final String name) {
269        return IOUtil.hasSuffix(name, Constants.FILTER_MCVZ.getPreferredSuffix())
270               || IOUtil.hasSuffix(name, Constants.FILTER_ZIDV.getPreferredSuffix());
271    }
272
273    /**
274     * Tests <code>name</code> to see if it has a known bundle extension.
275     * 
276     * @param name Name of the bundle.
277     * 
278     * @return Whether or not <code>name</code> has a bundle suffix.
279     */
280    public static boolean isBundle(final String name) {
281        return (isXmlBundle(name) || isZippedBundle(name));
282    }
283}