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.AlignmentAnnotation;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.HiddenColumns;
32 import jalview.datamodel.PDBEntry;
33 import jalview.datamodel.SequenceI;
34 import jalview.gui.AlignFrame;
35 import jalview.gui.AlignViewport;
36 import jalview.gui.Desktop;
37 import jalview.gui.Jalview2XML;
38 import jalview.gui.JvOptionPane;
39 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
40 import jalview.schemes.ColourSchemeI;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.util.MessageManager;
43 import jalview.ws.utils.UrlDownloadClient;
46 import java.io.IOException;
47 import java.util.StringTokenizer;
48 import java.util.Vector;
50 import javax.swing.SwingUtilities;
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;
76 * default constructor always raised errors in GUI dialog boxes
84 * construct a Fileloader that may raise errors non-interactively
87 * true if errors are to be raised as GUI dialog boxes
89 public FileLoader(boolean raiseGUI)
91 this.raiseGUI = raiseGUI;
94 public void LoadFile(AlignViewport viewport, String file,
95 DataSourceType protocol, FileFormatI format)
97 this.viewport = viewport;
98 LoadFile(file, protocol, format);
101 public void LoadFile(String file, DataSourceType protocol,
105 this.protocol = protocol;
106 this.format = format;
108 final Thread loader = new Thread(this);
110 SwingUtilities.invokeLater(new Runnable()
121 * Load a (file, protocol) source of unknown type
126 public void LoadFile(String file, DataSourceType protocol)
128 LoadFile(file, protocol, null);
132 * Load alignment from (file, protocol) and wait till loaded
136 * @return alignFrame constructed from file contents
138 public AlignFrame LoadFileWaitTillLoaded(String file,
139 DataSourceType sourceType)
141 return LoadFileWaitTillLoaded(file, sourceType, null);
145 * Load alignment from (file, protocol) of type format and wait till loaded
150 * @return alignFrame constructed from file contents
152 public AlignFrame LoadFileWaitTillLoaded(String file,
153 DataSourceType sourceType, FileFormatI format)
156 this.protocol = sourceType;
157 this.format = format;
158 return _LoadFileWaitTillLoaded();
162 * Load alignment from FileParse source of type format and wait till loaded
166 * @return alignFrame constructed from file contents
168 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
171 this.source = source;
173 file = source.getInFile();
174 protocol = source.getDataSourceType();
175 this.format = format;
176 return _LoadFileWaitTillLoaded();
180 * start thread and wait until finished, then return the alignFrame that's
181 * (hopefully) been read.
185 protected AlignFrame _LoadFileWaitTillLoaded()
187 Thread loader = new Thread(this);
190 while (loader.isAlive())
195 } catch (Exception ex)
203 public void LoadFileOntoAlignmentWaitTillLoaded(AlignViewport viewport,
204 String file, DataSourceType sourceType, FileFormatI format)
206 this.viewport = viewport;
208 this.protocol = sourceType;
209 this.format = format;
210 _LoadAlignmentFileWaitTillLoaded();
213 protected void _LoadAlignmentFileWaitTillLoaded()
215 Thread loader = new Thread(this);
218 while (loader.isAlive())
223 } catch (Exception ex)
229 public void updateRecentlyOpened()
231 Vector recent = new Vector();
232 if (protocol == DataSourceType.PASTE)
234 // do nothing if the file was pasted in as text... there is no filename to
239 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
241 // ignore files loaded from the system's temporary directory
244 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
247 String historyItems = jalview.bin.Cache.getProperty(type);
251 if (historyItems != null)
253 st = new StringTokenizer(historyItems, "\t");
255 while (st.hasMoreTokens())
257 recent.addElement(st.nextElement().toString().trim());
261 if (recent.contains(file))
266 StringBuffer newHistory = new StringBuffer(file);
267 for (int i = 0; i < recent.size() && i < 10; i++)
269 newHistory.append("\t");
270 newHistory.append(recent.elementAt(i));
273 Cache.setProperty(type, newHistory.toString());
275 if (protocol == DataSourceType.FILE)
277 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
284 String title = protocol == DataSourceType.PASTE
285 ? "Copied From Clipboard"
287 Runtime rt = Runtime.getRuntime();
290 if (Desktop.instance != null)
292 Desktop.instance.startLoading(file);
296 // just in case the caller didn't identify the file for us
299 format = new IdentifyFile().identify(source, false);
300 // identify stream and rewind rather than close
304 format = new IdentifyFile().identify(file, protocol);
311 Desktop.instance.stopLoading();
312 System.err.println("The input file \"" + file
313 + "\" has null or unidentifiable data content!");
314 if (!Jalview.isHeadlessMode())
316 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
317 MessageManager.getString("label.couldnt_read_data")
318 + " in " + file + "\n"
319 + AppletFormatAdapter.getSupportedFormats(),
320 MessageManager.getString("label.couldnt_read_data"),
321 JvOptionPane.WARNING_MESSAGE);
325 // TODO: cache any stream datasources as a temporary file (eg. PDBs
326 // retrieved via URL)
327 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
330 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
335 loadtime = -System.currentTimeMillis();
336 AlignmentI al = null;
338 if (FileFormat.Jalview.equals(format))
342 // Tell the user (developer?) that this is going to cause a problem
344 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
345 // We read the data anyway - it might make sense.
347 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
351 String error = AppletFormatAdapter.getSupportedFormats();
356 // read from the provided source
357 al = new FormatAdapter().readFromFile(source, format);
362 // open a new source and read from it
363 FormatAdapter fa = new FormatAdapter();
364 boolean downloadStructureFile = format.isStructureFile()
365 && protocol.equals(DataSourceType.URL);
366 if (downloadStructureFile)
368 String structExt = format.getExtensions().split(",")[0];
369 String urlLeafName = file.substring(
371 System.getProperty("file.separator")),
372 file.lastIndexOf("."));
373 String tempStructureFileStr = createNamedJvTempFile(
374 urlLeafName, structExt);
375 UrlDownloadClient.download(file, tempStructureFileStr);
376 al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
378 source = fa.getAlignFile();
382 al = fa.readFile(file, protocol, format);
383 source = fa.getAlignFile(); // keep reference for later if
387 } catch (java.io.IOException ex)
389 error = ex.getMessage();
392 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
394 // construct and register dataset sequences
395 for (SequenceI sq : al.getSequences())
397 while (sq.getDatasetSequence() != null)
399 sq = sq.getDatasetSequence();
401 if (sq.getAllPDBEntries() != null)
403 for (PDBEntry pdbe : sq.getAllPDBEntries())
405 // register PDB entries with desktop's structure selection
407 StructureSelectionManager
408 .getStructureSelectionManager(Desktop.instance)
409 .registerPDBEntry(pdbe);
414 FeatureSettingsModelI proxyColourScheme = source
415 .getFeatureColourScheme();
416 if (viewport != null)
418 if (proxyColourScheme != null)
420 viewport.applyFeaturesStyle(proxyColourScheme);
422 // append to existing alignment
423 viewport.addAlignment(al, title);
424 if (source instanceof HMMFile)
426 AlignmentI alignment = viewport.getAlignment();
427 SequenceI seq = alignment
428 .getSequenceAt(alignment.getAbsoluteHeight() - 1);
429 seq.setIsHMMConsensusSequence(true);
430 AlignmentAnnotation[] annots = viewport.getAlignment()
431 .getAlignmentAnnotation();
432 for (AlignmentAnnotation annot : annots)
434 if ("RF".equals(annot.label)
435 || annot.label.contains("Reference"))
437 seq.mapToReference(annot);
441 alignment.deleteSequence(alignment.getAbsoluteHeight() - 1);
442 alignment.insertSequenceAt(0, seq);
443 viewport.getAlignPanel().adjustAnnotationHeight();
444 viewport.updateSequenceIdColours();
450 // otherwise construct the alignFrame
452 if (source instanceof ComplexAlignFile)
454 HiddenColumns colSel = ((ComplexAlignFile) source)
456 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
457 .getHiddenSequences();
458 String colourSchemeName = ((ComplexAlignFile) source)
459 .getGlobalColourScheme();
460 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
461 .getDisplayedFeatures();
462 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
463 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
464 alignFrame.getViewport().setFeaturesDisplayed(fd);
465 alignFrame.getViewport().setShowSequenceFeatures(
466 ((ComplexAlignFile) source).isShowSeqFeatures());
467 ColourSchemeI cs = ColourSchemeMapper
468 .getJalviewColourScheme(colourSchemeName, al);
471 alignFrame.changeColour(cs);
476 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
477 AlignFrame.DEFAULT_HEIGHT);
478 if (source instanceof FeaturesSourceI)
480 alignFrame.getViewport().setShowSequenceFeatures(true);
483 // add metadata and update ui
484 if (!(protocol == DataSourceType.PASTE))
486 alignFrame.setFileName(file, format);
488 if (proxyColourScheme != null)
490 alignFrame.getViewport()
491 .applyFeaturesStyle(proxyColourScheme);
493 alignFrame.statusBar.setText(MessageManager.formatMessage(
494 "label.successfully_loaded_file", new String[]
499 // add the window to the GUI
500 // note - this actually should happen regardless of raiseGUI
501 // status in Jalview 3
502 // TODO: define 'virtual desktop' for benefit of headless scripts
503 // that perform queries to find the 'current working alignment'
504 Desktop.addInternalFrame(alignFrame, title,
505 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
510 alignFrame.setMaximum(jalview.bin.Cache
511 .getDefault("SHOW_FULLSCREEN", false));
512 } catch (java.beans.PropertyVetoException ex)
519 if (Desktop.instance != null)
521 Desktop.instance.stopLoading();
524 final String errorMessage = MessageManager.getString(
525 "label.couldnt_load_file") + " " + title + "\n" + error;
526 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
528 if (raiseGUI && Desktop.desktop != null)
530 javax.swing.SwingUtilities.invokeLater(new Runnable()
535 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
538 .getString("label.error_loading_file"),
539 JvOptionPane.WARNING_MESSAGE);
545 System.err.println(errorMessage);
550 updateRecentlyOpened();
552 } catch (Exception er)
554 System.err.println("Exception whilst opening file '" + file);
555 er.printStackTrace();
558 javax.swing.SwingUtilities.invokeLater(new Runnable()
563 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
564 MessageManager.formatMessage(
565 "label.problems_opening_file", new String[]
567 MessageManager.getString("label.file_open_error"),
568 JvOptionPane.WARNING_MESSAGE);
573 } catch (OutOfMemoryError er)
576 er.printStackTrace();
580 javax.swing.SwingUtilities.invokeLater(new Runnable()
585 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
586 MessageManager.formatMessage(
587 "warn.out_of_memory_loading_file", new String[]
589 MessageManager.getString("label.out_of_memory"),
590 JvOptionPane.WARNING_MESSAGE);
594 System.err.println("Out of memory loading file " + file + "!!");
597 loadtime += System.currentTimeMillis();
598 // TODO: Estimate percentage of memory used by a newly loaded alignment -
599 // warn if more memory will be needed to work with it
602 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
607 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
609 if (alignFrame != null)
611 AlignmentI al = alignFrame.getViewport().getAlignment();
613 System.out.println("Loaded '" + title + "' in "
614 + (loadtime / 1000.0) + "s, took an additional "
615 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
616 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
620 // report that we didn't load anything probably due to an out of memory
622 System.out.println("Failed to load '" + title + "' in "
623 + (loadtime / 1000.0) + "s, took an additional "
624 + (1.0 * memused / (1024.0 * 1024.0))
625 + " MB (alignment is null)");
628 // remove the visual delay indicator
629 if (Desktop.instance != null)
631 Desktop.instance.stopLoading();
637 * This method creates the file -
638 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
639 * file name and extension
642 * the name of the temp file to be created
644 * the extension of the temp file to be created
647 private static String createNamedJvTempFile(String fileName,
648 String extension) throws IOException
650 String seprator = System.getProperty("file.separator");
651 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
652 + seprator + System.currentTimeMillis();
653 File tempStructFile = new File(
654 jvTempDir + seprator + fileName + "." + extension);
655 tempStructFile.mkdirs();
656 return tempStructFile.toString();