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.FeatureSettingsModelI;
25 import jalview.api.FeaturesDisplayedI;
26 import jalview.api.FeaturesSourceI;
27 import jalview.bin.Jalview;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SequenceI;
32 import jalview.gui.AlignFrame;
33 import jalview.gui.AlignViewport;
34 import jalview.gui.Desktop;
35 import jalview.gui.Jalview2XML;
36 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.MessageManager;
41 import java.util.StringTokenizer;
42 import java.util.Vector;
44 import javax.swing.JOptionPane;
45 import javax.swing.SwingUtilities;
47 public class FileLoader implements Runnable
55 FileParse source = null; // alternative specification of where data comes
59 AlignViewport viewport;
61 AlignFrame alignFrame;
67 boolean raiseGUI = true;
70 * default constructor always raised errors in GUI dialog boxes
78 * construct a Fileloader that may raise errors non-interactively
81 * true if errors are to be raised as GUI dialog boxes
83 public FileLoader(boolean raiseGUI)
85 this.raiseGUI = raiseGUI;
88 public void LoadFile(AlignViewport viewport, String file,
89 String protocol, String format)
91 this.viewport = viewport;
92 LoadFile(file, protocol, format);
95 public void LoadFile(String file, String protocol, String format)
98 this.protocol = protocol;
101 final Thread loader = new Thread(this);
103 SwingUtilities.invokeLater(new Runnable()
114 * Load a (file, protocol) source of unknown type
119 public void LoadFile(String file, String protocol)
121 LoadFile(file, protocol, null);
125 * Load alignment from (file, protocol) and wait till loaded
129 * @return alignFrame constructed from file contents
131 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol)
133 return LoadFileWaitTillLoaded(file, protocol, null);
137 * Load alignment from (file, protocol) of type format and wait till loaded
142 * @return alignFrame constructed from file contents
144 public AlignFrame LoadFileWaitTillLoaded(String file, String protocol,
148 this.protocol = protocol;
149 this.format = format;
150 return _LoadFileWaitTillLoaded();
154 * Load alignment from FileParse source of type format and wait till loaded
158 * @return alignFrame constructed from file contents
160 public AlignFrame LoadFileWaitTillLoaded(FileParse source, String format)
162 this.source = source;
164 file = source.getInFile();
165 protocol = source.type;
166 this.format = format;
167 return _LoadFileWaitTillLoaded();
171 * start thread and wait until finished, then return the alignFrame that's
172 * (hopefully) been read.
176 protected AlignFrame _LoadFileWaitTillLoaded()
178 Thread loader = new Thread(this);
181 while (loader.isAlive())
186 } catch (Exception ex)
194 public void updateRecentlyOpened()
196 Vector recent = new Vector();
197 if (protocol.equals(FormatAdapter.PASTE))
199 // do nothing if the file was pasted in as text... there is no filename to
203 String type = protocol.equals(FormatAdapter.FILE) ? "RECENT_FILE"
206 String historyItems = jalview.bin.Cache.getProperty(type);
210 if (historyItems != null)
212 st = new StringTokenizer(historyItems, "\t");
214 while (st.hasMoreTokens())
216 recent.addElement(st.nextElement().toString().trim());
220 if (recent.contains(file))
225 StringBuffer newHistory = new StringBuffer(file);
226 for (int i = 0; i < recent.size() && i < 10; i++)
228 newHistory.append("\t");
229 newHistory.append(recent.elementAt(i));
232 jalview.bin.Cache.setProperty(type, newHistory.toString());
234 if (protocol.equals(FormatAdapter.FILE))
236 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT", format);
243 String title = protocol.equals(AppletFormatAdapter.PASTE) ? "Copied From Clipboard"
245 Runtime rt = Runtime.getRuntime();
248 if (Desktop.instance != null)
250 Desktop.instance.startLoading(file);
254 // just in case the caller didn't identify the file for us
257 format = new IdentifyFile().identify(source, false); // identify
264 format = new IdentifyFile().identify(file, protocol);
269 if (format == null || format.equalsIgnoreCase("EMPTY DATA FILE"))
271 Desktop.instance.stopLoading();
272 System.err.println("The input file \"" + file
273 + "\" has null or unidentifiable data content!");
274 if (!Jalview.isHeadlessMode())
276 javax.swing.JOptionPane.showInternalMessageDialog(
278 MessageManager.getString("label.couldnt_read_data")
279 + " in " + file + "\n"
280 + AppletFormatAdapter.SUPPORTED_FORMATS,
281 MessageManager.getString("label.couldnt_read_data"),
282 JOptionPane.WARNING_MESSAGE);
286 // TODO: cache any stream datasources as a temporary file (eg. PDBs
287 // retrieved via URL)
288 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
291 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
296 loadtime = -System.currentTimeMillis();
297 AlignmentI al = null;
299 if (format.equalsIgnoreCase("Jalview"))
303 // Tell the user (developer?) that this is going to cause a problem
305 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
306 // We read the data anyway - it might make sense.
308 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
312 String error = AppletFormatAdapter.SUPPORTED_FORMATS;
313 if (FormatAdapter.isValidFormat(format))
319 // read from the provided source
320 al = new FormatAdapter().readFromFile(source, format);
325 // open a new source and read from it
326 FormatAdapter fa = new FormatAdapter();
327 al = fa.readFile(file, protocol, format);
328 source = fa.getAlignFile(); // keep reference for later if
331 } catch (java.io.IOException ex)
333 error = ex.getMessage();
338 if (format != null && format.length() > 7)
340 // ad hoc message in format.
341 error = format + "\n" + error;
345 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
347 // construct and register dataset sequences
348 for (SequenceI sq : al.getSequences())
350 while (sq.getDatasetSequence() != null)
352 sq = sq.getDatasetSequence();
354 if (sq.getAllPDBEntries() != null)
356 for (PDBEntry pdbe : sq.getAllPDBEntries())
358 // register PDB entries with desktop's structure selection
360 StructureSelectionManager.getStructureSelectionManager(
361 Desktop.instance).registerPDBEntry(pdbe);
366 FeatureSettingsModelI proxyColourScheme = source
367 .getFeatureColourScheme();
368 if (viewport != null)
370 if (proxyColourScheme != null)
372 viewport.applyFeaturesStyle(proxyColourScheme);
374 // append to existing alignment
375 viewport.addAlignment(al, title);
379 // otherwise construct the alignFrame
381 if (source instanceof ComplexAlignFile)
383 ColumnSelection colSel = ((ComplexAlignFile) source)
384 .getColumnSelection();
385 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
386 .getHiddenSequences();
387 String colourSchemeName = ((ComplexAlignFile) source)
388 .getGlobalColourScheme();
389 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
390 .getDisplayedFeatures();
391 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
392 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
393 alignFrame.getViewport().setFeaturesDisplayed(fd);
394 alignFrame.getViewport().setShowSequenceFeatures(
395 ((ComplexAlignFile) source).isShowSeqFeatures());
396 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
397 colourSchemeName, al);
400 alignFrame.changeColour(cs);
405 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
406 AlignFrame.DEFAULT_HEIGHT);
407 if (source instanceof FeaturesSourceI)
409 alignFrame.getViewport().setShowSequenceFeatures(true);
412 // add metadata and update ui
413 if (!protocol.equals(AppletFormatAdapter.PASTE))
415 alignFrame.setFileName(file, format);
417 if (proxyColourScheme != null)
419 alignFrame.getViewport()
420 .applyFeaturesStyle(proxyColourScheme);
422 alignFrame.statusBar.setText(MessageManager.formatMessage(
423 "label.successfully_loaded_file",
424 new String[] { title }));
428 // add the window to the GUI
429 // note - this actually should happen regardless of raiseGUI
430 // status in Jalview 3
431 // TODO: define 'virtual desktop' for benefit of headless scripts
432 // that perform queries to find the 'current working alignment'
433 Desktop.addInternalFrame(alignFrame, title,
434 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
439 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
440 "SHOW_FULLSCREEN", false));
441 } catch (java.beans.PropertyVetoException ex)
448 if (Desktop.instance != null)
450 Desktop.instance.stopLoading();
453 final String errorMessage = MessageManager
454 .getString("label.couldnt_load_file")
458 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
460 if (raiseGUI && Desktop.desktop != null)
462 javax.swing.SwingUtilities.invokeLater(new Runnable()
467 JOptionPane.showInternalMessageDialog(Desktop.desktop,
468 errorMessage, MessageManager
469 .getString("label.error_loading_file"),
470 JOptionPane.WARNING_MESSAGE);
476 System.err.println(errorMessage);
481 updateRecentlyOpened();
483 } catch (Exception er)
485 System.err.println("Exception whilst opening file '" + file);
486 er.printStackTrace();
489 javax.swing.SwingUtilities.invokeLater(new Runnable()
494 javax.swing.JOptionPane.showInternalMessageDialog(
495 Desktop.desktop, MessageManager.formatMessage(
496 "label.problems_opening_file",
497 new String[] { file }), MessageManager
498 .getString("label.file_open_error"),
499 javax.swing.JOptionPane.WARNING_MESSAGE);
504 } catch (OutOfMemoryError er)
507 er.printStackTrace();
511 javax.swing.SwingUtilities.invokeLater(new Runnable()
516 javax.swing.JOptionPane.showInternalMessageDialog(
517 Desktop.desktop, MessageManager.formatMessage(
518 "warn.out_of_memory_loading_file", new String[]
519 { file }), MessageManager
520 .getString("label.out_of_memory"),
521 javax.swing.JOptionPane.WARNING_MESSAGE);
525 System.err.println("Out of memory loading file " + file + "!!");
528 loadtime += System.currentTimeMillis();
529 // TODO: Estimate percentage of memory used by a newly loaded alignment -
530 // warn if more memory will be needed to work with it
533 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
538 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
540 if (alignFrame != null)
542 AlignmentI al = alignFrame.getViewport().getAlignment();
544 System.out.println("Loaded '" + title + "' in "
545 + (loadtime / 1000.0) + "s, took an additional "
546 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
547 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
551 // report that we didn't load anything probably due to an out of memory
553 System.out.println("Failed to load '" + title + "' in "
554 + (loadtime / 1000.0) + "s, took an additional "
555 + (1.0 * memused / (1024.0 * 1024.0))
556 + " MB (alignment is null)");
559 // remove the visual delay indicator
560 if (Desktop.instance != null)
562 Desktop.instance.stopLoading();
570 * @see java.lang.Object#finalize()
573 protected void finalize() throws Throwable