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.Jalview;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.ColumnSelection;
28 import jalview.datamodel.PDBEntry;
29 import jalview.datamodel.SequenceI;
30 import jalview.gui.AlignFrame;
31 import jalview.gui.AlignViewport;
32 import jalview.gui.Desktop;
33 import jalview.gui.Jalview2XML;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.MessageManager;
38 import java.util.StringTokenizer;
39 import java.util.Vector;
41 import javax.swing.JOptionPane;
42 import javax.swing.SwingUtilities;
44 public class FileLoader implements Runnable
52 FileParse source = null; // alternative specification of where data comes
56 AlignViewport viewport;
58 AlignFrame alignFrame;
64 boolean raiseGUI = true;
67 * default constructor always raised errors in GUI dialog boxes
75 * construct a Fileloader that may raise errors non-interactively
78 * true if errors are to be raised as GUI dialog boxes
80 public FileLoader(boolean raiseGUI)
82 this.raiseGUI = raiseGUI;
85 public void LoadFile(AlignViewport viewport, String file,
86 String protocol, String format)
88 this.viewport = viewport;
89 LoadFile(file, protocol, format);
92 public void LoadFile(String file, String protocol, String format)
95 this.protocol = protocol;
98 final Thread loader = new Thread(this);
100 SwingUtilities.invokeLater(new Runnable()
110 * Load a (file, protocol) source of unknown type
115 public void LoadFile(String file, String protocol)
117 LoadFile(file, protocol, null);
121 * Load alignment from (file, protocol) and wait till loaded
125 * @return alignFrame constructed from file contents
127 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol)
129 return LoadFileWaitTillLoaded(file, protocol, null);
133 * Load alignment from (file, protocol) of type format and wait till loaded
138 * @return alignFrame constructed from file contents
140 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol,
144 this.protocol = protocol;
145 this.format = format;
146 return _LoadFileWaitTillLoaded();
150 * Load alignment from FileParse source of type format and wait till loaded
154 * @return alignFrame constructed from file contents
156 public AlignFrame LoadFileWaitTillLoaded(FileParse source, String format)
158 this.source = source;
160 file = source.getInFile();
161 protocol = source.type;
162 this.format = format;
163 return _LoadFileWaitTillLoaded();
167 * start thread and wait until finished, then return the alignFrame that's
168 * (hopefully) been read.
172 protected AlignFrame _LoadFileWaitTillLoaded()
174 Thread loader = new Thread(this);
177 while (loader.isAlive())
182 } catch (Exception ex)
190 public void updateRecentlyOpened()
192 Vector recent = new Vector();
193 if (protocol.equals(FormatAdapter.PASTE))
195 // do nothing if the file was pasted in as text... there is no filename to
199 String type = protocol.equals(FormatAdapter.FILE) ? "RECENT_FILE"
202 String historyItems = jalview.bin.Cache.getProperty(type);
206 if (historyItems != null)
208 st = new StringTokenizer(historyItems, "\t");
210 while (st.hasMoreTokens())
212 recent.addElement(st.nextElement().toString().trim());
216 if (recent.contains(file))
221 StringBuffer newHistory = new StringBuffer(file);
222 for (int i = 0; i < recent.size() && i < 10; i++)
224 newHistory.append("\t");
225 newHistory.append(recent.elementAt(i));
228 jalview.bin.Cache.setProperty(type, newHistory.toString());
230 if (protocol.equals(FormatAdapter.FILE))
232 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT", format);
238 String title = protocol.equals(AppletFormatAdapter.PASTE) ? "Copied From Clipboard"
240 Runtime rt = Runtime.getRuntime();
243 if (Desktop.instance != null)
245 Desktop.instance.startLoading(file);
249 // just in case the caller didn't identify the file for us
252 format = new IdentifyFile().Identify(source, false); // identify
259 format = new IdentifyFile().Identify(file, protocol);
264 if (format == null || format.equalsIgnoreCase("EMPTY DATA FILE"))
266 Desktop.instance.stopLoading();
267 System.err.println("The input file \"" + file
268 + "\" has no data content!");
269 if (!Jalview.isHeadlessMode())
271 JOptionPane.showMessageDialog(null, "The input file \""
272 + file + "\" has no data content!", "Empty data file",
273 JOptionPane.ERROR_MESSAGE);
277 // TODO: cache any stream datasources as a temporary file (eg. PDBs
278 // retrieved via URL)
279 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
282 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
287 loadtime = -System.currentTimeMillis();
288 AlignmentI al = null;
290 if (format.equalsIgnoreCase("Jalview"))
294 // Tell the user (developer?) that this is going to cause a problem
296 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
297 // We read the data anyway - it might make sense.
299 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
303 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
304 if (FormatAdapter.isValidFormat(format))
310 // read from the provided source
311 al = new FormatAdapter().readFromFile(source, format);
316 // open a new source and read from it
317 FormatAdapter fa = new FormatAdapter();
318 al = fa.readFile(file, protocol, format);
319 source = fa.getAlignFile(); // keep reference for later if
322 } catch (java.io.IOException ex)
324 error = ex.getMessage();
329 if (format != null && format.length() > 7)
331 // ad hoc message in format.
332 error = format + "\n" + error;
336 if ((al != null) && (al.getHeight() > 0))
338 // construct and register dataset sequences
339 for (SequenceI sq : al.getSequences())
341 while (sq.getDatasetSequence() != null)
343 sq = sq.getDatasetSequence();
345 if (sq.getPDBId() != null)
347 for (PDBEntry pdbe : sq.getPDBId())
349 // register PDB entries with desktop's structure selection
351 StructureSelectionManager.getStructureSelectionManager(
352 Desktop.instance).registerPDBEntry(pdbe);
357 if (viewport != null)
359 // append to existing alignment
360 viewport.addAlignment(al, title);
364 // otherwise construct the alignFrame
366 if (source instanceof ComplexAlignFile)
368 ColumnSelection colSel = ((ComplexAlignFile) source)
369 .getColumnSelection();
370 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
371 .getHiddenSequences();
372 boolean showSeqFeatures = ((ComplexAlignFile) source)
373 .isShowSeqFeatures();
374 ColourSchemeI cs = ((ComplexAlignFile) source)
376 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
377 .getDisplayedFeatures();
378 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
379 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
381 alignFrame.getViewport().setShowSequenceFeatures(
383 alignFrame.getViewport().setFeaturesDisplayed(fd);
384 alignFrame.changeColour(cs);
388 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
389 AlignFrame.DEFAULT_HEIGHT);
391 // add metadata and update ui
392 if (!protocol.equals(AppletFormatAdapter.PASTE))
394 alignFrame.setFileName(file, format);
397 alignFrame.statusBar.setText(MessageManager.formatMessage(
398 "label.successfully_loaded_file", new String[]
403 // add the window to the GUI
404 // note - this actually should happen regardless of raiseGUI
405 // status in Jalview 3
406 // TODO: define 'virtual desktop' for benefit of headless scripts
407 // that perform queries to find the 'current working alignment'
408 Desktop.addInternalFrame(alignFrame, title,
409 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
414 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
415 "SHOW_FULLSCREEN", false));
416 } catch (java.beans.PropertyVetoException ex)
423 if (Desktop.instance != null)
425 Desktop.instance.stopLoading();
428 final String errorMessage = "Couldn't load file " + title + "\n"
430 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
432 if (raiseGUI && Desktop.desktop != null)
434 javax.swing.SwingUtilities.invokeLater(new Runnable()
438 JOptionPane.showInternalMessageDialog(Desktop.desktop,
439 errorMessage, MessageManager
440 .getString("label.error_loading_file"),
441 JOptionPane.WARNING_MESSAGE);
447 System.err.println(errorMessage);
452 updateRecentlyOpened();
454 } catch (Exception er)
456 System.err.println("Exception whilst opening file '" + file);
457 er.printStackTrace();
460 javax.swing.SwingUtilities.invokeLater(new Runnable()
464 javax.swing.JOptionPane.showInternalMessageDialog(
465 Desktop.desktop, MessageManager.formatMessage(
466 "label.problems_opening_file", new String[]
467 { file }), MessageManager
468 .getString("label.file_open_error"),
469 javax.swing.JOptionPane.WARNING_MESSAGE);
474 } catch (OutOfMemoryError er)
477 er.printStackTrace();
481 javax.swing.SwingUtilities.invokeLater(new Runnable()
485 javax.swing.JOptionPane.showInternalMessageDialog(
486 Desktop.desktop, MessageManager.formatMessage(
487 "warn.out_of_memory_loading_file", new String[]
488 { file }), MessageManager
489 .getString("label.out_of_memory"),
490 javax.swing.JOptionPane.WARNING_MESSAGE);
494 System.err.println("Out of memory loading file " + file + "!!");
497 loadtime += System.currentTimeMillis();
498 // TODO: Estimate percentage of memory used by a newly loaded alignment -
499 // warn if more memory will be needed to work with it
502 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
507 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
509 if (alignFrame != null)
511 AlignmentI al = alignFrame.getViewport().getAlignment();
513 System.out.println("Loaded '" + title + "' in "
514 + (loadtime / 1000.0) + "s, took an additional "
515 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
516 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
520 // report that we didn't load anything probably due to an out of memory
522 System.out.println("Failed to load '" + title + "' in "
523 + (loadtime / 1000.0) + "s, took an additional "
524 + (1.0 * memused / (1024.0 * 1024.0))
525 + " MB (alignment is null)");
528 // remove the visual delay indicator
529 if (Desktop.instance != null)
531 Desktop.instance.stopLoading();
539 * @see java.lang.Object#finalize()
541 protected void finalize() throws Throwable