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.ColumnSelection;
31 import jalview.datamodel.ContactMatrixTest;
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;
44 import java.util.StringTokenizer;
45 import java.util.Vector;
47 import javax.swing.SwingUtilities;
49 public class FileLoader implements Runnable
53 DataSourceType protocol;
57 AlignmentFileI source = null; // alternative specification of where data comes
61 AlignViewport viewport;
63 AlignFrame alignFrame;
69 boolean raiseGUI = true;
72 * default constructor always raised errors in GUI dialog boxes
80 * construct a Fileloader that may raise errors non-interactively
83 * true if errors are to be raised as GUI dialog boxes
85 public FileLoader(boolean raiseGUI)
87 this.raiseGUI = raiseGUI;
90 public void LoadFile(AlignViewport viewport, String file,
91 DataSourceType protocol, FileFormatI format)
93 this.viewport = viewport;
94 LoadFile(file, protocol, format);
97 public void LoadFile(String file, DataSourceType protocol,
101 this.protocol = protocol;
102 this.format = format;
104 final Thread loader = new Thread(this);
106 SwingUtilities.invokeLater(new Runnable()
117 * Load a (file, protocol) source of unknown type
122 public void LoadFile(String file, DataSourceType protocol)
124 LoadFile(file, protocol, null);
128 * Load alignment from (file, protocol) and wait till loaded
132 * @return alignFrame constructed from file contents
134 public AlignFrame LoadFileWaitTillLoaded(String file,
135 DataSourceType sourceType)
137 return LoadFileWaitTillLoaded(file, sourceType, null);
141 * Load alignment from (file, protocol) of type format and wait till loaded
146 * @return alignFrame constructed from file contents
148 public AlignFrame LoadFileWaitTillLoaded(String file,
149 DataSourceType sourceType, FileFormatI format)
152 this.protocol = sourceType;
153 this.format = format;
154 return _LoadFileWaitTillLoaded();
158 * Load alignment from FileParse source of type format and wait till loaded
162 * @return alignFrame constructed from file contents
164 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileI source,
167 this.source = source;
169 file = source.getInFile();
170 protocol = source.getDataSourceType();
171 this.format = format;
172 return _LoadFileWaitTillLoaded();
176 * start thread and wait until finished, then return the alignFrame that's
177 * (hopefully) been read.
181 protected AlignFrame _LoadFileWaitTillLoaded()
183 Thread loader = new Thread(this);
186 while (loader.isAlive())
191 } catch (Exception ex)
199 public void updateRecentlyOpened()
201 Vector recent = new Vector();
202 if (protocol == DataSourceType.PASTE)
204 // do nothing if the file was pasted in as text... there is no filename to
208 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
211 String historyItems = jalview.bin.Cache.getProperty(type);
215 if (historyItems != null)
217 st = new StringTokenizer(historyItems, "\t");
219 while (st.hasMoreTokens())
221 recent.addElement(st.nextElement().toString().trim());
225 if (recent.contains(file))
230 StringBuffer newHistory = new StringBuffer(file);
231 for (int i = 0; i < recent.size() && i < 10; i++)
233 newHistory.append("\t");
234 newHistory.append(recent.elementAt(i));
237 Cache.setProperty(type, newHistory.toString());
239 if (protocol == DataSourceType.FILE)
241 Cache.setProperty("DEFAULT_FILE_FORMAT", format.toString());
248 String title = protocol == DataSourceType.PASTE ? "Copied From Clipboard"
250 Runtime rt = Runtime.getRuntime();
253 if (Desktop.instance != null)
255 Desktop.instance.startLoading(file);
259 // just in case the caller didn't identify the file for us
262 format = new IdentifyFile().identify(source, false);
263 // identify stream and rewind rather than close
267 format = new IdentifyFile().identify(file, protocol);
274 Desktop.instance.stopLoading();
275 System.err.println("The input file \"" + file
276 + "\" has null or unidentifiable data content!");
277 if (!Jalview.isHeadlessMode())
279 JvOptionPane.showInternalMessageDialog(
281 MessageManager.getString("label.couldnt_read_data")
282 + " in " + file + "\n"
283 + AppletFormatAdapter.SUPPORTED_FORMATS,
284 MessageManager.getString("label.couldnt_read_data"),
285 JvOptionPane.WARNING_MESSAGE);
289 // TODO: cache any stream datasources as a temporary file (eg. PDBs
290 // retrieved via URL)
291 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
294 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
299 loadtime = -System.currentTimeMillis();
300 AlignmentI al = null;
302 if (FileFormat.Jalview.equals(format))
306 // Tell the user (developer?) that this is going to cause a problem
308 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
309 // We read the data anyway - it might make sense.
311 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
315 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
320 // read from the provided source
321 al = new FormatAdapter().readFromFile(source, format);
326 // open a new source and read from it
327 FormatAdapter fa = new FormatAdapter();
328 al = fa.readFile(file, protocol, format);
329 source = fa.getAlignFile(); // keep reference for later if
332 } catch (java.io.IOException ex)
334 error = ex.getMessage();
337 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
339 al.addContactList(new ContactMatrixTest(al.getWidth()));
341 // construct and register dataset sequences
342 for (SequenceI sq : al.getSequences())
344 while (sq.getDatasetSequence() != null)
346 sq = sq.getDatasetSequence();
348 if (sq.getAllPDBEntries() != null)
350 for (PDBEntry pdbe : sq.getAllPDBEntries())
352 // register PDB entries with desktop's structure selection
354 StructureSelectionManager.getStructureSelectionManager(
355 Desktop.instance).registerPDBEntry(pdbe);
360 FeatureSettingsModelI proxyColourScheme = source
361 .getFeatureColourScheme();
362 if (viewport != null)
364 if (proxyColourScheme != null)
366 viewport.applyFeaturesStyle(proxyColourScheme);
368 // append to existing alignment
369 viewport.addAlignment(al, title);
373 // otherwise construct the alignFrame
375 if (source instanceof ComplexAlignFile)
377 ColumnSelection colSel = ((ComplexAlignFile) source)
378 .getColumnSelection();
379 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
380 .getHiddenSequences();
381 String colourSchemeName = ((ComplexAlignFile) source)
382 .getGlobalColourScheme();
383 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
384 .getDisplayedFeatures();
385 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
386 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
387 alignFrame.getViewport().setFeaturesDisplayed(fd);
388 alignFrame.getViewport().setShowSequenceFeatures(
389 ((ComplexAlignFile) source).isShowSeqFeatures());
390 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
391 colourSchemeName, al);
394 alignFrame.changeColour(cs);
399 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
400 AlignFrame.DEFAULT_HEIGHT);
401 if (source instanceof FeaturesSourceI)
403 alignFrame.getViewport().setShowSequenceFeatures(true);
406 // add metadata and update ui
407 if (!(protocol == DataSourceType.PASTE))
409 alignFrame.setFileName(file, format);
411 if (proxyColourScheme != null)
413 alignFrame.getViewport()
414 .applyFeaturesStyle(proxyColourScheme);
416 alignFrame.statusBar.setText(MessageManager.formatMessage(
417 "label.successfully_loaded_file",
418 new String[] { title }));
422 // add the window to the GUI
423 // note - this actually should happen regardless of raiseGUI
424 // status in Jalview 3
425 // TODO: define 'virtual desktop' for benefit of headless scripts
426 // that perform queries to find the 'current working alignment'
427 Desktop.addInternalFrame(alignFrame, title,
428 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
433 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
434 "SHOW_FULLSCREEN", false));
435 } catch (java.beans.PropertyVetoException ex)
442 if (Desktop.instance != null)
444 Desktop.instance.stopLoading();
447 final String errorMessage = MessageManager
448 .getString("label.couldnt_load_file")
452 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
454 if (raiseGUI && Desktop.desktop != null)
456 javax.swing.SwingUtilities.invokeLater(new Runnable()
461 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
462 errorMessage, MessageManager
463 .getString("label.error_loading_file"),
464 JvOptionPane.WARNING_MESSAGE);
470 System.err.println(errorMessage);
475 updateRecentlyOpened();
477 } catch (Exception er)
479 System.err.println("Exception whilst opening file '" + file);
480 er.printStackTrace();
483 javax.swing.SwingUtilities.invokeLater(new Runnable()
488 JvOptionPane.showInternalMessageDialog(
489 Desktop.desktop, MessageManager.formatMessage(
490 "label.problems_opening_file",
491 new String[] { file }), MessageManager
492 .getString("label.file_open_error"),
493 JvOptionPane.WARNING_MESSAGE);
498 } catch (OutOfMemoryError er)
501 er.printStackTrace();
505 javax.swing.SwingUtilities.invokeLater(new Runnable()
510 JvOptionPane.showInternalMessageDialog(
511 Desktop.desktop, MessageManager.formatMessage(
512 "warn.out_of_memory_loading_file", new String[]
513 { file }), MessageManager
514 .getString("label.out_of_memory"),
515 JvOptionPane.WARNING_MESSAGE);
519 System.err.println("Out of memory loading file " + file + "!!");
522 loadtime += System.currentTimeMillis();
523 // TODO: Estimate percentage of memory used by a newly loaded alignment -
524 // warn if more memory will be needed to work with it
527 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
532 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
534 if (alignFrame != null)
536 AlignmentI al = alignFrame.getViewport().getAlignment();
538 System.out.println("Loaded '" + title + "' in "
539 + (loadtime / 1000.0) + "s, took an additional "
540 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
541 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
545 // report that we didn't load anything probably due to an out of memory
547 System.out.println("Failed to load '" + title + "' in "
548 + (loadtime / 1000.0) + "s, took an additional "
549 + (1.0 * memused / (1024.0 * 1024.0))
550 + " MB (alignment is null)");
553 // remove the visual delay indicator
554 if (Desktop.instance != null)
556 Desktop.instance.stopLoading();
564 * @see java.lang.Object#finalize()
567 protected void finalize() throws Throwable