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.BamFileOptionsChooser;
43 import jalview.gui.Desktop;
44 import jalview.gui.JvOptionPane;
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;
78 * default constructor always raised errors in GUI dialog boxes
86 * construct a Fileloader that may raise errors non-interactively
89 * true if errors are to be raised as GUI dialog boxes
91 public FileLoader(boolean raiseGUI)
93 this.raiseGUI = raiseGUI;
96 public void LoadFile(AlignViewport viewport, Object file,
97 DataSourceType protocol, FileFormatI format)
99 this.viewport = viewport;
100 if (file instanceof File) {
101 this.selectedFile = (File) file;
102 file = selectedFile.getPath();
104 LoadFile(file.toString(), protocol, format);
107 public void LoadFile(String file, DataSourceType protocol,
111 this.protocol = protocol;
112 this.format = format;
114 final Thread loader = new Thread(this);
116 SwingUtilities.invokeLater(new Runnable()
127 * Load a (file, protocol) source of unknown type
132 public void LoadFile(String file, DataSourceType protocol)
134 LoadFile(file, protocol, null);
138 * Load alignment from (file, protocol) and wait till loaded
142 * @return alignFrame constructed from file contents
144 public AlignFrame LoadFileWaitTillLoaded(String file,
145 DataSourceType sourceType)
147 return LoadFileWaitTillLoaded(file, sourceType, null);
151 * Load alignment from (file, protocol) of type format and wait till loaded
156 * @return alignFrame constructed from file contents
158 public AlignFrame LoadFileWaitTillLoaded(String file,
159 DataSourceType sourceType, FileFormatI format)
162 this.protocol = sourceType;
163 this.format = format;
164 return _LoadFileWaitTillLoaded();
168 * Load alignment from (file, protocol) of type format and wait till loaded
173 * @return alignFrame constructed from file contents
175 public AlignFrame LoadFileWaitTillLoaded(File file,
176 DataSourceType sourceType, FileFormatI format)
178 this.selectedFile = file;
179 this.file = file.getPath();
180 this.protocol = sourceType;
181 this.format = format;
182 return _LoadFileWaitTillLoaded();
186 * Load alignment from FileParse source of type format and wait till loaded
190 * @return alignFrame constructed from file contents
192 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
195 this.source = source;
197 file = source.getInFile();
198 protocol = source.getDataSourceType();
199 this.format = format;
200 return _LoadFileWaitTillLoaded();
204 * runs the 'run' method (in this thread), then return the alignFrame that's
205 * (hopefully) been read
209 protected AlignFrame _LoadFileWaitTillLoaded()
216 public void updateRecentlyOpened()
218 Vector<String> recent = new Vector<>();
219 if (protocol == DataSourceType.PASTE)
221 // do nothing if the file was pasted in as text... there is no filename to
226 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
228 // ignore files loaded from the system's temporary directory
231 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
234 String historyItems = Cache.getProperty(type);
238 if (historyItems != null)
240 st = new StringTokenizer(historyItems, "\t");
242 while (st.hasMoreTokens())
244 recent.addElement(st.nextToken().trim());
248 if (recent.contains(file))
253 StringBuffer newHistory = new StringBuffer(file);
254 for (int i = 0; i < recent.size() && i < 10; i++)
256 newHistory.append("\t");
257 newHistory.append(recent.elementAt(i));
260 Cache.setProperty(type, newHistory.toString());
262 if (protocol == DataSourceType.FILE)
264 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
271 String title = protocol == DataSourceType.PASTE
272 ? "Copied From Clipboard"
274 Runtime rt = Runtime.getRuntime();
277 if (Desktop.instance != null)
279 Desktop.instance.startLoading(file);
283 // just in case the caller didn't identify the file for us
286 format = new IdentifyFile().identify(source, false);
287 // identify stream and rewind rather than close
289 else if (selectedFile != null) {
290 format = new IdentifyFile().identify(selectedFile, protocol);
294 format = new IdentifyFile().identify(file, protocol);
301 Desktop.instance.stopLoading();
302 System.err.println("The input file \"" + file
303 + "\" has null or unidentifiable data content!");
304 if (!Jalview.isHeadlessMode())
306 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
307 MessageManager.getString("label.couldnt_read_data")
308 + " in " + file + "\n"
309 + AppletFormatAdapter.getSupportedFormats(),
310 MessageManager.getString("label.couldnt_read_data"),
311 JvOptionPane.WARNING_MESSAGE);
315 // TODO: cache any stream datasources as a temporary file (eg. PDBs
316 // retrieved via URL)
317 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
320 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
325 loadtime = -System.currentTimeMillis();
326 AlignmentI al = null;
328 if (FileFormat.Bam.equals(format))
330 FormatAdapter fa = new FormatAdapter();
333 fa.prepareFileReader(null, file, protocol, format);
334 source = fa.getAlignFile();
336 if (!((BamFile) source).parseSuffix())
338 // configure a window
339 BamFileOptionsChooser bamoptions = new BamFileOptionsChooser(
341 // ask the user which bit of the bam they want to load
342 int confirm = JvOptionPane.showConfirmDialog(null, bamoptions,
343 MessageManager.getString("label.bam_file_options"),
344 JvOptionPane.OK_CANCEL_OPTION,
345 JvOptionPane.PLAIN_MESSAGE);
347 if (confirm == JvOptionPane.CANCEL_OPTION
348 || confirm == JvOptionPane.CLOSED_OPTION)
350 Desktop.instance.stopLoading();
355 bamoptions.update(source);
356 if (file.indexOf("#") == -1)
358 file = file + "#" + ((BamFile) source).suffix;
362 al = fa.readFile(file, protocol, format);
365 if (FileFormat.Jalview.equals(format))
369 // Tell the user (developer?) that this is going to cause a problem
371 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
372 // We read the data anyway - it might make sense.
374 // BH 2018 switch to File object here instead of filename
375 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
379 String error = AppletFormatAdapter.getSupportedFormats();
384 // read from the provided source
385 al = new FormatAdapter().readFromFile(source, format);
390 // open a new source and read from it
391 FormatAdapter fa = new FormatAdapter();
392 boolean downloadStructureFile = format.isStructureFile()
393 && protocol.equals(DataSourceType.URL);
394 if (downloadStructureFile)
396 String structExt = format.getExtensions().split(",")[0];
397 String urlLeafName = file.substring(
399 System.getProperty("file.separator")),
400 file.lastIndexOf("."));
401 String tempStructureFileStr = createNamedJvTempFile(
402 urlLeafName, structExt);
404 // BH - switching to File object here so as to hold
405 // ._bytes array directly
406 File tempFile = new File(tempStructureFileStr);
407 UrlDownloadClient.download(file, tempFile);
409 al = fa.readFile(tempFile, DataSourceType.FILE,
411 source = fa.getAlignFile();
415 if (selectedFile == null) {
416 al = fa.readFile(file, protocol, format);
419 al = fa.readFile(selectedFile, protocol, format);
421 source = fa.getAlignFile(); // keep reference for later if
425 } catch (java.io.IOException ex)
427 error = ex.getMessage();
430 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
432 // construct and register dataset sequences
433 for (SequenceI sq : al.getSequences())
435 while (sq.getDatasetSequence() != null)
437 sq = sq.getDatasetSequence();
439 if (sq.getAllPDBEntries() != null)
441 for (PDBEntry pdbe : sq.getAllPDBEntries())
443 // register PDB entries with desktop's structure selection
445 StructureSelectionManager
446 .getStructureSelectionManager(Desktop.instance)
447 .registerPDBEntry(pdbe);
452 FeatureSettingsModelI proxyColourScheme = source
453 .getFeatureColourScheme();
454 if (viewport != null)
456 // append to existing alignment
457 viewport.addAlignment(al, title);
458 viewport.applyFeaturesStyle(proxyColourScheme);
462 // otherwise construct the alignFrame
464 if (source instanceof ComplexAlignFile)
466 HiddenColumns colSel = ((ComplexAlignFile) source)
468 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
469 .getHiddenSequences();
470 String colourSchemeName = ((ComplexAlignFile) source)
471 .getGlobalColourScheme();
472 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
473 .getDisplayedFeatures();
474 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
475 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
476 alignFrame.getViewport().setFeaturesDisplayed(fd);
477 alignFrame.getViewport().setShowSequenceFeatures(
478 ((ComplexAlignFile) source).isShowSeqFeatures());
479 ColourSchemeI cs = ColourSchemeMapper
480 .getJalviewColourScheme(colourSchemeName, al);
483 alignFrame.changeColour(cs);
488 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
489 AlignFrame.DEFAULT_HEIGHT);
490 if (source instanceof FeaturesSourceI)
492 alignFrame.getViewport().setShowSequenceFeatures(true);
495 // add metadata and update ui
496 if (!(protocol == DataSourceType.PASTE))
498 alignFrame.setFileName(file, format);
499 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
501 if (proxyColourScheme != null)
503 alignFrame.getViewport()
504 .applyFeaturesStyle(proxyColourScheme);
506 alignFrame.setStatus(MessageManager.formatMessage(
507 "label.successfully_loaded_file", new String[]
512 // add the window to the GUI
513 // note - this actually should happen regardless of raiseGUI
514 // status in Jalview 3
515 // TODO: define 'virtual desktop' for benefit of headless scripts
516 // that perform queries to find the 'current working alignment'
517 Desktop.addInternalFrame(alignFrame, title,
518 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
523 alignFrame.setMaximum(jalview.bin.Cache
524 .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 && 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 System.err.println(errorMessage);
563 updateRecentlyOpened();
565 } catch (Exception er)
567 System.err.println("Exception whilst opening file '" + file);
568 er.printStackTrace();
571 javax.swing.SwingUtilities.invokeLater(new Runnable()
576 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
577 MessageManager.formatMessage(
578 "label.problems_opening_file", new String[]
580 MessageManager.getString("label.file_open_error"),
581 JvOptionPane.WARNING_MESSAGE);
586 } catch (OutOfMemoryError er)
589 er.printStackTrace();
593 javax.swing.SwingUtilities.invokeLater(new Runnable()
598 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
599 MessageManager.formatMessage(
600 "warn.out_of_memory_loading_file", new String[]
602 MessageManager.getString("label.out_of_memory"),
603 JvOptionPane.WARNING_MESSAGE);
607 System.err.println("Out of memory loading file " + file + "!!");
610 loadtime += System.currentTimeMillis();
611 // TODO: Estimate percentage of memory used by a newly loaded alignment -
612 // warn if more memory will be needed to work with it
615 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
620 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
622 if (alignFrame != null)
624 AlignmentI al = alignFrame.getViewport().getAlignment();
626 System.out.println("Loaded '" + title + "' in "
627 + (loadtime / 1000.0) + "s, took an additional "
628 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
629 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
633 // report that we didn't load anything probably due to an out of memory
635 System.out.println("Failed to load '" + title + "' in "
636 + (loadtime / 1000.0) + "s, took an additional "
637 + (1.0 * memused / (1024.0 * 1024.0))
638 + " MB (alignment is null)");
641 // remove the visual delay indicator
642 if (Desktop.instance != null)
644 Desktop.instance.stopLoading();
650 * This method creates the file -
651 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
652 * file name and extension
655 * the name of the temp file to be created
657 * the extension of the temp file to be created
660 private static String createNamedJvTempFile(String fileName,
661 String extension) throws IOException
663 String seprator = System.getProperty("file.separator");
664 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
665 + seprator + System.currentTimeMillis();
666 File tempStructFile = new File(
667 jvTempDir + seprator + fileName + "." + extension);
668 tempStructFile.mkdirs();
669 return tempStructFile.toString();