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.
23 import java.awt.Dimension;
25 import java.io.IOException;
26 import java.util.StringTokenizer;
27 import java.util.Vector;
29 import javax.swing.SwingUtilities;
31 import jalview.api.ComplexAlignFile;
32 import jalview.api.FeatureSettingsModelI;
33 import jalview.api.FeaturesDisplayedI;
34 import jalview.api.FeaturesSourceI;
35 import jalview.bin.Cache;
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.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.util.Platform;
51 import jalview.ws.utils.UrlDownloadClient;
53 import java.util.ArrayList;
54 import java.util.List;
55 public class FileLoader implements Runnable
57 private static final String TAB = "\t";
60 DataSourceType protocol;
64 AlignmentFileReaderI source = null; // alternative specification of where data
69 AlignViewport viewport;
71 AlignFrame alignFrame;
77 boolean raiseGUI = true;
79 private File selectedFile;
82 * default constructor always raised errors in GUI dialog boxes
90 * construct a Fileloader that may raise errors non-interactively
93 * true if errors are to be raised as GUI dialog boxes
95 public FileLoader(boolean raiseGUI)
97 this.raiseGUI = raiseGUI;
100 public void LoadFile(AlignViewport viewport, Object file,
101 DataSourceType protocol, FileFormatI format)
103 this.viewport = viewport;
104 if (file instanceof File)
106 this.selectedFile = (File) file;
107 file = selectedFile.getPath();
109 LoadFile(file.toString(), protocol, format);
112 public void LoadFile(String file, DataSourceType protocol,
116 this.protocol = protocol;
117 this.format = format;
119 final Thread loader = new Thread(this);
121 SwingUtilities.invokeLater(new Runnable()
132 * Load a (file, protocol) source of unknown type
137 public void LoadFile(String file, DataSourceType protocol)
139 LoadFile(file, protocol, null);
143 * Load alignment from (file, protocol) and wait till loaded
147 * @return alignFrame constructed from file contents
149 public AlignFrame LoadFileWaitTillLoaded(String file,
150 DataSourceType sourceType)
152 return LoadFileWaitTillLoaded(file, sourceType, null);
156 * Load alignment from (file, protocol) of type format and wait till loaded
161 * @return alignFrame constructed from file contents
163 public AlignFrame LoadFileWaitTillLoaded(String file,
164 DataSourceType sourceType, FileFormatI format)
167 this.protocol = sourceType;
168 this.format = format;
169 return _LoadFileWaitTillLoaded();
173 * Load alignment from (file, protocol) of type format and wait till loaded
178 * @return alignFrame constructed from file contents
180 public AlignFrame LoadFileWaitTillLoaded(File file,
181 DataSourceType sourceType, FileFormatI format)
183 this.selectedFile = file;
184 this.file = file.getPath();
185 this.protocol = sourceType;
186 this.format = format;
187 return _LoadFileWaitTillLoaded();
191 * Load alignment from FileParse source of type format and wait till loaded
195 * @return alignFrame constructed from file contents
197 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
200 this.source = source;
202 file = source.getInFile();
203 protocol = source.getDataSourceType();
204 this.format = format;
205 return _LoadFileWaitTillLoaded();
209 * runs the 'run' method (in this thread), then return the alignFrame that's
210 * (hopefully) been read
214 protected AlignFrame _LoadFileWaitTillLoaded()
221 public void LoadFileOntoAlignmentWaitTillLoaded(AlignViewport viewport,
222 String file, DataSourceType sourceType, FileFormatI format)
224 Vector<String> recent = new Vector<>();
225 if (protocol == DataSourceType.PASTE)
226 this.viewport = viewport;
228 this.protocol = sourceType;
229 this.format = format;
230 _LoadFileWaitTillLoaded();
235 * Updates (or creates) the tab-separated list of recently opened files held
236 * under the given property name by inserting the filePath at the front of the
237 * list. Duplicates are removed, and the list is limited to 11 entries. The
238 * method returns the updated value of the property.
243 public static String updateRecentlyOpened(String filePath,
244 DataSourceType sourceType)
246 if (sourceType != DataSourceType.FILE
247 && sourceType != DataSourceType.URL)
251 String propertyName = sourceType == DataSourceType.FILE ? "RECENT_FILE"
253 String historyItems = Cache.getProperty(propertyName);
255 && filePath.indexOf(System.getProperty("java.io.tmpdir")) > -1)
257 // ignore files loaded from the system's temporary directory
261 List<String> recent = new ArrayList<>();
263 if (historyItems != null)
265 StringTokenizer st = new StringTokenizer(historyItems, TAB);
267 while (st.hasMoreTokens())
269 String trimmed = st.nextToken().trim();
275 * if file was already in the list, it moves to the top
277 if (recent.contains(filePath))
279 recent.remove(filePath);
282 StringBuilder newHistory = new StringBuilder(filePath);
283 for (int i = 0; i < recent.size() && i < 10; i++)
285 newHistory.append(TAB);
286 newHistory.append(recent.get(i));
289 String newProperty = newHistory.toString();
290 Cache.setProperty(propertyName, newProperty);
298 String title = protocol == DataSourceType.PASTE
299 ? "Copied From Clipboard"
301 Runtime rt = Runtime.getRuntime();
304 if (Desktop.getInstance() != null)
306 Desktop.getInstance().startLoading(file);
310 // just in case the caller didn't identify the file for us
313 format = new IdentifyFile().identify(source, false);
314 // identify stream and rewind rather than close
316 else if (selectedFile != null)
318 format = new IdentifyFile().identify(selectedFile, protocol);
322 format = new IdentifyFile().identify(file, protocol);
329 Desktop.getInstance().stopLoading();
330 System.err.println("The input file \"" + file
331 + "\" has null or unidentifiable data content!");
332 if (!Jalview.isHeadlessMode())
334 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
335 MessageManager.getString("label.couldnt_read_data")
336 + " in " + file + "\n"
337 + AppletFormatAdapter.getSupportedFormats(),
338 MessageManager.getString("label.couldnt_read_data"),
339 JvOptionPane.WARNING_MESSAGE);
343 // TODO: cache any stream datasources as a temporary file (eg. PDBs
344 // retrieved via URL)
345 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
348 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
353 loadtime = -System.currentTimeMillis();
354 AlignmentI al = null;
356 if (FileFormat.Jalview.equals(format))
360 // Tell the user (developer?) that this is going to cause a problem
362 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
363 // We read the data anyway - it might make sense.
365 // BH 2018 switch to File object here instead of filename
366 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
367 selectedFile == null ? file : selectedFile);
371 String error = AppletFormatAdapter.getSupportedFormats();
376 // read from the provided source
377 al = new FormatAdapter().readFromFile(source, format);
382 // open a new source and read from it
383 FormatAdapter fa = new FormatAdapter();
384 boolean downloadStructureFile = format.isStructureFile()
385 && protocol.equals(DataSourceType.URL);
386 if (downloadStructureFile)
388 String structExt = format.getExtensions().split(",")[0];
389 String urlLeafName = file.substring(
391 System.getProperty("file.separator")),
392 file.lastIndexOf("."));
393 String tempStructureFileStr = createNamedJvTempFile(
394 urlLeafName, structExt);
396 // BH - switching to File object here so as to hold
397 // ._bytes array directly
398 File tempFile = new File(tempStructureFileStr);
399 UrlDownloadClient.download(file, tempFile);
401 al = fa.readFile(tempFile, DataSourceType.FILE, format);
402 source = fa.getAlignFile();
406 if (selectedFile == null)
408 al = fa.readFile(file, protocol, format);
413 al = fa.readFile(selectedFile, protocol, format);
415 source = fa.getAlignFile(); // keep reference for later if
420 } catch (java.io.IOException ex)
422 error = ex.getMessage();
425 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
427 // construct and register dataset sequences
428 for (SequenceI sq : al.getSequences())
430 while (sq.getDatasetSequence() != null)
432 sq = sq.getDatasetSequence();
434 if (sq.getAllPDBEntries() != null)
436 for (PDBEntry pdbe : sq.getAllPDBEntries())
438 // register PDB entries with desktop's structure selection
440 StructureSelectionManager
441 .getStructureSelectionManager(Desktop.getInstance())
442 .registerPDBEntry(pdbe);
447 FeatureSettingsModelI proxyColourScheme = source
448 .getFeatureColourScheme();
449 if (viewport != null)
451 // TODO: test if this needs to be done after addAlignment ? (like in 2.11.2)
452 if (proxyColourScheme != null)
454 viewport.applyFeaturesStyle(proxyColourScheme);
456 // append to existing alignment
457 viewport.addAlignment(al, title);
458 if (source instanceof HMMFile)
460 AlignmentI alignment = viewport.getAlignment();
461 SequenceI seq = alignment
462 .getSequenceAt(alignment.getHeight() - 1);
463 if (seq.hasHMMProfile())
466 * fudge: move HMM consensus sequence from last to first
468 alignment.deleteSequence(alignment.getAbsoluteHeight() - 1);
469 alignment.insertSequenceAt(0, seq);
471 viewport.getAlignPanel().adjustAnnotationHeight();
472 viewport.updateSequenceIdColours();
477 // otherwise construct the alignFrame
479 if (source instanceof ComplexAlignFile)
481 HiddenColumns colSel = ((ComplexAlignFile) source)
483 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
484 .getHiddenSequences();
485 String colourSchemeName = ((ComplexAlignFile) source)
486 .getGlobalColourScheme();
487 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
488 .getDisplayedFeatures();
489 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
490 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
491 alignFrame.getViewport().setFeaturesDisplayed(fd);
492 alignFrame.getViewport().setShowSequenceFeatures(
493 ((ComplexAlignFile) source).isShowSeqFeatures());
494 ColourSchemeI cs = ColourSchemeMapper
495 .getJalviewColourScheme(colourSchemeName, al);
498 alignFrame.changeColour(cs);
503 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
504 AlignFrame.DEFAULT_HEIGHT);
505 if (source instanceof FeaturesSourceI)
507 alignFrame.getViewport().setShowSequenceFeatures(true);
510 // add metadata and update ui
511 if (!(protocol == DataSourceType.PASTE))
513 alignFrame.setFile(file, selectedFile, protocol, format);
515 if (proxyColourScheme != null)
517 alignFrame.getViewport()
518 .applyFeaturesStyle(proxyColourScheme);
520 alignFrame.setStatus(MessageManager.formatMessage(
521 "label.successfully_loaded_file", new String[]
526 // add the window to the GUI
527 // note - this actually should happen regardless of raiseGUI
528 // status in Jalview 3
529 // TODO: define 'virtual desktop' for benefit of headless scripts
530 // that perform queries to find the 'current working alignment'
532 Dimension dim = Platform.getDimIfEmbedded(alignFrame,
533 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
534 alignFrame.setSize(dim);
535 Desktop.addInternalFrame(alignFrame, title, dim.width,
541 alignFrame.setMaximum(
542 Cache.getDefault("SHOW_FULLSCREEN", false));
543 } catch (java.beans.PropertyVetoException ex)
550 if (Desktop.getInstance() != null)
552 Desktop.getInstance().stopLoading();
555 final String errorMessage = MessageManager.getString(
556 "label.couldnt_load_file") + " " + title + "\n" + error;
557 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
559 if (raiseGUI && Desktop.getDesktopPane() != null)
561 javax.swing.SwingUtilities.invokeLater(new Runnable()
566 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
569 .getString("label.error_loading_file"),
570 JvOptionPane.WARNING_MESSAGE);
576 System.err.println(errorMessage);
581 updateRecentlyOpened(file, protocol);
583 if (protocol == DataSourceType.FILE && format != null)
585 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
588 } catch (Exception er)
590 System.err.println("Exception whilst opening file '" + file);
591 er.printStackTrace();
594 javax.swing.SwingUtilities.invokeLater(new Runnable()
599 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
600 MessageManager.formatMessage(
601 "label.problems_opening_file", new String[]
603 MessageManager.getString("label.file_open_error"),
604 JvOptionPane.WARNING_MESSAGE);
609 } catch (OutOfMemoryError er)
612 er.printStackTrace();
616 javax.swing.SwingUtilities.invokeLater(new Runnable()
621 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
622 MessageManager.formatMessage(
623 "warn.out_of_memory_loading_file", new String[]
625 MessageManager.getString("label.out_of_memory"),
626 JvOptionPane.WARNING_MESSAGE);
630 System.err.println("Out of memory loading file " + file + "!!");
633 loadtime += System.currentTimeMillis();
634 // TODO: Estimate percentage of memory used by a newly loaded alignment -
635 // warn if more memory will be needed to work with it
638 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
643 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
645 if (alignFrame != null)
647 AlignmentI al = alignFrame.getViewport().getAlignment();
649 System.out.println("Loaded '" + title + "' in "
650 + (loadtime / 1000.0) + "s, took an additional "
651 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
652 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
656 // report that we didn't load anything probably due to an out of memory
658 System.out.println("Failed to load '" + title + "' in "
659 + (loadtime / 1000.0) + "s, took an additional "
660 + (1.0 * memused / (1024.0 * 1024.0))
661 + " MB (alignment is null)");
664 // remove the visual delay indicator
665 if (Desktop.getInstance() != null)
667 Desktop.getInstance().stopLoading();
673 * This method creates the file -
674 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
675 * file name and extension
678 * the name of the temp file to be created
680 * the extension of the temp file to be created
683 private static String createNamedJvTempFile(String fileName,
684 String extension) throws IOException
686 String seprator = System.getProperty("file.separator");
687 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
688 + seprator + System.currentTimeMillis();
689 File tempStructFile = new File(
690 jvTempDir + seprator + fileName + "." + extension);
691 tempStructFile.mkdirs();
692 return tempStructFile.toString();