2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import java.io.IOException;
25 import java.util.StringTokenizer;
26 import java.util.Vector;
28 import javax.swing.SwingUtilities;
30 import jalview.api.ComplexAlignFile;
31 import jalview.api.FeatureSettingsModelI;
32 import jalview.api.FeaturesDisplayedI;
33 import jalview.api.FeaturesSourceI;
34 import jalview.bin.Cache;
35 import jalview.bin.Jalview;
36 import jalview.datamodel.AlignmentI;
37 import jalview.datamodel.HiddenColumns;
38 import jalview.datamodel.PDBEntry;
39 import jalview.datamodel.SequenceI;
40 import jalview.gui.AlignFrame;
41 import jalview.gui.AlignViewport;
42 import jalview.gui.Desktop;
43 import jalview.gui.JvOptionPane;
44 import jalview.gui.QuitHandler;
45 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
46 import jalview.project.Jalview2XML;
47 import jalview.schemes.ColourSchemeI;
48 import jalview.structure.StructureSelectionManager;
49 import jalview.util.MessageManager;
50 import jalview.ws.utils.UrlDownloadClient;
52 public class FileLoader implements Runnable
56 DataSourceType protocol;
60 AlignmentFileReaderI source = null; // alternative specification of where data
65 AlignViewport viewport;
67 AlignFrame alignFrame;
73 boolean raiseGUI = true;
75 private File selectedFile;
77 private static boolean useDefaultFileFormat = false;
80 * default constructor always raised errors in GUI dialog boxes
88 * construct a Fileloader that may raise errors non-interactively
91 * true if errors are to be raised as GUI dialog boxes
93 public FileLoader(boolean raiseGUI)
95 this.raiseGUI = raiseGUI;
98 public void LoadFile(AlignViewport viewport, Object file,
99 DataSourceType protocol, FileFormatI format)
101 LoadFile(viewport, file, protocol, format, true);
104 public void LoadFile(AlignViewport viewport, Object file,
105 DataSourceType protocol, FileFormatI format, boolean async)
107 this.viewport = viewport;
108 if (file instanceof File)
110 this.selectedFile = (File) file;
111 file = selectedFile.getPath();
113 LoadFile(file.toString(), protocol, format, async);
116 public void LoadFile(String file, DataSourceType protocol,
119 LoadFile(file, protocol, format, true);
122 public void LoadFile(String file, DataSourceType protocol,
123 FileFormatI format, boolean async)
126 this.protocol = protocol;
127 this.format = format;
131 final Thread loader = new Thread(this);
133 SwingUtilities.invokeLater(new Runnable()
149 * Load a (file, protocol) source of unknown type
154 public void LoadFile(String file, DataSourceType protocol)
156 LoadFile(file, protocol, null);
160 * Load alignment from (file, protocol) and wait till loaded
164 * @return alignFrame constructed from file contents
166 public AlignFrame LoadFileWaitTillLoaded(String file,
167 DataSourceType sourceType)
169 return LoadFileWaitTillLoaded(file, sourceType, null);
173 * Load alignment from (file, protocol) of type format and wait till loaded
178 * @return alignFrame constructed from file contents
180 public AlignFrame LoadFileWaitTillLoaded(String file,
181 DataSourceType sourceType, FileFormatI format)
184 this.protocol = sourceType;
185 this.format = format;
186 return _LoadFileWaitTillLoaded();
190 * Load alignment from (file, protocol) of type format and wait till loaded
195 * @return alignFrame constructed from file contents
197 public AlignFrame LoadFileWaitTillLoaded(File file,
198 DataSourceType sourceType, FileFormatI format)
200 this.selectedFile = file;
201 this.file = file.getPath();
202 this.protocol = sourceType;
203 this.format = format;
204 return _LoadFileWaitTillLoaded();
208 * Load alignment from FileParse source of type format and wait till loaded
212 * @return alignFrame constructed from file contents
214 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
217 this.source = source;
219 file = source.getInFile();
220 protocol = source.getDataSourceType();
221 this.format = format;
222 return _LoadFileWaitTillLoaded();
226 * runs the 'run' method (in this thread), then return the alignFrame that's
227 * (hopefully) been read
231 protected AlignFrame _LoadFileWaitTillLoaded()
238 public void updateRecentlyOpened()
240 Vector<String> recent = new Vector<>();
241 if (protocol == DataSourceType.PASTE)
243 // do nothing if the file was pasted in as text... there is no filename to
248 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
250 // ignore files loaded from the system's temporary directory
253 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
256 String historyItems = Cache.getProperty(type);
260 if (historyItems != null)
262 st = new StringTokenizer(historyItems, "\t");
264 while (st.hasMoreTokens())
266 recent.addElement(st.nextToken().trim());
270 if (recent.contains(file))
275 StringBuffer newHistory = new StringBuffer(file);
276 for (int i = 0; i < recent.size() && i < 10; i++)
278 newHistory.append("\t");
279 newHistory.append(recent.elementAt(i));
282 Cache.setProperty(type, newHistory.toString());
284 if (protocol == DataSourceType.FILE)
286 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
293 String title = protocol == DataSourceType.PASTE
294 ? "Copied From Clipboard"
296 Runtime rt = Runtime.getRuntime();
300 if (Desktop.instance != null)
302 Desktop.instance.startLoading(file);
306 // just in case the caller didn't identify the file for us
309 format = new IdentifyFile().identify(source, false);
310 // identify stream and rewind rather than close
312 else if (selectedFile != null)
314 format = new IdentifyFile().identify(selectedFile, protocol);
318 format = new IdentifyFile().identify(file, protocol);
325 Desktop.instance.stopLoading();
326 jalview.bin.Console.errPrintln("The input file \"" + file
327 + "\" has null or unidentifiable data content!");
328 if (!Jalview.isHeadlessMode() && !Jalview.isBatchMode())
330 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
331 MessageManager.getString("label.couldnt_read_data")
332 + " in " + file + "\n"
333 + AppletFormatAdapter.getSupportedFormats(),
334 MessageManager.getString("label.couldnt_read_data"),
335 JvOptionPane.WARNING_MESSAGE);
337 // don't set shouldBeSaved if didn't load anything
338 // this.setShouldBeSaved();
341 // TODO: cache any stream datasources as a temporary file (eg. PDBs
342 // retrieved via URL)
343 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
346 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
351 loadtime = -System.currentTimeMillis();
352 AlignmentI al = null;
354 if (FileFormat.Jalview.equals(format))
358 // Tell the user (developer?) that this is going to cause a problem
359 jalview.bin.Console.errPrintln(
360 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
361 // We read the data anyway - it might make sense.
363 // BH 2018 switch to File object here instead of filename
364 alignFrame = new Jalview2XML(raiseGUI && !Jalview.isBatchMode())
366 selectedFile == null ? file : selectedFile);
370 String error = AppletFormatAdapter.getSupportedFormats();
375 // read from the provided source
376 al = new FormatAdapter().readFromFile(source, format);
381 // open a new source and read from it
382 FormatAdapter fa = new FormatAdapter();
383 boolean downloadStructureFile = format.isStructureFile()
384 && protocol.equals(DataSourceType.URL);
385 if (downloadStructureFile)
387 String structExt = format.getExtensions().split(",")[0];
388 String urlLeafName = file.substring(
390 System.getProperty("file.separator")),
391 file.lastIndexOf("."));
392 String tempStructureFileStr = createNamedJvTempFile(
393 urlLeafName, structExt);
395 // BH - switching to File object here so as to hold
396 // ._bytes array directly
397 File tempFile = new File(tempStructureFileStr);
398 UrlDownloadClient.download(file, tempFile);
400 al = fa.readFile(tempFile, DataSourceType.FILE, format);
401 source = fa.getAlignFile();
405 if (selectedFile == null)
407 al = fa.readFile(null, file, protocol, format);
412 al = fa.readFile(selectedFile, null, protocol, format);
414 source = fa.getAlignFile(); // keep reference for later if
419 } catch (java.io.IOException ex)
421 error = ex.getMessage();
424 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
426 // construct and register dataset sequences
427 for (SequenceI sq : al.getSequences())
429 while (sq.getDatasetSequence() != null)
431 sq = sq.getDatasetSequence();
433 if (sq.getAllPDBEntries() != null)
435 for (PDBEntry pdbe : sq.getAllPDBEntries())
437 // register PDB entries with desktop's structure selection
439 StructureSelectionManager
440 .getStructureSelectionManager(Desktop.instance)
441 .registerPDBEntry(pdbe);
446 FeatureSettingsModelI proxyColourScheme = source
447 .getFeatureColourScheme();
448 if (viewport != null)
450 // append to existing alignment
451 viewport.addAlignment(al, title);
452 viewport.applyFeaturesStyle(proxyColourScheme);
456 // otherwise construct the alignFrame
458 if (source instanceof ComplexAlignFile)
460 HiddenColumns colSel = ((ComplexAlignFile) source)
462 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
463 .getHiddenSequences();
464 String colourSchemeName = ((ComplexAlignFile) source)
465 .getGlobalColourScheme();
466 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
467 .getDisplayedFeatures();
468 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
469 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
470 alignFrame.getViewport().setFeaturesDisplayed(fd);
471 alignFrame.getViewport().setShowSequenceFeatures(
472 ((ComplexAlignFile) source).isShowSeqFeatures());
473 ColourSchemeI cs = ColourSchemeMapper
474 .getJalviewColourScheme(colourSchemeName, al);
477 alignFrame.changeColour(cs);
482 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
483 AlignFrame.DEFAULT_HEIGHT);
484 if (source instanceof FeaturesSourceI)
486 alignFrame.getViewport().setShowSequenceFeatures(true);
489 // add metadata and update ui
490 if (!(protocol == DataSourceType.PASTE))
492 alignFrame.setFileName(file, format);
493 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
495 if (proxyColourScheme != null)
497 alignFrame.getViewport()
498 .applyFeaturesStyle(proxyColourScheme);
500 alignFrame.setStatus(MessageManager.formatMessage(
501 "label.successfully_loaded_file", new String[]
506 // add the window to the GUI
507 // note - this actually should happen regardless of raiseGUI
508 // status in Jalview 3
509 // TODO: define 'virtual desktop' for benefit of headless scripts
510 // that perform queries to find the 'current working alignment'
511 Desktop.addInternalFrame(alignFrame, title,
512 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
515 * for an Overview automatically opened with alignment,
516 * set its title now alignFrame title has been set
518 alignFrame.alignPanel.setOverviewTitle(alignFrame);
523 alignFrame.setMaximum(
524 Cache.getDefault("SHOW_FULLSCREEN", false));
525 } catch (java.beans.PropertyVetoException ex)
532 if (Desktop.instance != null)
534 Desktop.instance.stopLoading();
537 final String errorMessage = MessageManager.getString(
538 "label.couldnt_load_file") + " " + title + "\n" + error;
539 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
541 if (raiseGUI && !Jalview.isBatchMode() && Desktop.desktop != null)
543 javax.swing.SwingUtilities.invokeLater(new Runnable()
548 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
551 .getString("label.error_loading_file"),
552 JvOptionPane.WARNING_MESSAGE);
558 jalview.bin.Console.errPrintln(errorMessage);
563 updateRecentlyOpened();
565 } catch (Exception er)
568 .errPrintln("Exception whilst opening file '" + file);
569 er.printStackTrace();
570 if (raiseGUI && !Jalview.isBatchMode())
572 javax.swing.SwingUtilities.invokeLater(new Runnable()
577 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
578 MessageManager.formatMessage(
579 "label.problems_opening_file", new String[]
581 MessageManager.getString("label.file_open_error"),
582 JvOptionPane.WARNING_MESSAGE);
587 } catch (OutOfMemoryError er)
590 er.printStackTrace();
592 if (raiseGUI && !Jalview.isBatchMode())
594 javax.swing.SwingUtilities.invokeLater(new Runnable()
599 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
600 MessageManager.formatMessage(
601 "warn.out_of_memory_loading_file", new String[]
603 MessageManager.getString("label.out_of_memory"),
604 JvOptionPane.WARNING_MESSAGE);
609 .errPrintln("Out of memory loading file " + file + "!!");
612 loadtime += System.currentTimeMillis();
613 // TODO: Estimate percentage of memory used by a newly loaded alignment -
614 // warn if more memory will be needed to work with it
617 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
622 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
624 if (alignFrame != null)
626 AlignmentI al = alignFrame.getViewport().getAlignment();
628 jalview.bin.Console.outPrintln("Loaded '" + title + "' in "
629 + (loadtime / 1000.0) + "s, took an additional "
630 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
631 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
635 // report that we didn't load anything probably due to an out of memory
637 jalview.bin.Console.outPrintln("Failed to load '" + title + "' in "
638 + (loadtime / 1000.0) + "s, took an additional "
639 + (1.0 * memused / (1024.0 * 1024.0))
640 + " MB (alignment is null)");
643 // remove the visual delay indicator
644 if (Desktop.instance != null)
646 Desktop.instance.stopLoading();
649 this.setShouldBeSaved();
650 // after first file loaded we revert to assuming a default file format
651 useDefaultFileFormat = true;
655 * This method creates the file -
656 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
657 * file name and extension
660 * the name of the temp file to be created
662 * the extension of the temp file to be created
665 private static String createNamedJvTempFile(String fileName,
666 String extension) throws IOException
668 String seprator = System.getProperty("file.separator");
669 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
670 + seprator + System.currentTimeMillis();
671 File tempStructFile = new File(
672 jvTempDir + seprator + fileName + "." + extension);
673 tempStructFile.mkdirs();
674 return tempStructFile.toString();
678 * set whether quit should ask to save when just loaded this source
680 private void setShouldBeSaved()
682 if (protocol == null)
684 AlignFrame af = this.alignFrame;
687 AlignViewport avp = af.getViewport();
690 boolean upToDate = !protocol.isDynamic();
691 if (protocol.isUrl() && !Cache
692 .getDefault(PROMPT_SAVE_UNCHANGED_URL_ALIGNMENTS, true))
696 avp.setSavedUpToDate(upToDate,
697 upToDate ? null : QuitHandler.Message.UNSAVED_ALIGNMENTS);
700 public static final String PROMPT_SAVE_UNCHANGED_URL_ALIGNMENTS = "PROMPT_SAVE_UNCHANGED_URL_ALIGNMENTS";
702 public static boolean getUseDefaultFileFormat()
704 return useDefaultFileFormat;