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 null or unidentifiable data content!");
269 if (!Jalview.isHeadlessMode())
271 javax.swing.JOptionPane.showInternalMessageDialog(
273 MessageManager.getString("label.couldnt_read_data")
274 + " in " + file + "\n"
275 + AppletFormatAdapter.SUPPORTED_FORMATS,
276 MessageManager.getString("label.couldnt_read_data"),
277 JOptionPane.WARNING_MESSAGE);
281 // TODO: cache any stream datasources as a temporary file (eg. PDBs
282 // retrieved via URL)
283 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
286 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
291 loadtime = -System.currentTimeMillis();
292 AlignmentI al = null;
294 if (format.equalsIgnoreCase("Jalview"))
298 // Tell the user (developer?) that this is going to cause a problem
300 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
301 // We read the data anyway - it might make sense.
303 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
307 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
308 if (FormatAdapter.isValidFormat(format))
314 // read from the provided source
315 al = new FormatAdapter().readFromFile(source, format);
320 // open a new source and read from it
321 FormatAdapter fa = new FormatAdapter();
322 al = fa.readFile(file, protocol, format);
323 source = fa.getAlignFile(); // keep reference for later if
326 } catch (java.io.IOException ex)
328 error = ex.getMessage();
333 if (format != null && format.length() > 7)
335 // ad hoc message in format.
336 error = format + "\n" + error;
340 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
342 // construct and register dataset sequences
343 for (SequenceI sq : al.getSequences())
345 while (sq.getDatasetSequence() != null)
347 sq = sq.getDatasetSequence();
349 if (sq.getAllPDBEntries() != null)
351 for (PDBEntry pdbe : sq.getAllPDBEntries())
353 // register PDB entries with desktop's structure selection
355 StructureSelectionManager.getStructureSelectionManager(
356 Desktop.instance).registerPDBEntry(pdbe);
361 if (viewport != null)
363 // append to existing alignment
364 viewport.addAlignment(al, title);
368 // otherwise construct the alignFrame
370 if (source instanceof ComplexAlignFile)
372 ColumnSelection colSel = ((ComplexAlignFile) source)
373 .getColumnSelection();
374 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
375 .getHiddenSequences();
376 boolean showSeqFeatures = ((ComplexAlignFile) source)
377 .isShowSeqFeatures();
378 ColourSchemeI cs = ((ComplexAlignFile) source)
380 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
381 .getDisplayedFeatures();
382 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
383 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
385 alignFrame.getViewport().setShowSequenceFeatures(
387 alignFrame.getViewport().setFeaturesDisplayed(fd);
388 alignFrame.changeColour(cs);
392 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
393 AlignFrame.DEFAULT_HEIGHT);
395 // add metadata and update ui
396 if (!protocol.equals(AppletFormatAdapter.PASTE))
398 alignFrame.setFileName(file, format);
401 alignFrame.statusBar.setText(MessageManager.formatMessage(
402 "label.successfully_loaded_file", new String[]
407 // add the window to the GUI
408 // note - this actually should happen regardless of raiseGUI
409 // status in Jalview 3
410 // TODO: define 'virtual desktop' for benefit of headless scripts
411 // that perform queries to find the 'current working alignment'
412 Desktop.addInternalFrame(alignFrame, title,
413 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
418 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
419 "SHOW_FULLSCREEN", false));
420 } catch (java.beans.PropertyVetoException ex)
427 if (Desktop.instance != null)
429 Desktop.instance.stopLoading();
432 final String errorMessage = MessageManager
433 .getString("label.couldnt_load_file")
437 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
439 if (raiseGUI && Desktop.desktop != null)
441 javax.swing.SwingUtilities.invokeLater(new Runnable()
445 JOptionPane.showInternalMessageDialog(Desktop.desktop,
446 errorMessage, MessageManager
447 .getString("label.error_loading_file"),
448 JOptionPane.WARNING_MESSAGE);
454 System.err.println(errorMessage);
459 updateRecentlyOpened();
461 } catch (Exception er)
463 System.err.println("Exception whilst opening file '" + file);
464 er.printStackTrace();
467 javax.swing.SwingUtilities.invokeLater(new Runnable()
471 javax.swing.JOptionPane.showInternalMessageDialog(
472 Desktop.desktop, MessageManager.formatMessage(
473 "label.problems_opening_file", new String[]
474 { file }), MessageManager
475 .getString("label.file_open_error"),
476 javax.swing.JOptionPane.WARNING_MESSAGE);
481 } catch (OutOfMemoryError er)
484 er.printStackTrace();
488 javax.swing.SwingUtilities.invokeLater(new Runnable()
492 javax.swing.JOptionPane.showInternalMessageDialog(
493 Desktop.desktop, MessageManager.formatMessage(
494 "warn.out_of_memory_loading_file", new String[]
495 { file }), MessageManager
496 .getString("label.out_of_memory"),
497 javax.swing.JOptionPane.WARNING_MESSAGE);
501 System.err.println("Out of memory loading file " + file + "!!");
504 loadtime += System.currentTimeMillis();
505 // TODO: Estimate percentage of memory used by a newly loaded alignment -
506 // warn if more memory will be needed to work with it
509 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
514 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
516 if (alignFrame != null)
518 AlignmentI al = alignFrame.getViewport().getAlignment();
520 System.out.println("Loaded '" + title + "' in "
521 + (loadtime / 1000.0) + "s, took an additional "
522 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
523 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
527 // report that we didn't load anything probably due to an out of memory
529 System.out.println("Failed to load '" + title + "' in "
530 + (loadtime / 1000.0) + "s, took an additional "
531 + (1.0 * memused / (1024.0 * 1024.0))
532 + " MB (alignment is null)");
535 // remove the visual delay indicator
536 if (Desktop.instance != null)
538 Desktop.instance.stopLoading();
546 * @see java.lang.Object#finalize()
548 protected void finalize() throws Throwable