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.json.binding.biojson.v1.ColourSchemeMapper;
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 = jalview.bin.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 jalview.bin.Cache.setProperty(type, newHistory.toString());
231 if (protocol.equals(FormatAdapter.FILE))
233 jalview.bin.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 null or unidentifiable data content!");
270 if (!Jalview.isHeadlessMode())
272 javax.swing.JOptionPane.showInternalMessageDialog(
274 MessageManager.getString("label.couldnt_read_data")
275 + " in " + file + "\n"
276 + AppletFormatAdapter.SUPPORTED_FORMATS,
277 MessageManager.getString("label.couldnt_read_data"),
278 JOptionPane.WARNING_MESSAGE);
282 // TODO: cache any stream datasources as a temporary file (eg. PDBs
283 // retrieved via URL)
284 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
287 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
292 loadtime = -System.currentTimeMillis();
293 AlignmentI al = null;
295 if (format.equalsIgnoreCase("Jalview"))
299 // Tell the user (developer?) that this is going to cause a problem
301 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
302 // We read the data anyway - it might make sense.
304 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
308 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
309 if (FormatAdapter.isValidFormat(format))
315 // read from the provided source
316 al = new FormatAdapter().readFromFile(source, format);
321 // open a new source and read from it
322 FormatAdapter fa = new FormatAdapter();
323 al = fa.readFile(file, protocol, format);
324 source = fa.getAlignFile(); // keep reference for later if
327 } catch (java.io.IOException ex)
329 error = ex.getMessage();
334 if (format != null && format.length() > 7)
336 // ad hoc message in format.
337 error = format + "\n" + error;
341 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
343 // construct and register dataset sequences
344 for (SequenceI sq : al.getSequences())
346 while (sq.getDatasetSequence() != null)
348 sq = sq.getDatasetSequence();
350 if (sq.getAllPDBEntries() != null)
352 for (PDBEntry pdbe : sq.getAllPDBEntries())
354 // register PDB entries with desktop's structure selection
356 StructureSelectionManager.getStructureSelectionManager(
357 Desktop.instance).registerPDBEntry(pdbe);
362 if (viewport != null)
364 // append to existing alignment
365 viewport.addAlignment(al, title);
369 // otherwise construct the alignFrame
371 if (source instanceof ComplexAlignFile)
373 ColumnSelection colSel = ((ComplexAlignFile) source)
374 .getColumnSelection();
375 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
376 .getHiddenSequences();
377 boolean showSeqFeatures = ((ComplexAlignFile) source)
378 .isShowSeqFeatures();
379 String colourSchemeName = ((ComplexAlignFile) source)
380 .getGlobalColourScheme();
381 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
382 .getDisplayedFeatures();
383 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
384 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
386 alignFrame.getViewport().setShowSequenceFeatures(
388 alignFrame.getViewport().setFeaturesDisplayed(fd);
389 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
390 colourSchemeName, al);
393 alignFrame.changeColour(cs);
398 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
399 AlignFrame.DEFAULT_HEIGHT);
401 // add metadata and update ui
402 if (!protocol.equals(AppletFormatAdapter.PASTE))
404 alignFrame.setFileName(file, format);
407 alignFrame.statusBar.setText(MessageManager.formatMessage(
408 "label.successfully_loaded_file",
409 new String[] { title }));
413 // add the window to the GUI
414 // note - this actually should happen regardless of raiseGUI
415 // status in Jalview 3
416 // TODO: define 'virtual desktop' for benefit of headless scripts
417 // that perform queries to find the 'current working alignment'
418 Desktop.addInternalFrame(alignFrame, title,
419 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
424 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
425 "SHOW_FULLSCREEN", false));
426 } catch (java.beans.PropertyVetoException ex)
433 if (Desktop.instance != null)
435 Desktop.instance.stopLoading();
438 final String errorMessage = MessageManager
439 .getString("label.couldnt_load_file")
443 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
445 if (raiseGUI && Desktop.desktop != null)
447 javax.swing.SwingUtilities.invokeLater(new Runnable()
451 JOptionPane.showInternalMessageDialog(Desktop.desktop,
452 errorMessage, MessageManager
453 .getString("label.error_loading_file"),
454 JOptionPane.WARNING_MESSAGE);
460 System.err.println(errorMessage);
465 updateRecentlyOpened();
467 } catch (Exception er)
469 System.err.println("Exception whilst opening file '" + file);
470 er.printStackTrace();
473 javax.swing.SwingUtilities.invokeLater(new Runnable()
477 javax.swing.JOptionPane.showInternalMessageDialog(
478 Desktop.desktop, MessageManager.formatMessage(
479 "label.problems_opening_file",
480 new String[] { file }), MessageManager
481 .getString("label.file_open_error"),
482 javax.swing.JOptionPane.WARNING_MESSAGE);
487 } catch (OutOfMemoryError er)
490 er.printStackTrace();
494 javax.swing.SwingUtilities.invokeLater(new Runnable()
498 javax.swing.JOptionPane.showInternalMessageDialog(
499 Desktop.desktop, MessageManager.formatMessage(
500 "warn.out_of_memory_loading_file", new String[]
501 { file }), MessageManager
502 .getString("label.out_of_memory"),
503 javax.swing.JOptionPane.WARNING_MESSAGE);
507 System.err.println("Out of memory loading file " + file + "!!");
510 loadtime += System.currentTimeMillis();
511 // TODO: Estimate percentage of memory used by a newly loaded alignment -
512 // warn if more memory will be needed to work with it
515 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
520 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
522 if (alignFrame != null)
524 AlignmentI al = alignFrame.getViewport().getAlignment();
526 System.out.println("Loaded '" + title + "' in "
527 + (loadtime / 1000.0) + "s, took an additional "
528 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
529 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
533 // report that we didn't load anything probably due to an out of memory
535 System.out.println("Failed to load '" + title + "' in "
536 + (loadtime / 1000.0) + "s, took an additional "
537 + (1.0 * memused / (1024.0 * 1024.0))
538 + " MB (alignment is null)");
541 // remove the visual delay indicator
542 if (Desktop.instance != null)
544 Desktop.instance.stopLoading();
552 * @see java.lang.Object#finalize()
554 protected void finalize() throws Throwable