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.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 AlignmentFileI source = null; // alternative specification of where data comes
60 AlignViewport viewport;
62 AlignFrame alignFrame;
68 boolean raiseGUI = true;
71 * default constructor always raised errors in GUI dialog boxes
79 * construct a Fileloader that may raise errors non-interactively
82 * true if errors are to be raised as GUI dialog boxes
84 public FileLoader(boolean raiseGUI)
86 this.raiseGUI = raiseGUI;
89 public void LoadFile(AlignViewport viewport, String file,
90 DataSourceType protocol, FileFormatI format)
92 this.viewport = viewport;
93 LoadFile(file, protocol, format);
96 public void LoadFile(String file, DataSourceType protocol,
100 this.protocol = protocol;
101 this.format = format;
103 final Thread loader = new Thread(this);
105 SwingUtilities.invokeLater(new Runnable()
116 * Load a (file, protocol) source of unknown type
121 public void LoadFile(String file, DataSourceType protocol)
123 LoadFile(file, protocol, null);
127 * Load alignment from (file, protocol) and wait till loaded
131 * @return alignFrame constructed from file contents
133 public AlignFrame LoadFileWaitTillLoaded(String file,
134 DataSourceType sourceType)
136 return LoadFileWaitTillLoaded(file, sourceType, null);
140 * Load alignment from (file, protocol) of type format and wait till loaded
145 * @return alignFrame constructed from file contents
147 public AlignFrame LoadFileWaitTillLoaded(String file,
148 DataSourceType sourceType, FileFormatI format)
151 this.protocol = sourceType;
152 this.format = format;
153 return _LoadFileWaitTillLoaded();
157 * Load alignment from FileParse source of type format and wait till loaded
161 * @return alignFrame constructed from file contents
163 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileI source,
166 this.source = source;
168 file = source.getInFile();
169 protocol = source.getDataSourceType();
170 this.format = format;
171 return _LoadFileWaitTillLoaded();
175 * start thread and wait until finished, then return the alignFrame that's
176 * (hopefully) been read.
180 protected AlignFrame _LoadFileWaitTillLoaded()
182 Thread loader = new Thread(this);
185 while (loader.isAlive())
190 } catch (Exception ex)
198 public void updateRecentlyOpened()
200 Vector recent = new Vector();
201 if (protocol == DataSourceType.PASTE)
203 // do nothing if the file was pasted in as text... there is no filename to
207 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
210 String historyItems = jalview.bin.Cache.getProperty(type);
214 if (historyItems != null)
216 st = new StringTokenizer(historyItems, "\t");
218 while (st.hasMoreTokens())
220 recent.addElement(st.nextElement().toString().trim());
224 if (recent.contains(file))
229 StringBuffer newHistory = new StringBuffer(file);
230 for (int i = 0; i < recent.size() && i < 10; i++)
232 newHistory.append("\t");
233 newHistory.append(recent.elementAt(i));
236 Cache.setProperty(type, newHistory.toString());
238 if (protocol == DataSourceType.FILE)
240 Cache.setProperty("DEFAULT_FILE_FORMAT", format.toString());
247 String title = protocol == DataSourceType.PASTE ? "Copied From Clipboard"
249 Runtime rt = Runtime.getRuntime();
252 if (Desktop.instance != null)
254 Desktop.instance.startLoading(file);
258 // just in case the caller didn't identify the file for us
261 format = new IdentifyFile().identify(source, false);
262 // identify stream and rewind rather than close
266 format = new IdentifyFile().identify(file, protocol);
273 Desktop.instance.stopLoading();
274 System.err.println("The input file \"" + file
275 + "\" has null or unidentifiable data content!");
276 if (!Jalview.isHeadlessMode())
278 JvOptionPane.showInternalMessageDialog(
280 MessageManager.getString("label.couldnt_read_data")
281 + " in " + file + "\n"
282 + AppletFormatAdapter.SUPPORTED_FORMATS,
283 MessageManager.getString("label.couldnt_read_data"),
284 JvOptionPane.WARNING_MESSAGE);
288 // TODO: cache any stream datasources as a temporary file (eg. PDBs
289 // retrieved via URL)
290 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
293 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
298 loadtime = -System.currentTimeMillis();
299 AlignmentI al = null;
301 if (FileFormat.Jalview.equals(format))
305 // Tell the user (developer?) that this is going to cause a problem
307 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
308 // We read the data anyway - it might make sense.
310 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
314 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
319 // read from the provided source
320 al = new FormatAdapter().readFromFile(source, format);
325 // open a new source and read from it
326 FormatAdapter fa = new FormatAdapter();
327 al = fa.readFile(file, protocol, format);
328 source = fa.getAlignFile(); // keep reference for later if
331 } catch (java.io.IOException ex)
333 error = ex.getMessage();
336 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
338 // construct and register dataset sequences
339 for (SequenceI sq : al.getSequences())
341 while (sq.getDatasetSequence() != null)
343 sq = sq.getDatasetSequence();
345 if (sq.getAllPDBEntries() != null)
347 for (PDBEntry pdbe : sq.getAllPDBEntries())
349 // register PDB entries with desktop's structure selection
351 StructureSelectionManager.getStructureSelectionManager(
352 Desktop.instance).registerPDBEntry(pdbe);
357 FeatureSettingsModelI proxyColourScheme = source
358 .getFeatureColourScheme();
359 if (viewport != null)
361 if (proxyColourScheme != null)
363 viewport.applyFeaturesStyle(proxyColourScheme);
365 // append to existing alignment
366 viewport.addAlignment(al, title);
370 // otherwise construct the alignFrame
372 if (source instanceof ComplexAlignFile)
374 ColumnSelection colSel = ((ComplexAlignFile) source)
375 .getColumnSelection();
376 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
377 .getHiddenSequences();
378 String colourSchemeName = ((ComplexAlignFile) source)
379 .getGlobalColourScheme();
380 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
381 .getDisplayedFeatures();
382 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
383 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
384 alignFrame.getViewport().setFeaturesDisplayed(fd);
385 alignFrame.getViewport().setShowSequenceFeatures(
386 ((ComplexAlignFile) source).isShowSeqFeatures());
387 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
388 colourSchemeName, al);
391 alignFrame.changeColour(cs);
396 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
397 AlignFrame.DEFAULT_HEIGHT);
398 if (source instanceof FeaturesSourceI)
400 alignFrame.getViewport().setShowSequenceFeatures(true);
403 // add metadata and update ui
404 if (!(protocol == DataSourceType.PASTE))
406 alignFrame.setFileName(file, format);
408 if (proxyColourScheme != null)
410 alignFrame.getViewport()
411 .applyFeaturesStyle(proxyColourScheme);
413 alignFrame.statusBar.setText(MessageManager.formatMessage(
414 "label.successfully_loaded_file",
415 new String[] { title }));
419 // add the window to the GUI
420 // note - this actually should happen regardless of raiseGUI
421 // status in Jalview 3
422 // TODO: define 'virtual desktop' for benefit of headless scripts
423 // that perform queries to find the 'current working alignment'
424 Desktop.addInternalFrame(alignFrame, title,
425 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
430 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
431 "SHOW_FULLSCREEN", false));
432 } catch (java.beans.PropertyVetoException ex)
439 if (Desktop.instance != null)
441 Desktop.instance.stopLoading();
444 final String errorMessage = MessageManager
445 .getString("label.couldnt_load_file")
449 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
451 if (raiseGUI && Desktop.desktop != null)
453 javax.swing.SwingUtilities.invokeLater(new Runnable()
458 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
459 errorMessage, MessageManager
460 .getString("label.error_loading_file"),
461 JvOptionPane.WARNING_MESSAGE);
467 System.err.println(errorMessage);
472 updateRecentlyOpened();
474 } catch (Exception er)
476 System.err.println("Exception whilst opening file '" + file);
477 er.printStackTrace();
480 javax.swing.SwingUtilities.invokeLater(new Runnable()
485 JvOptionPane.showInternalMessageDialog(
486 Desktop.desktop, MessageManager.formatMessage(
487 "label.problems_opening_file",
488 new String[] { file }), MessageManager
489 .getString("label.file_open_error"),
490 JvOptionPane.WARNING_MESSAGE);
495 } catch (OutOfMemoryError er)
498 er.printStackTrace();
502 javax.swing.SwingUtilities.invokeLater(new Runnable()
507 JvOptionPane.showInternalMessageDialog(
508 Desktop.desktop, MessageManager.formatMessage(
509 "warn.out_of_memory_loading_file", new String[]
510 { file }), MessageManager
511 .getString("label.out_of_memory"),
512 JvOptionPane.WARNING_MESSAGE);
516 System.err.println("Out of memory loading file " + file + "!!");
519 loadtime += System.currentTimeMillis();
520 // TODO: Estimate percentage of memory used by a newly loaded alignment -
521 // warn if more memory will be needed to work with it
524 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
529 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
531 if (alignFrame != null)
533 AlignmentI al = alignFrame.getViewport().getAlignment();
535 System.out.println("Loaded '" + title + "' in "
536 + (loadtime / 1000.0) + "s, took an additional "
537 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
538 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
542 // report that we didn't load anything probably due to an out of memory
544 System.out.println("Failed to load '" + title + "' in "
545 + (loadtime / 1000.0) + "s, took an additional "
546 + (1.0 * memused / (1024.0 * 1024.0))
547 + " MB (alignment is null)");
550 // remove the visual delay indicator
551 if (Desktop.instance != null)
553 Desktop.instance.stopLoading();
561 * @see java.lang.Object#finalize()
564 protected void finalize() throws Throwable