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.FeaturesDisplayedI;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.ColumnSelection;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.AlignViewport;
31 import jalview.gui.Desktop;
32 import jalview.gui.Jalview2XML;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.structure.StructureSelectionManager;
35 import jalview.util.MessageManager;
37 import java.util.StringTokenizer;
38 import java.util.Vector;
40 import javax.swing.JOptionPane;
41 import javax.swing.SwingUtilities;
43 public class FileLoader implements Runnable
51 FileParse source = null; // alternative specification of where data comes
55 AlignViewport viewport;
57 AlignFrame alignFrame;
63 boolean raiseGUI = true;
66 * default constructor always raised errors in GUI dialog boxes
74 * construct a Fileloader that may raise errors non-interactively
77 * true if errors are to be raised as GUI dialog boxes
79 public FileLoader(boolean raiseGUI)
81 this.raiseGUI = raiseGUI;
84 public void LoadFile(AlignViewport viewport, String file,
85 String protocol, String format)
87 this.viewport = viewport;
88 LoadFile(file, protocol, format);
91 public void LoadFile(String file, String protocol, String format)
94 this.protocol = protocol;
97 final Thread loader = new Thread(this);
99 SwingUtilities.invokeLater(new Runnable()
109 * Load a (file, protocol) source of unknown type
114 public void LoadFile(String file, String protocol)
116 LoadFile(file, protocol, null);
120 * Load alignment from (file, protocol) and wait till loaded
124 * @return alignFrame constructed from file contents
126 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol)
128 return LoadFileWaitTillLoaded(file, protocol, null);
132 * Load alignment from (file, protocol) of type format and wait till loaded
137 * @return alignFrame constructed from file contents
139 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol,
143 this.protocol = protocol;
144 this.format = format;
145 return _LoadFileWaitTillLoaded();
149 * Load alignment from FileParse source of type format and wait till loaded
153 * @return alignFrame constructed from file contents
155 public AlignFrame LoadFileWaitTillLoaded(FileParse source, String format)
157 this.source = source;
159 file = source.getInFile();
160 protocol = source.type;
161 this.format = format;
162 return _LoadFileWaitTillLoaded();
166 * start thread and wait until finished, then return the alignFrame that's
167 * (hopefully) been read.
171 protected AlignFrame _LoadFileWaitTillLoaded()
173 Thread loader = new Thread(this);
176 while (loader.isAlive())
181 } catch (Exception ex)
189 public void updateRecentlyOpened()
191 Vector recent = new Vector();
192 if (protocol.equals(FormatAdapter.PASTE))
194 // do nothing if the file was pasted in as text... there is no filename to
198 String type = protocol.equals(FormatAdapter.FILE) ? "RECENT_FILE"
201 String historyItems = jalview.bin.Cache.getProperty(type);
205 if (historyItems != null)
207 st = new StringTokenizer(historyItems, "\t");
209 while (st.hasMoreTokens())
211 recent.addElement(st.nextElement().toString().trim());
215 if (recent.contains(file))
220 StringBuffer newHistory = new StringBuffer(file);
221 for (int i = 0; i < recent.size() && i < 10; i++)
223 newHistory.append("\t");
224 newHistory.append(recent.elementAt(i));
227 jalview.bin.Cache.setProperty(type, newHistory.toString());
229 if (protocol.equals(FormatAdapter.FILE))
231 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT", format);
237 String title = protocol.equals(AppletFormatAdapter.PASTE) ? "Copied From Clipboard"
239 Runtime rt = Runtime.getRuntime();
242 if (Desktop.instance != null)
244 Desktop.instance.startLoading(file);
248 // just in case the caller didn't identify the file for us
251 format = new IdentifyFile().Identify(source, false); // identify
258 format = new IdentifyFile().Identify(file, protocol);
261 // TODO: cache any stream datasources as a temporary file (eg. PDBs
262 // retrieved via URL)
263 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
266 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
271 loadtime = -System.currentTimeMillis();
272 AlignmentI al = null;
274 if (format.equalsIgnoreCase("Jalview"))
278 // Tell the user (developer?) that this is going to cause a problem
280 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
281 // We read the data anyway - it might make sense.
283 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
287 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
288 if (FormatAdapter.isValidFormat(format))
294 // read from the provided source
295 al = new FormatAdapter().readFromFile(source, format);
300 // open a new source and read from it
301 FormatAdapter fa = new FormatAdapter();
302 al = fa.readFile(file, protocol, format);
303 source = fa.getAlignFile(); // keep reference for later if
306 } catch (java.io.IOException ex)
308 error = ex.getMessage();
313 if (format != null && format.length() > 7)
315 // ad hoc message in format.
316 error = format + "\n" + error;
320 if ((al != null) && (al.getHeight() > 0))
322 // construct and register dataset sequences
323 for (SequenceI sq : al.getSequences())
325 while (sq.getDatasetSequence() != null)
327 sq = sq.getDatasetSequence();
329 if (sq.getPDBId() != null)
331 for (PDBEntry pdbe : sq.getPDBId())
333 // register PDB entries with desktop's structure selection
335 StructureSelectionManager.getStructureSelectionManager(
336 Desktop.instance).registerPDBEntry(pdbe);
341 if (viewport != null)
343 // append to existing alignment
344 viewport.addAlignment(al, title);
348 // otherwise construct the alignFrame
350 if (source instanceof ComplexAlignFile)
352 ColumnSelection colSel = ((ComplexAlignFile) source)
353 .getColumnSelection();
354 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
355 .getHiddenSequences();
356 boolean showSeqFeatures = ((ComplexAlignFile) source)
357 .isShowSeqFeatures();
358 ColourSchemeI cs = ((ComplexAlignFile) source)
360 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
361 .getDisplayedFeatures();
362 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
363 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
365 alignFrame.getViewport().setShowSequenceFeatures(
367 alignFrame.getViewport().setFeaturesDisplayed(fd);
368 alignFrame.changeColour(cs);
372 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
373 AlignFrame.DEFAULT_HEIGHT);
375 // add metadata and update ui
376 if (!protocol.equals(AppletFormatAdapter.PASTE))
378 alignFrame.setFileName(file, format);
381 alignFrame.statusBar.setText(MessageManager.formatMessage(
382 "label.successfully_loaded_file", new String[]
387 // add the window to the GUI
388 // note - this actually should happen regardless of raiseGUI
389 // status in Jalview 3
390 // TODO: define 'virtual desktop' for benefit of headless scripts
391 // that perform queries to find the 'current working alignment'
392 Desktop.addInternalFrame(alignFrame, title,
393 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
398 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
399 "SHOW_FULLSCREEN", false));
400 } catch (java.beans.PropertyVetoException ex)
407 if (Desktop.instance != null)
409 Desktop.instance.stopLoading();
412 final String errorMessage = "Couldn't load file " + title + "\n"
414 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
416 if (raiseGUI && Desktop.desktop != null)
418 javax.swing.SwingUtilities.invokeLater(new Runnable()
422 JOptionPane.showInternalMessageDialog(Desktop.desktop,
423 errorMessage, MessageManager
424 .getString("label.error_loading_file"),
425 JOptionPane.WARNING_MESSAGE);
431 System.err.println(errorMessage);
436 updateRecentlyOpened();
438 } catch (Exception er)
440 System.err.println("Exception whilst opening file '" + file);
441 er.printStackTrace();
444 javax.swing.SwingUtilities.invokeLater(new Runnable()
448 javax.swing.JOptionPane.showInternalMessageDialog(
449 Desktop.desktop, MessageManager.formatMessage(
450 "label.problems_opening_file", new String[]
451 { file }), MessageManager
452 .getString("label.file_open_error"),
453 javax.swing.JOptionPane.WARNING_MESSAGE);
458 } catch (OutOfMemoryError er)
461 er.printStackTrace();
465 javax.swing.SwingUtilities.invokeLater(new Runnable()
469 javax.swing.JOptionPane.showInternalMessageDialog(
470 Desktop.desktop, MessageManager.formatMessage(
471 "warn.out_of_memory_loading_file", new String[]
472 { file }), MessageManager
473 .getString("label.out_of_memory"),
474 javax.swing.JOptionPane.WARNING_MESSAGE);
478 System.err.println("Out of memory loading file " + file + "!!");
481 loadtime += System.currentTimeMillis();
482 // TODO: Estimate percentage of memory used by a newly loaded alignment -
483 // warn if more memory will be needed to work with it
486 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
491 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
493 if (alignFrame != null)
495 AlignmentI al = alignFrame.getViewport().getAlignment();
497 System.out.println("Loaded '" + title + "' in "
498 + (loadtime / 1000.0) + "s, took an additional "
499 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
500 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
504 // report that we didn't load anything probably due to an out of memory
506 System.out.println("Failed to load '" + title + "' in "
507 + (loadtime / 1000.0) + "s, took an additional "
508 + (1.0 * memused / (1024.0 * 1024.0))
509 + " MB (alignment is null)");
512 // remove the visual delay indicator
513 if (Desktop.instance != null)
515 Desktop.instance.stopLoading();
523 * @see java.lang.Object#finalize()
525 protected void finalize() throws Throwable