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;
56 public class FileLoader implements Runnable
58 private static final String TAB = "\t";
62 DataSourceType protocol;
66 AlignmentFileReaderI source = null; // alternative specification of where data
71 AlignViewport viewport;
73 AlignFrame alignFrame;
79 boolean raiseGUI = true;
81 private File selectedFile;
84 * default constructor always raised errors in GUI dialog boxes
92 * construct a Fileloader that may raise errors non-interactively
95 * true if errors are to be raised as GUI dialog boxes
97 public FileLoader(boolean raiseGUI)
99 this.raiseGUI = raiseGUI;
102 public void LoadFile(AlignViewport viewport, Object file,
103 DataSourceType protocol, FileFormatI format)
105 this.viewport = viewport;
106 if (file instanceof File) {
107 this.selectedFile = (File) file;
108 file = selectedFile.getPath();
110 LoadFile(file.toString(), protocol, format);
113 public void LoadFile(String file, DataSourceType protocol,
117 this.protocol = protocol;
118 this.format = format;
120 final Thread loader = new Thread(this);
122 SwingUtilities.invokeLater(new Runnable()
133 * Load a (file, protocol) source of unknown type
138 public void LoadFile(String file, DataSourceType protocol)
140 LoadFile(file, protocol, null);
144 * Load alignment from (file, protocol) and wait till loaded
148 * @return alignFrame constructed from file contents
150 public AlignFrame LoadFileWaitTillLoaded(String file,
151 DataSourceType sourceType)
153 return LoadFileWaitTillLoaded(file, sourceType, null);
157 * Load alignment from (file, protocol) of type format and wait till loaded
162 * @return alignFrame constructed from file contents
164 public AlignFrame LoadFileWaitTillLoaded(String file,
165 DataSourceType sourceType, FileFormatI format)
168 this.protocol = sourceType;
169 this.format = format;
170 return _LoadFileWaitTillLoaded();
174 * Load alignment from (file, protocol) of type format and wait till loaded
179 * @return alignFrame constructed from file contents
181 public AlignFrame LoadFileWaitTillLoaded(File file,
182 DataSourceType sourceType, FileFormatI format)
184 this.selectedFile = file;
185 this.file = file.getPath();
186 this.protocol = sourceType;
187 this.format = format;
188 return _LoadFileWaitTillLoaded();
192 * Load alignment from FileParse source of type format and wait till loaded
196 * @return alignFrame constructed from file contents
198 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
201 this.source = source;
203 file = source.getInFile();
204 protocol = source.getDataSourceType();
205 this.format = format;
206 return _LoadFileWaitTillLoaded();
210 * runs the 'run' method (in this thread), then return the alignFrame that's
211 * (hopefully) been read
215 protected AlignFrame _LoadFileWaitTillLoaded()
222 public void LoadFileOntoAlignmentWaitTillLoaded(AlignViewport viewport,
223 String file, DataSourceType sourceType, FileFormatI format)
225 Vector<String> recent = new Vector<>();
226 if (protocol == DataSourceType.PASTE)
227 this.viewport = viewport;
229 this.protocol = sourceType;
230 this.format = format;
231 _LoadFileWaitTillLoaded();
236 * Updates (or creates) the tab-separated list of recently opened files held
237 * under the given property name by inserting the filePath at the front of the
238 * list. Duplicates are removed, and the list is limited to 11 entries. The
239 * method returns the updated value of the property.
244 public static String updateRecentlyOpened(String filePath,
245 DataSourceType sourceType)
247 if (sourceType != DataSourceType.FILE
248 && sourceType != DataSourceType.URL)
253 String propertyName = sourceType == DataSourceType.FILE ? "RECENT_FILE"
255 String historyItems = Cache.getProperty(propertyName);
257 && filePath.indexOf(System.getProperty("java.io.tmpdir")) > -1)
259 // ignore files loaded from the system's temporary directory
263 List<String> recent = new ArrayList<>();
265 if (historyItems != null)
267 StringTokenizer st = new StringTokenizer(historyItems, TAB);
269 while (st.hasMoreTokens())
271 String trimmed = st.nextToken().trim();
277 * if file was already in the list, it moves to the top
279 if (recent.contains(filePath))
281 recent.remove(filePath);
284 StringBuilder newHistory = new StringBuilder(filePath);
285 for (int i = 0; i < recent.size() && i < 10; i++)
287 newHistory.append(TAB);
288 newHistory.append(recent.get(i));
291 String newProperty = newHistory.toString();
292 Cache.setProperty(propertyName, newProperty);
300 String title = protocol == DataSourceType.PASTE
301 ? "Copied From Clipboard"
303 Runtime rt = Runtime.getRuntime();
306 if (Desktop.getInstance() != null)
308 Desktop.getInstance().startLoading(file);
312 // just in case the caller didn't identify the file for us
315 format = new IdentifyFile().identify(source, false);
316 // identify stream and rewind rather than close
318 else if (selectedFile != null) {
319 format = new IdentifyFile().identify(selectedFile, protocol);
323 format = new IdentifyFile().identify(file, protocol);
330 Desktop.getInstance().stopLoading();
331 System.err.println("The input file \"" + file
332 + "\" has null or unidentifiable data content!");
333 if (!Jalview.isHeadlessMode())
335 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
336 MessageManager.getString("label.couldnt_read_data")
337 + " in " + file + "\n"
338 + AppletFormatAdapter.getSupportedFormats(),
339 MessageManager.getString("label.couldnt_read_data"),
340 JvOptionPane.WARNING_MESSAGE);
344 // TODO: cache any stream datasources as a temporary file (eg. PDBs
345 // retrieved via URL)
346 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
349 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
354 loadtime = -System.currentTimeMillis();
355 AlignmentI al = null;
357 if (FileFormat.Jalview.equals(format))
361 // Tell the user (developer?) that this is going to cause a problem
363 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
364 // We read the data anyway - it might make sense.
366 // BH 2018 switch to File object here instead of filename
367 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(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,
403 source = fa.getAlignFile();
407 if (selectedFile == null) {
408 al = fa.readFile(file, protocol, format);
411 al = fa.readFile(selectedFile, 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.getInstance())
440 .registerPDBEntry(pdbe);
445 FeatureSettingsModelI proxyColourScheme = source
446 .getFeatureColourScheme();
447 if (viewport != null)
449 if (proxyColourScheme != null)
451 viewport.applyFeaturesStyle(proxyColourScheme);
453 // append to existing alignment
454 viewport.addAlignment(al, title);
455 if (source instanceof HMMFile)
457 AlignmentI alignment = viewport.getAlignment();
458 SequenceI seq = alignment
459 .getSequenceAt(alignment.getHeight() - 1);
460 if (seq.hasHMMProfile())
463 * fudge: move HMM consensus sequence from last to first
465 alignment.deleteSequence(alignment.getAbsoluteHeight() - 1);
466 alignment.insertSequenceAt(0, seq);
468 viewport.getAlignPanel().adjustAnnotationHeight();
469 viewport.updateSequenceIdColours();
474 // otherwise construct the alignFrame
476 if (source instanceof ComplexAlignFile)
478 HiddenColumns colSel = ((ComplexAlignFile) source)
480 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
481 .getHiddenSequences();
482 String colourSchemeName = ((ComplexAlignFile) source)
483 .getGlobalColourScheme();
484 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
485 .getDisplayedFeatures();
486 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
487 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
488 alignFrame.getViewport().setFeaturesDisplayed(fd);
489 alignFrame.getViewport().setShowSequenceFeatures(
490 ((ComplexAlignFile) source).isShowSeqFeatures());
491 ColourSchemeI cs = ColourSchemeMapper
492 .getJalviewColourScheme(colourSchemeName, al);
495 alignFrame.changeColour(cs);
500 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
501 AlignFrame.DEFAULT_HEIGHT);
502 if (source instanceof FeaturesSourceI)
504 alignFrame.getViewport().setShowSequenceFeatures(true);
507 // add metadata and update ui
508 if (!(protocol == DataSourceType.PASTE))
510 alignFrame.setFile(file, selectedFile, protocol, format);
512 if (proxyColourScheme != null)
514 alignFrame.getViewport()
515 .applyFeaturesStyle(proxyColourScheme);
517 alignFrame.setStatus(MessageManager.formatMessage(
518 "label.successfully_loaded_file", new String[]
523 // add the window to the GUI
524 // note - this actually should happen regardless of raiseGUI
525 // status in Jalview 3
526 // TODO: define 'virtual desktop' for benefit of headless scripts
527 // that perform queries to find the 'current working alignment'
529 Dimension dim = Platform.getDimIfEmbedded(alignFrame,
530 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
531 alignFrame.setSize(dim);
532 Desktop.addInternalFrame(alignFrame, title, dim.width,
538 alignFrame.setMaximum(jalview.bin.Cache
539 .getDefault("SHOW_FULLSCREEN", false));
540 } catch (java.beans.PropertyVetoException ex)
547 if (Desktop.getInstance() != null)
549 Desktop.getInstance().stopLoading();
552 final String errorMessage = MessageManager.getString(
553 "label.couldnt_load_file") + " " + title + "\n" + error;
554 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
556 if (raiseGUI && Desktop.getDesktopPane() != null)
558 javax.swing.SwingUtilities.invokeLater(new Runnable()
563 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
566 .getString("label.error_loading_file"),
567 JvOptionPane.WARNING_MESSAGE);
573 System.err.println(errorMessage);
578 updateRecentlyOpened(file, protocol);
580 if (protocol == DataSourceType.FILE && format != null)
582 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
585 } catch (Exception er)
587 System.err.println("Exception whilst opening file '" + file);
588 er.printStackTrace();
591 javax.swing.SwingUtilities.invokeLater(new Runnable()
596 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
597 MessageManager.formatMessage(
598 "label.problems_opening_file", new String[]
600 MessageManager.getString("label.file_open_error"),
601 JvOptionPane.WARNING_MESSAGE);
606 } catch (OutOfMemoryError er)
609 er.printStackTrace();
613 javax.swing.SwingUtilities.invokeLater(new Runnable()
618 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
619 MessageManager.formatMessage(
620 "warn.out_of_memory_loading_file", new String[]
622 MessageManager.getString("label.out_of_memory"),
623 JvOptionPane.WARNING_MESSAGE);
627 System.err.println("Out of memory loading file " + file + "!!");
630 loadtime += System.currentTimeMillis();
631 // TODO: Estimate percentage of memory used by a newly loaded alignment -
632 // warn if more memory will be needed to work with it
635 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
640 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
642 if (alignFrame != null)
644 AlignmentI al = alignFrame.getViewport().getAlignment();
646 System.out.println("Loaded '" + title + "' in "
647 + (loadtime / 1000.0) + "s, took an additional "
648 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
649 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
653 // report that we didn't load anything probably due to an out of memory
655 System.out.println("Failed to load '" + title + "' in "
656 + (loadtime / 1000.0) + "s, took an additional "
657 + (1.0 * memused / (1024.0 * 1024.0))
658 + " MB (alignment is null)");
661 // remove the visual delay indicator
662 if (Desktop.getInstance() != null)
664 Desktop.getInstance().stopLoading();
670 * This method creates the file -
671 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
672 * file name and extension
675 * the name of the temp file to be created
677 * the extension of the temp file to be created
680 private static String createNamedJvTempFile(String fileName,
681 String extension) throws IOException
683 String seprator = System.getProperty("file.separator");
684 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
685 + seprator + System.currentTimeMillis();
686 File tempStructFile = new File(
687 jvTempDir + seprator + fileName + "." + extension);
688 tempStructFile.mkdirs();
689 return tempStructFile.toString();