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.bin.Cache;
26 import jalview.bin.Jalview;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.AlignFrame;
32 import jalview.gui.AlignViewport;
33 import jalview.gui.Desktop;
34 import jalview.gui.Jalview2XML;
35 import jalview.schemes.ColourSchemeI;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.MessageManager;
39 import java.util.StringTokenizer;
40 import java.util.Vector;
42 import javax.swing.JOptionPane;
43 import javax.swing.SwingUtilities;
45 public class FileLoader implements Runnable
53 FileParse source = null; // alternative specification of where data comes
57 AlignViewport viewport;
59 AlignFrame alignFrame;
65 boolean raiseGUI = true;
68 * default constructor always raised errors in GUI dialog boxes
76 * construct a Fileloader that may raise errors non-interactively
79 * true if errors are to be raised as GUI dialog boxes
81 public FileLoader(boolean raiseGUI)
83 this.raiseGUI = raiseGUI;
86 public void LoadFile(AlignViewport viewport, String file,
87 String protocol, String format)
89 this.viewport = viewport;
90 LoadFile(file, protocol, format);
93 public void LoadFile(String file, String protocol, String format)
96 this.protocol = protocol;
99 final Thread loader = new Thread(this);
101 SwingUtilities.invokeLater(new Runnable()
111 * Load a (file, protocol) source of unknown type
116 public void LoadFile(String file, String protocol)
118 LoadFile(file, protocol, null);
122 * Load alignment from (file, protocol) and wait till loaded
126 * @return alignFrame constructed from file contents
128 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol)
130 return LoadFileWaitTillLoaded(file, protocol, null);
134 * Load alignment from (file, protocol) of type format and wait till loaded
139 * @return alignFrame constructed from file contents
141 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol,
145 this.protocol = protocol;
146 this.format = format;
147 return _LoadFileWaitTillLoaded();
151 * Load alignment from FileParse source of type format and wait till loaded
155 * @return alignFrame constructed from file contents
157 public AlignFrame LoadFileWaitTillLoaded(FileParse source, String format)
159 this.source = source;
161 file = source.getInFile();
162 protocol = source.type;
163 this.format = format;
164 return _LoadFileWaitTillLoaded();
168 * start thread and wait until finished, then return the alignFrame that's
169 * (hopefully) been read.
173 protected AlignFrame _LoadFileWaitTillLoaded()
175 Thread loader = new Thread(this);
178 while (loader.isAlive())
183 } catch (Exception ex)
191 public void updateRecentlyOpened()
193 Vector recent = new Vector();
194 if (protocol.equals(FormatAdapter.PASTE))
196 // do nothing if the file was pasted in as text... there is no filename to
200 String type = protocol.equals(FormatAdapter.FILE) ? "RECENT_FILE"
203 String historyItems = Cache.getProperty(type);
207 if (historyItems != null)
209 st = new StringTokenizer(historyItems, "\t");
211 while (st.hasMoreTokens())
213 recent.addElement(st.nextElement().toString().trim());
217 if (recent.contains(file))
222 StringBuffer newHistory = new StringBuffer(file);
223 for (int i = 0; i < recent.size() && i < 10; i++)
225 newHistory.append("\t");
226 newHistory.append(recent.elementAt(i));
229 Cache.setProperty(type, newHistory.toString());
231 if (protocol.equals(FormatAdapter.FILE))
233 Cache.setProperty("DEFAULT_FILE_FORMAT", format);
239 String title = protocol.equals(AppletFormatAdapter.PASTE) ? "Copied From Clipboard"
241 Runtime rt = Runtime.getRuntime();
244 if (Desktop.instance != null)
246 Desktop.instance.startLoading(file);
250 // just in case the caller didn't identify the file for us
253 format = new IdentifyFile().Identify(source, false); // identify
260 format = new IdentifyFile().Identify(file, protocol);
265 if (format == null || format.equalsIgnoreCase("EMPTY DATA FILE"))
267 Desktop.instance.stopLoading();
268 System.err.println("The input file \"" + file
269 + "\" has no data content!");
270 if (!Jalview.isHeadlessMode())
272 JOptionPane.showMessageDialog(null, "The input file \""
273 + file + "\" has no data content!", "Empty data file",
274 JOptionPane.ERROR_MESSAGE);
278 // TODO: cache any stream datasources as a temporary file (eg. PDBs
279 // retrieved via URL)
280 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
283 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
288 loadtime = -System.currentTimeMillis();
289 AlignmentI al = null;
291 if (format.equalsIgnoreCase("Jalview"))
295 // Tell the user (developer?) that this is going to cause a problem
297 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
298 // We read the data anyway - it might make sense.
300 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
304 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
305 if (FormatAdapter.isValidFormat(format))
311 // read from the provided source
312 al = new FormatAdapter().readFromFile(source, format);
317 // open a new source and read from it
318 FormatAdapter fa = new FormatAdapter();
319 al = fa.readFile(file, protocol, format);
320 source = fa.getAlignFile(); // keep reference for later if
323 } catch (java.io.IOException ex)
325 error = ex.getMessage();
330 if (format != null && format.length() > 7)
332 // ad hoc message in format.
333 error = format + "\n" + error;
337 if ((al != null) && (al.getHeight() > 0))
339 // construct and register dataset sequences
340 for (SequenceI sq : al.getSequences())
342 while (sq.getDatasetSequence() != null)
344 sq = sq.getDatasetSequence();
346 if (sq.getPDBId() != null)
348 for (PDBEntry pdbe : sq.getPDBId())
350 // register PDB entries with desktop's structure selection
352 StructureSelectionManager.getStructureSelectionManager(
353 Desktop.instance).registerPDBEntry(pdbe);
358 if (viewport != null)
360 // append to existing alignment
361 viewport.addAlignment(al, title);
365 // otherwise construct the alignFrame
367 if (source instanceof ComplexAlignFile)
369 ColumnSelection colSel = ((ComplexAlignFile) source)
370 .getColumnSelection();
371 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
372 .getHiddenSequences();
373 boolean showSeqFeatures = ((ComplexAlignFile) source)
374 .isShowSeqFeatures();
375 ColourSchemeI cs = ((ComplexAlignFile) source)
377 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
378 .getDisplayedFeatures();
379 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
380 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
382 alignFrame.getViewport().setShowSequenceFeatures(
384 alignFrame.getViewport().setFeaturesDisplayed(fd);
385 alignFrame.changeColour(cs);
389 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
390 AlignFrame.DEFAULT_HEIGHT);
392 // add metadata and update ui
393 if (!protocol.equals(AppletFormatAdapter.PASTE))
395 alignFrame.setFileName(file, format);
398 alignFrame.statusBar.setText(MessageManager.formatMessage(
399 "label.successfully_loaded_file", new String[]
404 // add the window to the GUI
405 // note - this actually should happen regardless of raiseGUI
406 // status in Jalview 3
407 // TODO: define 'virtual desktop' for benefit of headless scripts
408 // that perform queries to find the 'current working alignment'
409 Desktop.addInternalFrame(alignFrame, title,
410 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
415 alignFrame.setMaximum(Cache.getDefault(
416 "SHOW_FULLSCREEN", false));
417 } catch (java.beans.PropertyVetoException ex)
424 if (Desktop.instance != null)
426 Desktop.instance.stopLoading();
429 final String errorMessage = "Couldn't load file " + title + "\n"
431 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
433 if (raiseGUI && Desktop.desktop != null)
435 javax.swing.SwingUtilities.invokeLater(new Runnable()
439 JOptionPane.showInternalMessageDialog(Desktop.desktop,
440 errorMessage, MessageManager
441 .getString("label.error_loading_file"),
442 JOptionPane.WARNING_MESSAGE);
448 System.err.println(errorMessage);
453 updateRecentlyOpened();
455 } catch (Exception er)
457 System.err.println("Exception whilst opening file '" + file);
458 er.printStackTrace();
461 javax.swing.SwingUtilities.invokeLater(new Runnable()
465 javax.swing.JOptionPane.showInternalMessageDialog(
466 Desktop.desktop, MessageManager.formatMessage(
467 "label.problems_opening_file", new String[]
468 { file }), MessageManager
469 .getString("label.file_open_error"),
470 javax.swing.JOptionPane.WARNING_MESSAGE);
475 } catch (OutOfMemoryError er)
478 er.printStackTrace();
482 javax.swing.SwingUtilities.invokeLater(new Runnable()
486 javax.swing.JOptionPane.showInternalMessageDialog(
487 Desktop.desktop, MessageManager.formatMessage(
488 "warn.out_of_memory_loading_file", new String[]
489 { file }), MessageManager
490 .getString("label.out_of_memory"),
491 javax.swing.JOptionPane.WARNING_MESSAGE);
495 System.err.println("Out of memory loading file " + file + "!!");
498 loadtime += System.currentTimeMillis();
499 // TODO: Estimate percentage of memory used by a newly loaded alignment -
500 // warn if more memory will be needed to work with it
503 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
508 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
510 if (alignFrame != null)
512 AlignmentI al = alignFrame.getViewport().getAlignment();
514 System.out.println("Loaded '" + title + "' in "
515 + (loadtime / 1000.0) + "s, took an additional "
516 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
517 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
521 // report that we didn't load anything probably due to an out of memory
523 System.out.println("Failed to load '" + title + "' in "
524 + (loadtime / 1000.0) + "s, took an additional "
525 + (1.0 * memused / (1024.0 * 1024.0))
526 + " MB (alignment is null)");
529 // remove the visual delay indicator
530 if (Desktop.instance != null)
532 Desktop.instance.stopLoading();
540 * @see java.lang.Object#finalize()
542 protected void finalize() throws Throwable