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.Console;
36 import jalview.bin.Jalview;
37 import jalview.datamodel.AlignmentI;
38 import jalview.datamodel.HiddenColumns;
39 import jalview.datamodel.PDBEntry;
40 import jalview.datamodel.SequenceI;
41 import jalview.gui.AlignFrame;
42 import jalview.gui.AlignViewport;
43 import jalview.gui.Desktop;
44 import jalview.gui.JvOptionPane;
45 import jalview.gui.QuitHandler;
46 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
47 import jalview.project.Jalview2XML;
48 import jalview.schemes.ColourSchemeI;
49 import jalview.structure.StructureSelectionManager;
50 import jalview.util.MessageManager;
51 import jalview.ws.utils.UrlDownloadClient;
53 public class FileLoader implements Runnable
57 DataSourceType protocol;
61 AlignmentFileReaderI source = null; // alternative specification of where data
66 AlignViewport viewport;
68 AlignFrame alignFrame;
74 boolean raiseGUI = true;
76 private File selectedFile;
79 * default constructor always raised errors in GUI dialog boxes
87 * construct a Fileloader that may raise errors non-interactively
90 * true if errors are to be raised as GUI dialog boxes
92 public FileLoader(boolean raiseGUI)
94 this.raiseGUI = raiseGUI;
97 public void LoadFile(AlignViewport viewport, Object file,
98 DataSourceType protocol, FileFormatI format)
100 this.viewport = viewport;
101 if (file instanceof File)
103 this.selectedFile = (File) file;
104 file = selectedFile.getPath();
106 LoadFile(file.toString(), protocol, format);
109 public void LoadFile(String file, DataSourceType protocol,
113 this.protocol = protocol;
114 this.format = format;
116 final Thread loader = new Thread(this);
118 SwingUtilities.invokeLater(new Runnable()
129 * Load a (file, protocol) source of unknown type
134 public void LoadFile(String file, DataSourceType protocol)
136 LoadFile(file, protocol, null);
140 * Load alignment from (file, protocol) and wait till loaded
144 * @return alignFrame constructed from file contents
146 public AlignFrame LoadFileWaitTillLoaded(String file,
147 DataSourceType sourceType)
149 return LoadFileWaitTillLoaded(file, sourceType, null);
153 * Load alignment from (file, protocol) of type format and wait till loaded
158 * @return alignFrame constructed from file contents
160 public AlignFrame LoadFileWaitTillLoaded(String file,
161 DataSourceType sourceType, FileFormatI format)
164 this.protocol = sourceType;
165 this.format = format;
166 return _LoadFileWaitTillLoaded();
170 * Load alignment from (file, protocol) of type format and wait till loaded
175 * @return alignFrame constructed from file contents
177 public AlignFrame LoadFileWaitTillLoaded(File file,
178 DataSourceType sourceType, FileFormatI format)
180 this.selectedFile = file;
181 this.file = file.getPath();
182 this.protocol = sourceType;
183 this.format = format;
184 return _LoadFileWaitTillLoaded();
188 * Load alignment from FileParse source of type format and wait till loaded
192 * @return alignFrame constructed from file contents
194 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
197 this.source = source;
199 file = source.getInFile();
200 protocol = source.getDataSourceType();
201 this.format = format;
202 return _LoadFileWaitTillLoaded();
206 * runs the 'run' method (in this thread), then return the alignFrame that's
207 * (hopefully) been read
211 protected AlignFrame _LoadFileWaitTillLoaded()
218 public void updateRecentlyOpened()
220 Vector<String> recent = new Vector<>();
221 if (protocol == DataSourceType.PASTE)
223 // do nothing if the file was pasted in as text... there is no filename to
228 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
230 // ignore files loaded from the system's temporary directory
233 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
236 String historyItems = Cache.getProperty(type);
240 if (historyItems != null)
242 st = new StringTokenizer(historyItems, "\t");
244 while (st.hasMoreTokens())
246 recent.addElement(st.nextToken().trim());
250 if (recent.contains(file))
255 StringBuffer newHistory = new StringBuffer(file);
256 for (int i = 0; i < recent.size() && i < 10; i++)
258 newHistory.append("\t");
259 newHistory.append(recent.elementAt(i));
262 Cache.setProperty(type, newHistory.toString());
264 if (protocol == DataSourceType.FILE)
266 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
273 String title = protocol == DataSourceType.PASTE
274 ? "Copied From Clipboard"
276 Runtime rt = Runtime.getRuntime();
280 if (Desktop.instance != null)
282 Desktop.instance.startLoading(file);
286 // just in case the caller didn't identify the file for us
289 format = new IdentifyFile().identify(source, false);
290 // identify stream and rewind rather than close
292 else if (selectedFile != null)
294 format = new IdentifyFile().identify(selectedFile, protocol);
298 format = new IdentifyFile().identify(file, protocol);
305 Desktop.instance.stopLoading();
306 System.err.println("The input file \"" + file
307 + "\" has null or unidentifiable data content!");
308 if (!Jalview.isHeadlessMode())
310 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
311 MessageManager.getString("label.couldnt_read_data")
312 + " in " + file + "\n"
313 + AppletFormatAdapter.getSupportedFormats(),
314 MessageManager.getString("label.couldnt_read_data"),
315 JvOptionPane.WARNING_MESSAGE);
317 this.setShouldBeSaved();
320 // TODO: cache any stream datasources as a temporary file (eg. PDBs
321 // retrieved via URL)
322 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
325 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
330 loadtime = -System.currentTimeMillis();
331 AlignmentI al = null;
332 if (FileFormat.Jalview.equals(format))
336 // Tell the user (developer?) that this is going to cause a problem
338 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
339 // We read the data anyway - it might make sense.
341 // BH 2018 switch to File object here instead of filename
342 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
343 selectedFile == null ? file : selectedFile);
347 FormatAdapter fa = null; // populated for simple and complex flatfile formats - but not Jalview Projects
348 String error = AppletFormatAdapter.getSupportedFormats();
353 fa=new FormatAdapter();
354 // read from the provided source
355 al = fa.readFromFile(source, format);
360 // open a new source and read from it
361 fa = new FormatAdapter();
362 boolean downloadStructureFile = format.isStructureFile()
363 && protocol.equals(DataSourceType.URL);
364 if (downloadStructureFile)
366 String structExt = format.getExtensions().split(",")[0];
367 String urlLeafName = file.substring(
369 System.getProperty("file.separator")),
370 file.lastIndexOf("."));
371 String tempStructureFileStr = createNamedJvTempFile(
372 urlLeafName, structExt);
374 // BH - switching to File object here so as to hold
375 // ._bytes array directly
376 File tempFile = new File(tempStructureFileStr);
377 UrlDownloadClient.download(file, tempFile);
379 al = fa.readFile(tempFile, DataSourceType.FILE, format);
380 source = fa.getAlignFile();
384 if (selectedFile == null)
386 al = fa.readFile(null, file, protocol, format);
391 al = fa.readFile(selectedFile, null, protocol, format);
393 source = fa.getAlignFile(); // keep reference for later if
398 } catch (java.io.IOException ex)
400 error = ex.getMessage();
403 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
405 // construct and register dataset sequences
406 for (SequenceI sq : al.getSequences())
408 while (sq.getDatasetSequence() != null)
410 sq = sq.getDatasetSequence();
412 if (sq.getAllPDBEntries() != null)
414 for (PDBEntry pdbe : sq.getAllPDBEntries())
416 // register PDB entries with desktop's structure selection
418 StructureSelectionManager
419 .getStructureSelectionManager(Desktop.instance)
420 .registerPDBEntry(pdbe);
425 FeatureSettingsModelI proxyColourScheme = source
426 .getFeatureColourScheme();
427 if (viewport != null)
429 // append to existing alignment
430 viewport.addAlignment(al, title);
431 viewport.applyFeaturesStyle(proxyColourScheme);
435 // otherwise construct the alignFrame
437 if (source instanceof ComplexAlignFile)
439 HiddenColumns colSel = ((ComplexAlignFile) source)
441 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
442 .getHiddenSequences();
443 String colourSchemeName = ((ComplexAlignFile) source)
444 .getGlobalColourScheme();
445 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
446 .getDisplayedFeatures();
447 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
448 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
449 alignFrame.getViewport().setFeaturesDisplayed(fd);
450 alignFrame.getViewport().setShowSequenceFeatures(
451 ((ComplexAlignFile) source).isShowSeqFeatures());
452 ColourSchemeI cs = ColourSchemeMapper
453 .getJalviewColourScheme(colourSchemeName, al);
456 alignFrame.changeColour(cs);
461 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
462 AlignFrame.DEFAULT_HEIGHT);
463 if (source instanceof FeaturesSourceI)
465 alignFrame.getViewport().setShowSequenceFeatures(true);
468 // add metadata and update ui
469 if (!(protocol == DataSourceType.PASTE))
471 alignFrame.setFileName(file, format);
472 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
474 if (proxyColourScheme != null)
476 alignFrame.getViewport()
477 .applyFeaturesStyle(proxyColourScheme);
479 if (source.hasTrees())
481 for (String[] nhxtree : source.getNewickTrees())
483 NewickFile fin = null;
486 fin = new NewickFile(new FileParse(nhxtree[1],
487 DataSourceType.PASTE));
488 if (fin.hasWarningMessage())
491 "Warnings when importing tree from file: "
492 + fin.getWarningMessage());
494 if (fin.isValid())// && fin.getTree() != null)
496 alignFrame.showNewickTree(fin, nhxtree[0]);
498 Console.warn("Ignoring tree "+nhxtree[0]+"\t"+nhxtree[1]);
500 } catch (Throwable thr)
502 Console.warn("Couldn't import tree from file", thr);
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);
521 * for an Overview automatically opened with alignment,
522 * set its title now alignFrame title has been set
524 alignFrame.alignPanel.setOverviewTitle(alignFrame);
529 alignFrame.setMaximum(
530 Cache.getDefault("SHOW_FULLSCREEN", false));
531 } catch (java.beans.PropertyVetoException ex)
538 if (Desktop.instance != null)
540 Desktop.instance.stopLoading();
543 final String errorMessage = MessageManager.getString(
544 "label.couldnt_load_file") + " " + title + "\n" + error;
545 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
547 if (raiseGUI && Desktop.desktop != null)
549 javax.swing.SwingUtilities.invokeLater(new Runnable()
554 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
557 .getString("label.error_loading_file"),
558 JvOptionPane.WARNING_MESSAGE);
564 System.err.println(errorMessage);
569 updateRecentlyOpened();
571 } catch (Exception er)
573 System.err.println("Exception whilst opening file '" + file);
574 er.printStackTrace();
577 javax.swing.SwingUtilities.invokeLater(new Runnable()
582 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
583 MessageManager.formatMessage(
584 "label.problems_opening_file", new String[]
586 MessageManager.getString("label.file_open_error"),
587 JvOptionPane.WARNING_MESSAGE);
592 } catch (OutOfMemoryError er)
595 er.printStackTrace();
599 javax.swing.SwingUtilities.invokeLater(new Runnable()
604 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
605 MessageManager.formatMessage(
606 "warn.out_of_memory_loading_file", new String[]
608 MessageManager.getString("label.out_of_memory"),
609 JvOptionPane.WARNING_MESSAGE);
613 System.err.println("Out of memory loading file " + file + "!!");
616 loadtime += System.currentTimeMillis();
617 // TODO: Estimate percentage of memory used by a newly loaded alignment -
618 // warn if more memory will be needed to work with it
621 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
626 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
628 if (alignFrame != null)
630 AlignmentI al = alignFrame.getViewport().getAlignment();
632 System.out.println("Loaded '" + title + "' in "
633 + (loadtime / 1000.0) + "s, took an additional "
634 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
635 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
639 // report that we didn't load anything probably due to an out of memory
641 System.out.println("Failed to load '" + title + "' in "
642 + (loadtime / 1000.0) + "s, took an additional "
643 + (1.0 * memused / (1024.0 * 1024.0))
644 + " MB (alignment is null)");
647 // remove the visual delay indicator
648 if (Desktop.instance != null)
650 Desktop.instance.stopLoading();
653 this.setShouldBeSaved();
657 * This method creates the file -
658 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
659 * file name and extension
662 * the name of the temp file to be created
664 * the extension of the temp file to be created
667 private static String createNamedJvTempFile(String fileName,
668 String extension) throws IOException
670 String seprator = System.getProperty("file.separator");
671 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
672 + seprator + System.currentTimeMillis();
673 File tempStructFile = new File(
674 jvTempDir + seprator + fileName + "." + extension);
675 tempStructFile.mkdirs();
676 return tempStructFile.toString();
680 * set whether quit should ask to save when just loaded this source
682 private void setShouldBeSaved()
684 if (protocol == null)
686 AlignFrame af = this.alignFrame;
689 AlignViewport avp = af.getViewport();
692 avp.setSavedUpToDate(!protocol.isDynamic(),
693 QuitHandler.Message.UNSAVED_ALIGNMENTS);