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.api.FeaturesSourceI;
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.json.binding.biojson.v1.ColourSchemeMapper;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.MessageManager;
40 import java.util.StringTokenizer;
41 import java.util.Vector;
43 import javax.swing.JOptionPane;
44 import javax.swing.SwingUtilities;
46 public class FileLoader implements Runnable
54 FileParse source = null; // alternative specification of where data comes
58 AlignViewport viewport;
60 AlignFrame alignFrame;
66 boolean raiseGUI = true;
69 * default constructor always raised errors in GUI dialog boxes
77 * construct a Fileloader that may raise errors non-interactively
80 * true if errors are to be raised as GUI dialog boxes
82 public FileLoader(boolean raiseGUI)
84 this.raiseGUI = raiseGUI;
87 public void LoadFile(AlignViewport viewport, String file,
88 String protocol, String format)
90 this.viewport = viewport;
91 LoadFile(file, protocol, format);
94 public void LoadFile(String file, String protocol, String format)
97 this.protocol = protocol;
100 final Thread loader = new Thread(this);
102 SwingUtilities.invokeLater(new Runnable()
113 * Load a (file, protocol) source of unknown type
118 public void LoadFile(String file, String protocol)
120 LoadFile(file, protocol, null);
124 * Load alignment from (file, protocol) and wait till loaded
128 * @return alignFrame constructed from file contents
130 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol)
132 return LoadFileWaitTillLoaded(file, protocol, null);
136 * Load alignment from (file, protocol) of type format and wait till loaded
141 * @return alignFrame constructed from file contents
143 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol,
147 this.protocol = protocol;
148 this.format = format;
149 return _LoadFileWaitTillLoaded();
153 * Load alignment from FileParse source of type format and wait till loaded
157 * @return alignFrame constructed from file contents
159 public AlignFrame LoadFileWaitTillLoaded(FileParse source, String format)
161 this.source = source;
163 file = source.getInFile();
164 protocol = source.type;
165 this.format = format;
166 return _LoadFileWaitTillLoaded();
170 * start thread and wait until finished, then return the alignFrame that's
171 * (hopefully) been read.
175 protected AlignFrame _LoadFileWaitTillLoaded()
177 Thread loader = new Thread(this);
180 while (loader.isAlive())
185 } catch (Exception ex)
193 public void updateRecentlyOpened()
195 Vector recent = new Vector();
196 if (protocol.equals(FormatAdapter.PASTE))
198 // do nothing if the file was pasted in as text... there is no filename to
202 String type = protocol.equals(FormatAdapter.FILE) ? "RECENT_FILE"
205 String historyItems = jalview.bin.Cache.getProperty(type);
209 if (historyItems != null)
211 st = new StringTokenizer(historyItems, "\t");
213 while (st.hasMoreTokens())
215 recent.addElement(st.nextElement().toString().trim());
219 if (recent.contains(file))
224 StringBuffer newHistory = new StringBuffer(file);
225 for (int i = 0; i < recent.size() && i < 10; i++)
227 newHistory.append("\t");
228 newHistory.append(recent.elementAt(i));
231 jalview.bin.Cache.setProperty(type, newHistory.toString());
233 if (protocol.equals(FormatAdapter.FILE))
235 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT", format);
242 String title = protocol.equals(AppletFormatAdapter.PASTE) ? "Copied From Clipboard"
244 Runtime rt = Runtime.getRuntime();
247 if (Desktop.instance != null)
249 Desktop.instance.startLoading(file);
253 // just in case the caller didn't identify the file for us
256 format = new IdentifyFile().identify(source, false); // identify
263 format = new IdentifyFile().identify(file, protocol);
268 if (format == null || format.equalsIgnoreCase("EMPTY DATA FILE"))
270 Desktop.instance.stopLoading();
271 System.err.println("The input file \"" + file
272 + "\" has null or unidentifiable data content!");
273 if (!Jalview.isHeadlessMode())
275 javax.swing.JOptionPane.showInternalMessageDialog(
277 MessageManager.getString("label.couldnt_read_data")
278 + " in " + file + "\n"
279 + AppletFormatAdapter.SUPPORTED_FORMATS,
280 MessageManager.getString("label.couldnt_read_data"),
281 JOptionPane.WARNING_MESSAGE);
285 // TODO: cache any stream datasources as a temporary file (eg. PDBs
286 // retrieved via URL)
287 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
290 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
295 loadtime = -System.currentTimeMillis();
296 AlignmentI al = null;
298 if (format.equalsIgnoreCase("Jalview"))
302 // Tell the user (developer?) that this is going to cause a problem
304 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
305 // We read the data anyway - it might make sense.
307 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
311 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
312 if (FormatAdapter.isValidFormat(format))
318 // read from the provided source
319 al = new FormatAdapter().readFromFile(source, format);
324 // open a new source and read from it
325 FormatAdapter fa = new FormatAdapter();
326 al = fa.readFile(file, protocol, format);
327 source = fa.getAlignFile(); // keep reference for later if
330 } catch (java.io.IOException ex)
332 error = ex.getMessage();
337 if (format != null && format.length() > 7)
339 // ad hoc message in format.
340 error = format + "\n" + error;
344 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
346 // construct and register dataset sequences
347 for (SequenceI sq : al.getSequences())
349 while (sq.getDatasetSequence() != null)
351 sq = sq.getDatasetSequence();
353 if (sq.getAllPDBEntries() != null)
355 for (PDBEntry pdbe : sq.getAllPDBEntries())
357 // register PDB entries with desktop's structure selection
359 StructureSelectionManager.getStructureSelectionManager(
360 Desktop.instance).registerPDBEntry(pdbe);
365 if (viewport != null)
367 // append to existing alignment
368 viewport.addAlignment(al, title);
372 // otherwise construct the alignFrame
374 if (source instanceof ComplexAlignFile)
376 ColumnSelection colSel = ((ComplexAlignFile) source)
377 .getColumnSelection();
378 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
379 .getHiddenSequences();
380 String colourSchemeName = ((ComplexAlignFile) source)
381 .getGlobalColourScheme();
382 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
383 .getDisplayedFeatures();
384 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
385 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
386 alignFrame.getViewport().setFeaturesDisplayed(fd);
387 alignFrame.getViewport().setShowSequenceFeatures(
388 ((ComplexAlignFile) source).isShowSeqFeatures());
389 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
390 colourSchemeName, al);
393 alignFrame.changeColour(cs);
398 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
399 AlignFrame.DEFAULT_HEIGHT);
400 if (source instanceof FeaturesSourceI)
402 alignFrame.getViewport().setShowSequenceFeatures(true);
405 // add metadata and update ui
406 if (!protocol.equals(AppletFormatAdapter.PASTE))
408 alignFrame.setFileName(file, format);
411 alignFrame.statusBar.setText(MessageManager.formatMessage(
412 "label.successfully_loaded_file",
413 new String[] { title }));
417 // add the window to the GUI
418 // note - this actually should happen regardless of raiseGUI
419 // status in Jalview 3
420 // TODO: define 'virtual desktop' for benefit of headless scripts
421 // that perform queries to find the 'current working alignment'
422 Desktop.addInternalFrame(alignFrame, title,
423 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
428 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
429 "SHOW_FULLSCREEN", false));
430 } catch (java.beans.PropertyVetoException ex)
437 if (Desktop.instance != null)
439 Desktop.instance.stopLoading();
442 final String errorMessage = MessageManager
443 .getString("label.couldnt_load_file")
447 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
449 if (raiseGUI && Desktop.desktop != null)
451 javax.swing.SwingUtilities.invokeLater(new Runnable()
456 JOptionPane.showInternalMessageDialog(Desktop.desktop,
457 errorMessage, MessageManager
458 .getString("label.error_loading_file"),
459 JOptionPane.WARNING_MESSAGE);
465 System.err.println(errorMessage);
470 updateRecentlyOpened();
472 } catch (Exception er)
474 System.err.println("Exception whilst opening file '" + file);
475 er.printStackTrace();
478 javax.swing.SwingUtilities.invokeLater(new Runnable()
483 javax.swing.JOptionPane.showInternalMessageDialog(
484 Desktop.desktop, MessageManager.formatMessage(
485 "label.problems_opening_file",
486 new String[] { file }), MessageManager
487 .getString("label.file_open_error"),
488 javax.swing.JOptionPane.WARNING_MESSAGE);
493 } catch (OutOfMemoryError er)
496 er.printStackTrace();
500 javax.swing.SwingUtilities.invokeLater(new Runnable()
505 javax.swing.JOptionPane.showInternalMessageDialog(
506 Desktop.desktop, MessageManager.formatMessage(
507 "warn.out_of_memory_loading_file", new String[]
508 { file }), MessageManager
509 .getString("label.out_of_memory"),
510 javax.swing.JOptionPane.WARNING_MESSAGE);
514 System.err.println("Out of memory loading file " + file + "!!");
517 loadtime += System.currentTimeMillis();
518 // TODO: Estimate percentage of memory used by a newly loaded alignment -
519 // warn if more memory will be needed to work with it
522 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
527 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
529 if (alignFrame != null)
531 AlignmentI al = alignFrame.getViewport().getAlignment();
533 System.out.println("Loaded '" + title + "' in "
534 + (loadtime / 1000.0) + "s, took an additional "
535 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
536 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
540 // report that we didn't load anything probably due to an out of memory
542 System.out.println("Failed to load '" + title + "' in "
543 + (loadtime / 1000.0) + "s, took an additional "
544 + (1.0 * memused / (1024.0 * 1024.0))
545 + " MB (alignment is null)");
548 // remove the visual delay indicator
549 if (Desktop.instance != null)
551 Desktop.instance.stopLoading();
559 * @see java.lang.Object#finalize()
562 protected void finalize() throws Throwable