001/*****************************************************************************
002 * Copyright by The HDF Group.                                               *
003 * Copyright by the Board of Trustees of the University of Illinois.         *
004 * All rights reserved.                                                      *
005 *                                                                           *
006 * This file is part of the HDF Java Products distribution.                  *
007 * The full copyright notice, including terms governing use, modification,   *
008 * and redistribution, is contained in the COPYING file, which can be found  *
009 * at the root of the source code distribution tree,                         *
010 * or in https://www.hdfgroup.org/licenses.                                  *
011 * If you do not have access to either file, you may request a copy from     *
012 * help@hdfgroup.org.                                                        *
013 ****************************************************************************/
014
015package hdf.view.dialog;
016
017import java.io.File;
018import java.util.Iterator;
019import java.util.List;
020
021import org.eclipse.swt.SWT;
022import org.eclipse.swt.events.DisposeEvent;
023import org.eclipse.swt.events.DisposeListener;
024import org.eclipse.swt.events.SelectionAdapter;
025import org.eclipse.swt.events.SelectionEvent;
026import org.eclipse.swt.graphics.Font;
027import org.eclipse.swt.graphics.Point;
028import org.eclipse.swt.graphics.Rectangle;
029import org.eclipse.swt.layout.GridData;
030import org.eclipse.swt.layout.GridLayout;
031import org.eclipse.swt.widgets.Button;
032import org.eclipse.swt.widgets.Composite;
033import org.eclipse.swt.widgets.Dialog;
034import org.eclipse.swt.widgets.Display;
035import org.eclipse.swt.widgets.FileDialog;
036import org.eclipse.swt.widgets.Label;
037import org.eclipse.swt.widgets.Shell;
038import org.eclipse.swt.widgets.Text;
039
040import hdf.object.FileFormat;
041import hdf.view.DefaultFileFilter;
042import hdf.view.Tools;
043import hdf.view.ViewProperties;
044
045/**
046 * ImageConversionDialog shows a message dialog requesting user input for
047 * converting files.
048 *
049 * @author Jordan T. Henderson
050 * @version 2.4 1/28/2016
051 */
052public class ImageConversionDialog extends Dialog {
053    private Shell              shell;
054
055    private Font               curFont;
056
057    private String             fileTypeFrom, fileTypeTo;
058
059    private Text               srcFileField, dstFileField;
060
061    private boolean            isConverted;
062
063    private boolean            isConvertedFromImage;
064
065    private String             convertedFile;
066
067    private String             toFileExtension;
068
069    private List<FileFormat>   fileList;
070
071    private String             currentDir;
072
073    /**
074     * Constructs a FileConversionDialog
075     *
076     * @param parent
077     *            The parent shell of the dialog.
078     * @param typeFrom
079     *            source file type
080     * @param typeTo
081     *            destination file type
082     * @param dir
083     *            current file directory
084     * @param openFiles
085     *            The list of currently open files
086     */
087    public ImageConversionDialog(Shell parent, String typeFrom, String typeTo,
088            String dir, List<FileFormat> openFiles) {
089        super(parent, SWT.APPLICATION_MODAL);
090
091        try {
092            curFont = new Font(
093                    Display.getCurrent(),
094                    ViewProperties.getFontType(),
095                    ViewProperties.getFontSize(),
096                    SWT.NORMAL);
097        }
098        catch (Exception ex) {
099            curFont = null;
100        }
101
102        fileTypeFrom = typeFrom;
103        fileTypeTo = typeTo;
104        isConverted = false;
105        isConvertedFromImage = false;
106        fileList = openFiles;
107        toFileExtension = "";
108        currentDir = dir;
109    }
110
111    /**
112     * Open the ImageConversionDialog for converting images.
113     */
114    public void open() {
115        Shell parent = getParent();
116        shell = new Shell(parent, SWT.SHELL_TRIM | SWT.APPLICATION_MODAL);
117        shell.setFont(curFont);
118        shell.setText(parent.getText());
119        shell.setImages(ViewProperties.getHdfIcons());
120        shell.setLayout(new GridLayout(1, true));
121
122        if (fileTypeTo.equals(FileFormat.FILE_TYPE_HDF5)) {
123            toFileExtension = ".h5";
124            shell.setText("Convert Image to HDF5 ...");
125            isConvertedFromImage = true;
126        }
127        else if (fileTypeTo.equals(FileFormat.FILE_TYPE_HDF4)) {
128            toFileExtension = ".hdf";
129            shell.setText("Convert Image to HDF4 ...");
130            isConvertedFromImage = true;
131        }
132
133
134        // Create content region
135        Composite contentComposite = new Composite(shell, SWT.NONE);
136        contentComposite.setLayout(new GridLayout(3, false));
137        contentComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
138
139        Label label = new Label(contentComposite, SWT.RIGHT);
140        label.setFont(curFont);
141        label.setText("IMAGE File: ");
142
143        srcFileField = new Text(contentComposite, SWT.SINGLE | SWT.BORDER);
144        srcFileField.setFont(curFont);
145        GridData fieldData = new GridData(SWT.FILL, SWT.FILL, true, false);
146        fieldData.minimumWidth = 350;
147        srcFileField.setLayoutData(fieldData);
148
149        Button browseButton = new Button(contentComposite, SWT.PUSH);
150        browseButton.setFont(curFont);
151        browseButton.setText("Browse...");
152        browseButton.addSelectionListener(new SelectionAdapter() {
153            public void widgetSelected(SelectionEvent e) {
154                FileDialog fChooser = new FileDialog(shell, SWT.OPEN);
155                fChooser.setFilterPath(currentDir);
156
157                if(isConvertedFromImage) {
158                    DefaultFileFilter filter = DefaultFileFilter.getImageFileFilter();
159                    fChooser.setFilterExtensions(new String[] {"*", filter.getExtensions()});
160                    fChooser.setFilterNames(new String[] {"All Files", filter.getDescription()});
161                    fChooser.setFilterIndex(1);
162                } else {
163                    fChooser.setFilterExtensions(new String[] {"*"});
164                    fChooser.setFilterNames(new String[] {"All Files"});
165                    fChooser.setFilterIndex(0);
166                }
167
168                String filename = fChooser.open();
169
170                if(filename == null) {
171                    return;
172                }
173
174                File chosenFile = new File(filename);
175
176                currentDir = chosenFile.getParent();
177                srcFileField.setText(chosenFile.getAbsolutePath());
178                dstFileField.setText(chosenFile.getAbsolutePath() + toFileExtension);
179            }
180        });
181
182        label = new Label(contentComposite, SWT.RIGHT);
183        label.setFont(curFont);
184        label.setText("HDF File: ");
185
186        dstFileField = new Text(contentComposite, SWT.SINGLE | SWT.BORDER);
187        dstFileField.setFont(curFont);
188        dstFileField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
189
190        browseButton = new Button(contentComposite, SWT.PUSH);
191        browseButton.setFont(curFont);
192        browseButton.setText("Browse...");
193        browseButton.addSelectionListener(new SelectionAdapter() {
194            public void widgetSelected(SelectionEvent e) {
195                FileDialog fChooser = new FileDialog(shell, SWT.OPEN);
196
197                fChooser.setFilterExtensions(new String[] {"*"});
198                fChooser.setFilterNames(new String[] {"All Files"});
199                fChooser.setFilterIndex(0);
200
201                String filename = fChooser.open();
202
203                if(filename == null) {
204                    return;
205                }
206
207                dstFileField.setText(filename);
208            }
209        });
210
211        // Dummy label to fill space as dialog is resized
212        new Label(shell, SWT.NONE).setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
213
214
215        // Create Ok/Cancel button
216        Composite buttonComposite = new Composite(shell, SWT.NONE);
217        buttonComposite.setLayout(new GridLayout(2, true));
218        buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
219
220        Button okButton = new Button(buttonComposite, SWT.PUSH);
221        okButton.setFont(curFont);
222        okButton.setText("   &OK   ");
223        okButton.setLayoutData(new GridData(SWT.END, SWT.FILL, true, false));
224        okButton.addSelectionListener(new SelectionAdapter() {
225            public void widgetSelected(SelectionEvent e) {
226                isConverted = convert();
227
228                if (isConverted) {
229                    shell.dispose();
230                }
231            }
232        });
233
234        Button cancelButton = new Button(buttonComposite, SWT.PUSH);
235        cancelButton.setFont(curFont);
236        cancelButton.setText(" &Cancel ");
237        cancelButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.FILL, true, false));
238        cancelButton.addSelectionListener(new SelectionAdapter() {
239            public void widgetSelected(SelectionEvent e) {
240                isConverted = false;
241                convertedFile = null;
242                shell.dispose();
243            }
244        });
245
246
247        shell.pack();
248
249        shell.addDisposeListener(new DisposeListener() {
250            public void widgetDisposed(DisposeEvent e) {
251                if (curFont != null) curFont.dispose();
252            }
253        });
254
255        shell.setMinimumSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT));
256
257        Rectangle parentBounds = parent.getBounds();
258        Point shellSize = shell.getSize();
259        shell.setLocation((parentBounds.x + (parentBounds.width / 2)) - (shellSize.x / 2),
260                          (parentBounds.y + (parentBounds.height / 2)) - (shellSize.y / 2));
261
262        shell.open();
263
264        Display display = parent.getDisplay();
265        while(!shell.isDisposed()) {
266            if (!display.readAndDispatch())
267                display.sleep();
268        }
269    }
270
271    /** Convert file */
272    private boolean convert() {
273        boolean converted = false;
274        String srcFile = srcFileField.getText();
275        String dstFile = dstFileField.getText();
276
277        if ((srcFile == null) || (dstFile == null)) {
278            return false;
279        }
280
281        srcFile = srcFile.trim();
282        dstFile = dstFile.trim();
283        if ((srcFile == null) || (srcFile.length() <= 0) || (dstFile == null)
284                || (dstFile.length() <= 0)) {
285            return false;
286        }
287
288        // verify the source file
289        File f = new File(srcFile);
290        if (!f.exists()) {
291            shell.getDisplay().beep();
292            Tools.showError(shell, "Convert", "Source file does not exist.");
293            return false;
294        }
295        else if (f.isDirectory()) {
296            shell.getDisplay().beep();
297            Tools.showError(shell, "Convert", "Source file is a directory.");
298            return false;
299        }
300
301        // verify target file
302        String srcPath = f.getParent();
303        f = new File(dstFile);
304        File pfile = f.getParentFile();
305        if (pfile == null) {
306            dstFile = srcPath + File.separator + dstFile;
307            f = new File(dstFile);
308        }
309        else if (!pfile.exists()) {
310            shell.getDisplay().beep();
311            Tools.showError(shell, "Convert", "Destination file path does not exist at\n"
312                    + pfile.getPath());
313            return false;
314        }
315
316        // check if the file is in use
317        if (fileList != null) {
318            FileFormat theFile = null;
319            Iterator<FileFormat> iterator = fileList.iterator();
320            while (iterator.hasNext()) {
321                theFile = (FileFormat) iterator.next();
322                if (theFile.getFilePath().equals(dstFile)) {
323                    shell.getDisplay().beep();
324                    Tools.showError(shell, "Convert", "The destination file is being used.");
325                    return false;
326                }
327            }
328        }
329
330        if (f.exists()) {
331            if(!Tools.showConfirm(shell, "Convert", "Destination file exists. Do you want to replace it ?"))
332                return false;
333        }
334
335        try {
336            Tools.convertImageToHDF(srcFile, dstFile, fileTypeFrom, fileTypeTo);
337            convertedFile = dstFile;
338            converted = true;
339        }
340        catch (Exception ex) {
341            convertedFile = null;
342            converted = false;
343            shell.getDisplay().beep();
344            Tools.showError(shell, "Convert", ex.getMessage());
345            return false;
346        }
347
348        return converted;
349    }
350
351    /**
352     * if an image file has been converted.
353     *
354     * @return the state of conversion
355     */
356    public boolean isFileConverted() {
357        return isConverted;
358    }
359
360    /**
361     * get the file of an image file that has been converted.
362     *
363     * @return the name of the converted file
364     */
365    public String getConvertedFile() {
366        return convertedFile;
367    }
368}