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()).loadJalviewAlign(
365 selectedFile == null ? file : selectedFile);
369 String error = AppletFormatAdapter.getSupportedFormats();
374 // read from the provided source
375 al = new FormatAdapter().readFromFile(source, format);
380 // open a new source and read from it
381 FormatAdapter fa = new FormatAdapter();
382 boolean downloadStructureFile = format.isStructureFile()
383 && protocol.equals(DataSourceType.URL);
384 if (downloadStructureFile)
386 String structExt = format.getExtensions().split(",")[0];
387 String urlLeafName = file.substring(
389 System.getProperty("file.separator")),
390 file.lastIndexOf("."));
391 String tempStructureFileStr = createNamedJvTempFile(
392 urlLeafName, structExt);
394 // BH - switching to File object here so as to hold
395 // ._bytes array directly
396 File tempFile = new File(tempStructureFileStr);
397 UrlDownloadClient.download(file, tempFile);
399 al = fa.readFile(tempFile, DataSourceType.FILE, format);
400 source = fa.getAlignFile();
404 if (selectedFile == null)
406 al = fa.readFile(null, file, protocol, format);
411 al = fa.readFile(selectedFile, null, protocol, format);
413 source = fa.getAlignFile(); // keep reference for later if
418 } catch (java.io.IOException ex)
420 error = ex.getMessage();
423 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
425 // construct and register dataset sequences
426 for (SequenceI sq : al.getSequences())
428 while (sq.getDatasetSequence() != null)
430 sq = sq.getDatasetSequence();
432 if (sq.getAllPDBEntries() != null)
434 for (PDBEntry pdbe : sq.getAllPDBEntries())
436 // register PDB entries with desktop's structure selection
438 StructureSelectionManager
439 .getStructureSelectionManager(Desktop.instance)
440 .registerPDBEntry(pdbe);
445 FeatureSettingsModelI proxyColourScheme = source
446 .getFeatureColourScheme();
447 if (viewport != null)
449 // append to existing alignment
450 viewport.addAlignment(al, title);
451 viewport.applyFeaturesStyle(proxyColourScheme);
455 // otherwise construct the alignFrame
457 if (source instanceof ComplexAlignFile)
459 HiddenColumns colSel = ((ComplexAlignFile) source)
461 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
462 .getHiddenSequences();
463 String colourSchemeName = ((ComplexAlignFile) source)
464 .getGlobalColourScheme();
465 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
466 .getDisplayedFeatures();
467 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
468 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
469 alignFrame.getViewport().setFeaturesDisplayed(fd);
470 alignFrame.getViewport().setShowSequenceFeatures(
471 ((ComplexAlignFile) source).isShowSeqFeatures());
472 ColourSchemeI cs = ColourSchemeMapper
473 .getJalviewColourScheme(colourSchemeName, al);
476 alignFrame.changeColour(cs);
481 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
482 AlignFrame.DEFAULT_HEIGHT);
483 if (source instanceof FeaturesSourceI)
485 alignFrame.getViewport().setShowSequenceFeatures(true);
488 // add metadata and update ui
489 if (!(protocol == DataSourceType.PASTE))
491 alignFrame.setFileName(file, format);
492 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
494 if (proxyColourScheme != null)
496 alignFrame.getViewport()
497 .applyFeaturesStyle(proxyColourScheme);
499 alignFrame.setStatus(MessageManager.formatMessage(
500 "label.successfully_loaded_file", new String[]
505 // add the window to the GUI
506 // note - this actually should happen regardless of raiseGUI
507 // status in Jalview 3
508 // TODO: define 'virtual desktop' for benefit of headless scripts
509 // that perform queries to find the 'current working alignment'
510 Desktop.addInternalFrame(alignFrame, title,
511 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
514 * for an Overview automatically opened with alignment,
515 * set its title now alignFrame title has been set
517 alignFrame.alignPanel.setOverviewTitle(alignFrame);
522 alignFrame.setMaximum(
523 Cache.getDefault("SHOW_FULLSCREEN", false));
524 } catch (java.beans.PropertyVetoException ex)
531 if (Desktop.instance != null)
533 Desktop.instance.stopLoading();
536 final String errorMessage = MessageManager.getString(
537 "label.couldnt_load_file") + " " + title + "\n" + error;
538 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
540 if (raiseGUI && !Jalview.isBatchMode() && Desktop.desktop != null)
542 javax.swing.SwingUtilities.invokeLater(new Runnable()
547 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
550 .getString("label.error_loading_file"),
551 JvOptionPane.WARNING_MESSAGE);
557 jalview.bin.Console.errPrintln(errorMessage);
562 updateRecentlyOpened();
564 } catch (Exception er)
566 jalview.bin.Console.errPrintln("Exception whilst opening file '" + file);
567 er.printStackTrace();
568 if (raiseGUI && !Jalview.isBatchMode())
570 javax.swing.SwingUtilities.invokeLater(new Runnable()
575 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
576 MessageManager.formatMessage(
577 "label.problems_opening_file", new String[]
579 MessageManager.getString("label.file_open_error"),
580 JvOptionPane.WARNING_MESSAGE);
585 } catch (OutOfMemoryError er)
588 er.printStackTrace();
590 if (raiseGUI && !Jalview.isBatchMode())
592 javax.swing.SwingUtilities.invokeLater(new Runnable()
597 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
598 MessageManager.formatMessage(
599 "warn.out_of_memory_loading_file", new String[]
601 MessageManager.getString("label.out_of_memory"),
602 JvOptionPane.WARNING_MESSAGE);
606 jalview.bin.Console.errPrintln("Out of memory loading file " + file + "!!");
609 loadtime += System.currentTimeMillis();
610 // TODO: Estimate percentage of memory used by a newly loaded alignment -
611 // warn if more memory will be needed to work with it
614 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
619 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
621 if (alignFrame != null)
623 AlignmentI al = alignFrame.getViewport().getAlignment();
625 jalview.bin.Console.outPrintln("Loaded '" + title + "' in "
626 + (loadtime / 1000.0) + "s, took an additional "
627 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
628 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
632 // report that we didn't load anything probably due to an out of memory
634 jalview.bin.Console.outPrintln("Failed to load '" + title + "' in "
635 + (loadtime / 1000.0) + "s, took an additional "
636 + (1.0 * memused / (1024.0 * 1024.0))
637 + " MB (alignment is null)");
640 // remove the visual delay indicator
641 if (Desktop.instance != null)
643 Desktop.instance.stopLoading();
646 this.setShouldBeSaved();
647 // after first file loaded we revert to assuming a default file format
648 useDefaultFileFormat = true;
652 * This method creates the file -
653 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
654 * file name and extension
657 * the name of the temp file to be created
659 * the extension of the temp file to be created
662 private static String createNamedJvTempFile(String fileName,
663 String extension) throws IOException
665 String seprator = System.getProperty("file.separator");
666 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
667 + seprator + System.currentTimeMillis();
668 File tempStructFile = new File(
669 jvTempDir + seprator + fileName + "." + extension);
670 tempStructFile.mkdirs();
671 return tempStructFile.toString();
675 * set whether quit should ask to save when just loaded this source
677 private void setShouldBeSaved()
679 if (protocol == null)
681 AlignFrame af = this.alignFrame;
684 AlignViewport avp = af.getViewport();
687 avp.setSavedUpToDate(!protocol.isDynamic(),
688 QuitHandler.Message.UNSAVED_ALIGNMENTS);
691 public static boolean getUseDefaultFileFormat()
693 return useDefaultFileFormat;