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 jalview.api.ComplexAlignFile;
24 import jalview.api.FeatureSettingsModelI;
25 import jalview.api.FeaturesDisplayedI;
26 import jalview.api.FeaturesSourceI;
27 import jalview.bin.Cache;
28 import jalview.bin.Jalview;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.AlignViewport;
35 import jalview.gui.Desktop;
36 import jalview.gui.JvOptionPane;
37 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
38 import jalview.project.Jalview2XML;
39 import jalview.schemes.ColourSchemeI;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.ws.utils.UrlDownloadClient;
45 import java.io.IOException;
46 import java.util.ArrayList;
47 import java.util.List;
48 import java.util.StringTokenizer;
50 import javax.swing.SwingUtilities;
52 public class FileLoader implements Runnable
54 private static final String TAB = "\t";
58 DataSourceType protocol;
62 AlignmentFileReaderI source = null; // alternative specification of where data
67 AlignViewport viewport;
69 AlignFrame alignFrame;
75 boolean raiseGUI = true;
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, String file,
97 DataSourceType protocol, FileFormatI format)
99 this.viewport = viewport;
100 LoadFile(file, protocol, format);
103 public void LoadFile(String file, DataSourceType protocol,
107 this.protocol = protocol;
108 this.format = format;
110 final Thread loader = new Thread(this);
112 SwingUtilities.invokeLater(new Runnable()
123 * Load a (file, protocol) source of unknown type
128 public void LoadFile(String file, DataSourceType protocol)
130 LoadFile(file, protocol, null);
134 * Load alignment from (file, protocol) and wait till loaded
138 * @return alignFrame constructed from file contents
140 public AlignFrame LoadFileWaitTillLoaded(String file,
141 DataSourceType sourceType)
143 return LoadFileWaitTillLoaded(file, sourceType, null);
147 * Load alignment from (file, protocol) of type format and wait till loaded
152 * @return alignFrame constructed from file contents
154 public AlignFrame LoadFileWaitTillLoaded(String file,
155 DataSourceType sourceType, FileFormatI format)
158 this.protocol = sourceType;
159 this.format = format;
160 return _LoadFileWaitTillLoaded();
164 * Load alignment from FileParse source of type format and wait till loaded
168 * @return alignFrame constructed from file contents
170 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
173 this.source = source;
175 file = source.getInFile();
176 protocol = source.getDataSourceType();
177 this.format = format;
178 return _LoadFileWaitTillLoaded();
182 * start thread and wait until finished, then return the alignFrame that's
183 * (hopefully) been read.
187 protected AlignFrame _LoadFileWaitTillLoaded()
189 Thread loader = new Thread(this);
192 while (loader.isAlive())
197 } catch (Exception ex)
200 "Exception caught while waiting for FileLoader thread");
201 ex.printStackTrace();
208 public void LoadFileOntoAlignmentWaitTillLoaded(AlignViewport viewport,
209 String file, DataSourceType sourceType, FileFormatI format)
211 this.viewport = viewport;
213 this.protocol = sourceType;
214 this.format = format;
215 _LoadAlignmentFileWaitTillLoaded();
218 protected void _LoadAlignmentFileWaitTillLoaded()
220 Thread loader = new Thread(this);
223 while (loader.isAlive())
228 } catch (Exception ex)
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)
252 String propertyName = sourceType == DataSourceType.FILE ? "RECENT_FILE"
254 String historyItems = Cache.getProperty(propertyName);
256 && filePath.indexOf(System.getProperty("java.io.tmpdir")) > -1)
258 // ignore files loaded from the system's temporary directory
262 List<String> recent = new ArrayList<>();
264 if (historyItems != null)
266 StringTokenizer st = new StringTokenizer(historyItems, TAB);
268 while (st.hasMoreTokens())
270 String trimmed = st.nextToken().trim();
271 if (!recent.contains(trimmed))
279 * if file was already in the list, it moves to the top
281 if (recent.contains(filePath))
283 recent.remove(filePath);
286 StringBuilder newHistory = new StringBuilder(filePath);
287 for (int i = 0; i < recent.size() && i < 10; i++)
289 newHistory.append(TAB);
290 newHistory.append(recent.get(i));
293 String newProperty = newHistory.toString();
294 Cache.setProperty(propertyName, newProperty);
302 String title = protocol == DataSourceType.PASTE
303 ? "Copied From Clipboard"
305 Runtime rt = Runtime.getRuntime();
308 if (Desktop.instance != null)
310 Desktop.instance.startLoading(file);
314 // just in case the caller didn't identify the file for us
317 format = new IdentifyFile().identify(source, false);
318 // identify stream and rewind rather than close
322 format = new IdentifyFile().identify(file, protocol);
329 Desktop.instance.stopLoading();
330 System.err.println("The input file \"" + file
331 + "\" has null or unidentifiable data content!");
332 if (!Jalview.isHeadlessMode())
334 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
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.desktop != null && Desktop.desktop.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 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
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);
393 UrlDownloadClient.download(file, tempStructureFileStr);
394 al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
396 source = fa.getAlignFile();
400 al = fa.readFile(file, protocol, format);
401 source = fa.getAlignFile(); // keep reference for later if
405 } catch (java.io.IOException ex)
407 error = ex.getMessage();
410 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
412 // construct and register dataset sequences
413 for (SequenceI sq : al.getSequences())
415 while (sq.getDatasetSequence() != null)
417 sq = sq.getDatasetSequence();
419 if (sq.getAllPDBEntries() != null)
421 for (PDBEntry pdbe : sq.getAllPDBEntries())
423 // register PDB entries with desktop's structure selection
425 StructureSelectionManager
426 .getStructureSelectionManager(Desktop.instance)
427 .registerPDBEntry(pdbe);
432 FeatureSettingsModelI proxyColourScheme = source
433 .getFeatureColourScheme();
434 if (viewport != null)
436 if (proxyColourScheme != null)
438 viewport.applyFeaturesStyle(proxyColourScheme);
440 // append to existing alignment
441 viewport.addAlignment(al, title);
442 if (source instanceof HMMFile)
444 // TODO: absorb into viewport.addAlignment above ?
445 AlignmentI alignment = viewport.getAlignment();
446 SequenceI seq = alignment
447 .getSequenceAt(alignment.getHeight() - 1);
448 if (seq.hasHMMProfile())
451 * fudge: move HMM consensus sequence from last to first
453 alignment.deleteSequence(alignment.getAbsoluteHeight() - 1);
454 alignment.insertSequenceAt(0, seq);
456 viewport.getAlignPanel().adjustAnnotationHeight();
457 viewport.updateSequenceIdColours();
458 // update HMM colour optionsÂ
459 if (alignFrame != null)
461 alignFrame.buildColourMenu();
467 // otherwise construct the alignFrame
469 if (source instanceof ComplexAlignFile)
471 HiddenColumns colSel = ((ComplexAlignFile) source)
473 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
474 .getHiddenSequences();
475 String colourSchemeName = ((ComplexAlignFile) source)
476 .getGlobalColourScheme();
477 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
478 .getDisplayedFeatures();
479 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
480 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
481 alignFrame.getViewport().setFeaturesDisplayed(fd);
482 alignFrame.getViewport().setShowSequenceFeatures(
483 ((ComplexAlignFile) source).isShowSeqFeatures());
484 ColourSchemeI cs = ColourSchemeMapper
485 .getJalviewColourScheme(colourSchemeName, al);
488 alignFrame.changeColour(cs);
493 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
494 AlignFrame.DEFAULT_HEIGHT);
495 if (source instanceof FeaturesSourceI)
497 alignFrame.getViewport().setShowSequenceFeatures(true);
500 // add metadata and update ui
501 if (!(protocol == DataSourceType.PASTE))
503 alignFrame.setFileName(file, format);
505 if (proxyColourScheme != null)
507 alignFrame.getViewport()
508 .applyFeaturesStyle(proxyColourScheme);
510 alignFrame.setStatus(MessageManager.formatMessage(
511 "label.successfully_loaded_file", new String[]
516 // add the window to the GUI
517 // note - this actually should happen regardless of raiseGUI
518 // status in Jalview 3
519 // TODO: define 'virtual desktop' for benefit of headless scripts
520 // that perform queries to find the 'current working alignment'
521 Desktop.addInternalFrame(alignFrame, title,
522 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
527 alignFrame.setMaximum(jalview.bin.Cache
528 .getDefault("SHOW_FULLSCREEN", false));
529 } catch (java.beans.PropertyVetoException ex)
536 if (Desktop.instance != null)
538 Desktop.instance.stopLoading();
541 final String errorMessage = MessageManager.getString(
542 "label.couldnt_load_file") + " " + title + "\n" + error;
543 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
545 if (raiseGUI && Desktop.desktop != null)
547 javax.swing.SwingUtilities.invokeLater(new Runnable()
552 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
555 .getString("label.error_loading_file"),
556 JvOptionPane.WARNING_MESSAGE);
562 System.err.println(errorMessage);
567 updateRecentlyOpened(file, protocol);
569 if (protocol == DataSourceType.FILE && format != null)
571 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
574 } catch (Exception er)
576 System.err.println("Exception whilst opening file '" + file);
577 er.printStackTrace();
580 javax.swing.SwingUtilities.invokeLater(new Runnable()
585 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
586 MessageManager.formatMessage(
587 "label.problems_opening_file", new String[]
589 MessageManager.getString("label.file_open_error"),
590 JvOptionPane.WARNING_MESSAGE);
595 } catch (OutOfMemoryError er)
598 er.printStackTrace();
602 javax.swing.SwingUtilities.invokeLater(new Runnable()
607 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
608 MessageManager.formatMessage(
609 "warn.out_of_memory_loading_file", new String[]
611 MessageManager.getString("label.out_of_memory"),
612 JvOptionPane.WARNING_MESSAGE);
616 System.err.println("Out of memory loading file " + file + "!!");
619 loadtime += System.currentTimeMillis();
620 // TODO: Estimate percentage of memory used by a newly loaded alignment -
621 // warn if more memory will be needed to work with it
624 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
629 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
631 if (alignFrame != null)
633 AlignmentI al = alignFrame.getViewport().getAlignment();
635 System.out.println("Loaded '" + title + "' in "
636 + (loadtime / 1000.0) + "s, took an additional "
637 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
638 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
642 // report that we didn't load anything probably due to an out of memory
644 System.out.println("Failed to load '" + title + "' in "
645 + (loadtime / 1000.0) + "s, took an additional "
646 + (1.0 * memused / (1024.0 * 1024.0))
647 + " MB (alignment is null)");
650 // remove the visual delay indicator
651 if (Desktop.instance != null)
653 Desktop.instance.stopLoading();
659 * This method creates the file -
660 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
661 * file name and extension
664 * the name of the temp file to be created
666 * the extension of the temp file to be created
669 private static String createNamedJvTempFile(String fileName,
670 String extension) throws IOException
672 String seprator = System.getProperty("file.separator");
673 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
674 + seprator + System.currentTimeMillis();
675 File tempStructFile = new File(
676 jvTempDir + seprator + fileName + "." + extension);
677 tempStructFile.mkdirs();
678 return tempStructFile.toString();