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.Jalview2XML;
37 import jalview.gui.JvOptionPane;
38 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
39 import jalview.schemes.ColourSchemeI;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
43 import java.util.StringTokenizer;
44 import java.util.Vector;
46 import javax.swing.SwingUtilities;
48 public class FileLoader implements Runnable
52 DataSourceType protocol;
56 AlignmentFileReaderI source = null; // alternative specification of where data
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(AlignmentFileReaderI 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.getName());
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.getSupportedFormats(),
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.getSupportedFormats();
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 // construct and register dataset sequences
340 for (SequenceI sq : al.getSequences())
342 while (sq.getDatasetSequence() != null)
344 sq = sq.getDatasetSequence();
346 if (sq.getAllPDBEntries() != null)
348 for (PDBEntry pdbe : sq.getAllPDBEntries())
350 // register PDB entries with desktop's structure selection
352 StructureSelectionManager.getStructureSelectionManager(
353 Desktop.instance).registerPDBEntry(pdbe);
358 FeatureSettingsModelI proxyColourScheme = source
359 .getFeatureColourScheme();
360 if (viewport != null)
362 if (proxyColourScheme != null)
364 viewport.applyFeaturesStyle(proxyColourScheme);
366 // append to existing alignment
367 viewport.addAlignment(al, title);
371 // otherwise construct the alignFrame
373 if (source instanceof ComplexAlignFile)
375 HiddenColumns colSel = ((ComplexAlignFile) source)
377 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
378 .getHiddenSequences();
379 String colourSchemeName = ((ComplexAlignFile) source)
380 .getGlobalColourScheme();
381 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
382 .getDisplayedFeatures();
383 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
384 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
385 alignFrame.getViewport().setFeaturesDisplayed(fd);
386 alignFrame.getViewport().setShowSequenceFeatures(
387 ((ComplexAlignFile) source).isShowSeqFeatures());
388 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
389 colourSchemeName, al);
392 alignFrame.changeColour(cs);
397 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
398 AlignFrame.DEFAULT_HEIGHT);
399 if (source instanceof FeaturesSourceI)
401 alignFrame.getViewport().setShowSequenceFeatures(true);
404 // add metadata and update ui
405 if (!(protocol == DataSourceType.PASTE))
407 alignFrame.setFileName(file, format);
409 if (proxyColourScheme != null)
411 alignFrame.getViewport()
412 .applyFeaturesStyle(proxyColourScheme);
414 alignFrame.statusBar.setText(MessageManager.formatMessage(
415 "label.successfully_loaded_file",
416 new String[] { title }));
420 // add the window to the GUI
421 // note - this actually should happen regardless of raiseGUI
422 // status in Jalview 3
423 // TODO: define 'virtual desktop' for benefit of headless scripts
424 // that perform queries to find the 'current working alignment'
425 Desktop.addInternalFrame(alignFrame, title,
426 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
431 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
432 "SHOW_FULLSCREEN", false));
433 } catch (java.beans.PropertyVetoException ex)
440 if (Desktop.instance != null)
442 Desktop.instance.stopLoading();
445 final String errorMessage = MessageManager
446 .getString("label.couldnt_load_file")
450 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
452 if (raiseGUI && Desktop.desktop != null)
454 javax.swing.SwingUtilities.invokeLater(new Runnable()
459 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
460 errorMessage, MessageManager
461 .getString("label.error_loading_file"),
462 JvOptionPane.WARNING_MESSAGE);
468 System.err.println(errorMessage);
473 updateRecentlyOpened();
475 } catch (Exception er)
477 System.err.println("Exception whilst opening file '" + file);
478 er.printStackTrace();
481 javax.swing.SwingUtilities.invokeLater(new Runnable()
486 JvOptionPane.showInternalMessageDialog(
487 Desktop.desktop, MessageManager.formatMessage(
488 "label.problems_opening_file",
489 new String[] { file }), MessageManager
490 .getString("label.file_open_error"),
491 JvOptionPane.WARNING_MESSAGE);
496 } catch (OutOfMemoryError er)
499 er.printStackTrace();
503 javax.swing.SwingUtilities.invokeLater(new Runnable()
508 JvOptionPane.showInternalMessageDialog(
509 Desktop.desktop, MessageManager.formatMessage(
510 "warn.out_of_memory_loading_file", new String[]
511 { file }), MessageManager
512 .getString("label.out_of_memory"),
513 JvOptionPane.WARNING_MESSAGE);
517 System.err.println("Out of memory loading file " + file + "!!");
520 loadtime += System.currentTimeMillis();
521 // TODO: Estimate percentage of memory used by a newly loaded alignment -
522 // warn if more memory will be needed to work with it
525 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
530 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
532 if (alignFrame != null)
534 AlignmentI al = alignFrame.getViewport().getAlignment();
536 System.out.println("Loaded '" + title + "' in "
537 + (loadtime / 1000.0) + "s, took an additional "
538 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
539 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
543 // report that we didn't load anything probably due to an out of memory
545 System.out.println("Failed to load '" + title + "' in "
546 + (loadtime / 1000.0) + "s, took an additional "
547 + (1.0 * memused / (1024.0 * 1024.0))
548 + " MB (alignment is null)");
551 // remove the visual delay indicator
552 if (Desktop.instance != null)
554 Desktop.instance.stopLoading();
562 * @see java.lang.Object#finalize()
565 protected void finalize() throws Throwable