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.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.gui.JvSwingUtils;
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 AlignmentFileReaderI source = null; // alternative specification of where data
62 AlignViewport viewport;
64 AlignFrame alignFrame;
70 boolean raiseGUI = true;
73 * default constructor always raised errors in GUI dialog boxes
81 * construct a Fileloader that may raise errors non-interactively
84 * true if errors are to be raised as GUI dialog boxes
86 public FileLoader(boolean raiseGUI)
88 this.raiseGUI = raiseGUI;
91 public void LoadFile(AlignViewport viewport, String file,
92 DataSourceType protocol, FileFormatI format)
94 this.viewport = viewport;
96 this.protocol = protocol;
99 final Thread loader = new Thread(this);
101 SwingUtilities.invokeLater(new Runnable()
112 * Load alignment from (file, protocol) and wait till loaded
116 * @return alignFrame constructed from file contents
118 public AlignFrame LoadFileWaitTillLoaded(String file,
119 DataSourceType sourceType)
121 return LoadFileWaitTillLoaded(file, sourceType, null);
125 * Load alignment from (file, protocol) of type format and wait till loaded
130 * @return alignFrame constructed from file contents
132 public AlignFrame LoadFileWaitTillLoaded(String file,
133 DataSourceType sourceType, FileFormatI format)
136 this.protocol = sourceType;
137 this.format = format;
138 return _LoadFileWaitTillLoaded();
142 * start thread and wait until finished, then return the alignFrame that's
143 * (hopefully) been read.
147 protected AlignFrame _LoadFileWaitTillLoaded()
149 Thread loader = new Thread(this);
152 while (loader.isAlive())
157 } catch (Exception ex)
165 public void updateRecentlyOpened()
167 Vector recent = new Vector();
168 if (protocol == DataSourceType.PASTE)
170 // do nothing if the file was pasted in as text... there is no filename to
174 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
177 String historyItems = jalview.bin.Cache.getProperty(type);
181 if (historyItems != null)
183 st = new StringTokenizer(historyItems, "\t");
185 while (st.hasMoreTokens())
187 recent.addElement(st.nextElement().toString().trim());
191 if (recent.contains(file))
196 StringBuffer newHistory = new StringBuffer(file);
197 for (int i = 0; i < recent.size() && i < 10; i++)
199 newHistory.append("\t");
200 newHistory.append(recent.elementAt(i));
203 Cache.setProperty(type, newHistory.toString());
205 if (protocol == DataSourceType.FILE)
207 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
214 final String title = protocol == DataSourceType.PASTE ? "Copied From Clipboard"
216 Runtime rt = Runtime.getRuntime();
219 if (Desktop.instance != null)
221 Desktop.instance.startLoading(file);
225 // just in case the caller didn't identify the file for us
228 format = new IdentifyFile().identify(source, false);
229 // identify stream and rewind rather than close
233 format = new IdentifyFile().identify(file, protocol);
240 Desktop.instance.stopLoading();
241 System.err.println("The input file \"" + file
242 + "\" has null or unidentifiable data content!");
243 if (!Jalview.isHeadlessMode())
245 JvOptionPane.showInternalMessageDialog(
247 MessageManager.getString("label.couldnt_read_data")
248 + " in " + file + "\n"
249 + AppletFormatAdapter.getSupportedFormats(),
250 MessageManager.getString("label.couldnt_read_data"),
251 JvOptionPane.WARNING_MESSAGE);
255 // TODO: cache any stream datasources as a temporary file (eg. PDBs
256 // retrieved via URL)
257 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
260 // free memory before loading file
261 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory());
263 loadtime = -System.currentTimeMillis();
264 AlignmentI al = null;
266 if (FileFormat.Jalview.equals(format))
270 // Tell the user (developer?) that this is going to cause a problem
272 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
273 // We read the data anyway - it might make sense.
275 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
279 String error = AppletFormatAdapter.getSupportedFormats();
284 // read from the provided source
285 al = new FormatAdapter().readFromFile(source, format);
290 // open a new source and read from it
291 FormatAdapter fa = new FormatAdapter();
292 al = fa.readFile(file, protocol, format);
293 source = fa.getAlignFile(); // keep reference for later if
296 } catch (java.io.IOException ex)
298 error = ex.getMessage();
301 if (!format.hasSequenceData())
303 javax.swing.SwingUtilities.invokeLater(new Runnable()
308 String msg = MessageManager.formatMessage("label.successfully_loaded_file_type", format.getName(), title);
309 msg = JvSwingUtils.wrapTooltip(true, msg);
310 JvOptionPane.showInternalMessageDialog(Desktop.desktop, msg,
311 "", JvOptionPane.INFORMATION_MESSAGE);
315 else if ((al != null) && (al.getHeight() > 0)
316 && al.hasValidSequence())
318 // construct and register dataset sequences
319 for (SequenceI sq : al.getSequences())
321 while (sq.getDatasetSequence() != null)
323 sq = sq.getDatasetSequence();
325 if (sq.getAllPDBEntries() != null)
327 for (PDBEntry pdbe : sq.getAllPDBEntries())
329 StructureSelectionManager.getStructureSelectionManager(
330 Desktop.instance).registerPDBEntry(pdbe);
335 FeatureSettingsModelI proxyColourScheme = source
336 .getFeatureColourScheme();
337 if (viewport != null)
339 if (proxyColourScheme != null)
341 viewport.applyFeaturesStyle(proxyColourScheme);
343 // append to existing alignment
344 viewport.addAlignment(al, title);
348 addAlignFrame(al, title);
353 if (Desktop.instance != null)
355 Desktop.instance.stopLoading();
358 final String errorMessage = MessageManager
359 .getString("label.couldnt_load_file")
363 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
365 if (format.hasSequenceData() && raiseGUI
366 && Desktop.desktop != null)
368 javax.swing.SwingUtilities.invokeLater(new Runnable()
373 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
374 errorMessage, MessageManager
375 .getString("label.error_loading_file"),
376 JvOptionPane.WARNING_MESSAGE);
382 System.err.println(errorMessage);
387 updateRecentlyOpened();
389 } catch (Exception er)
391 System.err.println("Exception whilst opening file '" + file);
392 er.printStackTrace();
395 javax.swing.SwingUtilities.invokeLater(new Runnable()
400 JvOptionPane.showInternalMessageDialog(
401 Desktop.desktop, MessageManager.formatMessage(
402 "label.problems_opening_file",
403 new String[] { file }), MessageManager
404 .getString("label.file_open_error"),
405 JvOptionPane.WARNING_MESSAGE);
410 } catch (OutOfMemoryError er)
413 er.printStackTrace();
417 javax.swing.SwingUtilities.invokeLater(new Runnable()
422 JvOptionPane.showInternalMessageDialog(
423 Desktop.desktop, MessageManager.formatMessage(
424 "warn.out_of_memory_loading_file", new String[]
425 { file }), MessageManager
426 .getString("label.out_of_memory"),
427 JvOptionPane.WARNING_MESSAGE);
431 System.err.println("Out of memory loading file " + file + "!!");
434 loadtime += System.currentTimeMillis();
435 // TODO: Estimate percentage of memory used by a newly loaded alignment -
436 // warn if more memory will be needed to work with it
439 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
444 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
446 if (alignFrame != null)
448 AlignmentI al = alignFrame.getViewport().getAlignment();
450 System.out.println("Loaded '" + title + "' in "
451 + (loadtime / 1000.0) + "s, took an additional "
452 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
453 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
457 // report that we didn't load anything probably due to an out of memory
459 System.out.println("Failed to load '" + title + "' in "
460 + (loadtime / 1000.0) + "s, took an additional "
461 + (1.0 * memused / (1024.0 * 1024.0))
462 + " MB (alignment is null)");
465 // remove the visual delay indicator
466 if (Desktop.instance != null)
468 Desktop.instance.stopLoading();
474 * Helper method that adds the alignment as a new frame on the Desktop
479 protected void addAlignFrame(AlignmentI al, String title)
481 // otherwise construct the alignFrame
483 if (source instanceof ComplexAlignFile)
485 ColumnSelection colSel = ((ComplexAlignFile) source)
486 .getColumnSelection();
487 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
488 .getHiddenSequences();
489 String colourSchemeName = ((ComplexAlignFile) source)
490 .getGlobalColourScheme();
491 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
492 .getDisplayedFeatures();
493 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
494 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
495 alignFrame.getViewport().setFeaturesDisplayed(fd);
496 alignFrame.getViewport().setShowSequenceFeatures(
497 ((ComplexAlignFile) source).isShowSeqFeatures());
498 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
499 colourSchemeName, al);
502 alignFrame.changeColour(cs);
507 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
508 AlignFrame.DEFAULT_HEIGHT);
509 if (source instanceof FeaturesSourceI)
511 alignFrame.getViewport().setShowSequenceFeatures(true);
514 // add metadata and update ui
515 if (!(protocol == DataSourceType.PASTE))
517 alignFrame.setFileName(file, format);
519 FeatureSettingsModelI proxyColourScheme = source
520 .getFeatureColourScheme();
521 if (proxyColourScheme != null)
523 alignFrame.getViewport()
524 .applyFeaturesStyle(proxyColourScheme);
526 alignFrame.statusBar.setText(MessageManager.formatMessage(
527 "label.successfully_loaded_file",
528 new String[] { title }));
532 // add the window to the GUI
533 // note - this actually should happen regardless of raiseGUI
534 // status in Jalview 3
535 // TODO: define 'virtual desktop' for benefit of headless scripts
536 // that perform queries to find the 'current working alignment'
537 Desktop.addInternalFrame(alignFrame, title,
538 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
543 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
544 "SHOW_FULLSCREEN", false));
545 } catch (java.beans.PropertyVetoException ex)