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.Cache;
28 import jalview.bin.Jalview;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.ColumnSelection;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.AlignViewport;
35 import jalview.gui.Desktop;
36 import jalview.gui.Jalview2XML;
37 import jalview.gui.JvOptionPane;
38 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
39 import jalview.schemes.ColourSchemeI;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.ws.utils.UrlDownloadClient;
44 import java.nio.file.Files;
45 import java.util.StringTokenizer;
46 import java.util.Vector;
48 import javax.swing.SwingUtilities;
50 public class FileLoader implements Runnable
54 DataSourceType protocol;
58 AlignmentFileReaderI source = null; // alternative specification of where data
63 AlignViewport viewport;
65 AlignFrame alignFrame;
71 boolean raiseGUI = true;
74 * default constructor always raised errors in GUI dialog boxes
82 * construct a Fileloader that may raise errors non-interactively
85 * true if errors are to be raised as GUI dialog boxes
87 public FileLoader(boolean raiseGUI)
89 this.raiseGUI = raiseGUI;
92 public void LoadFile(AlignViewport viewport, String file,
93 DataSourceType protocol, FileFormatI format)
95 this.viewport = viewport;
96 LoadFile(file, protocol, format);
99 public void LoadFile(String file, DataSourceType protocol,
103 this.protocol = protocol;
104 this.format = format;
106 final Thread loader = new Thread(this);
108 SwingUtilities.invokeLater(new Runnable()
119 * Load a (file, protocol) source of unknown type
124 public void LoadFile(String file, DataSourceType protocol)
126 LoadFile(file, protocol, null);
130 * Load alignment from (file, protocol) and wait till loaded
134 * @return alignFrame constructed from file contents
136 public AlignFrame LoadFileWaitTillLoaded(String file,
137 DataSourceType sourceType)
139 return LoadFileWaitTillLoaded(file, sourceType, null);
143 * Load alignment from (file, protocol) of type format and wait till loaded
148 * @return alignFrame constructed from file contents
150 public AlignFrame LoadFileWaitTillLoaded(String file,
151 DataSourceType sourceType, FileFormatI format)
154 this.protocol = sourceType;
155 this.format = format;
156 return _LoadFileWaitTillLoaded();
160 * Load alignment from FileParse source of type format and wait till loaded
164 * @return alignFrame constructed from file contents
166 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
169 this.source = source;
171 file = source.getInFile();
172 protocol = source.getDataSourceType();
173 this.format = format;
174 return _LoadFileWaitTillLoaded();
178 * start thread and wait until finished, then return the alignFrame that's
179 * (hopefully) been read.
183 protected AlignFrame _LoadFileWaitTillLoaded()
185 Thread loader = new Thread(this);
188 while (loader.isAlive())
193 } catch (Exception ex)
201 public void updateRecentlyOpened()
203 Vector recent = new Vector();
204 if (protocol == DataSourceType.PASTE)
206 // do nothing if the file was pasted in as text... there is no filename to
210 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
213 String historyItems = jalview.bin.Cache.getProperty(type);
217 if (historyItems != null)
219 st = new StringTokenizer(historyItems, "\t");
221 while (st.hasMoreTokens())
223 recent.addElement(st.nextElement().toString().trim());
227 if (recent.contains(file))
232 StringBuffer newHistory = new StringBuffer(file);
233 for (int i = 0; i < recent.size() && i < 10; i++)
235 newHistory.append("\t");
236 newHistory.append(recent.elementAt(i));
239 Cache.setProperty(type, newHistory.toString());
241 if (protocol == DataSourceType.FILE)
243 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
250 String title = protocol == DataSourceType.PASTE ? "Copied From Clipboard"
252 Runtime rt = Runtime.getRuntime();
255 if (Desktop.instance != null)
257 Desktop.instance.startLoading(file);
261 // just in case the caller didn't identify the file for us
264 format = new IdentifyFile().identify(source, false);
265 // identify stream and rewind rather than close
269 format = new IdentifyFile().identify(file, protocol);
276 Desktop.instance.stopLoading();
277 System.err.println("The input file \"" + file
278 + "\" has null or unidentifiable data content!");
279 if (!Jalview.isHeadlessMode())
281 JvOptionPane.showInternalMessageDialog(
283 MessageManager.getString("label.couldnt_read_data")
284 + " in " + file + "\n"
285 + AppletFormatAdapter.getSupportedFormats(),
286 MessageManager.getString("label.couldnt_read_data"),
287 JvOptionPane.WARNING_MESSAGE);
291 // TODO: cache any stream datasources as a temporary file (eg. PDBs
292 // retrieved via URL)
293 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
296 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
301 loadtime = -System.currentTimeMillis();
302 AlignmentI al = null;
304 if (FileFormat.Jalview.equals(format))
308 // Tell the user (developer?) that this is going to cause a problem
310 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
311 // We read the data anyway - it might make sense.
313 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
317 String error = AppletFormatAdapter.getSupportedFormats();
322 // read from the provided source
323 al = new FormatAdapter().readFromFile(source, format);
328 // open a new source and read from it
329 FormatAdapter fa = new FormatAdapter();
330 boolean downloadStructureFile = format.isStructureFile()
331 && protocol.equals(DataSourceType.URL);
332 if (downloadStructureFile)
334 String structExt = format.getExtensions().split(",")[0];
335 String tempStructurefile = Files.createTempFile(".jalview_",
336 "." + structExt).toString();
337 UrlDownloadClient.download(file, tempStructurefile);
338 file = tempStructurefile;
339 protocol = DataSourceType.FILE;
341 al = fa.readFile(file, protocol, format);
342 source = fa.getAlignFile(); // keep reference for later if
345 } catch (java.io.IOException ex)
347 error = ex.getMessage();
350 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
352 // construct and register dataset sequences
353 for (SequenceI sq : al.getSequences())
355 while (sq.getDatasetSequence() != null)
357 sq = sq.getDatasetSequence();
359 if (sq.getAllPDBEntries() != null)
361 for (PDBEntry pdbe : sq.getAllPDBEntries())
363 // register PDB entries with desktop's structure selection
365 StructureSelectionManager.getStructureSelectionManager(
366 Desktop.instance).registerPDBEntry(pdbe);
371 FeatureSettingsModelI proxyColourScheme = source
372 .getFeatureColourScheme();
373 if (viewport != null)
375 if (proxyColourScheme != null)
377 viewport.applyFeaturesStyle(proxyColourScheme);
379 // append to existing alignment
380 viewport.addAlignment(al, title);
384 // otherwise construct the alignFrame
386 if (source instanceof ComplexAlignFile)
388 ColumnSelection colSel = ((ComplexAlignFile) source)
389 .getColumnSelection();
390 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
391 .getHiddenSequences();
392 String colourSchemeName = ((ComplexAlignFile) source)
393 .getGlobalColourScheme();
394 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
395 .getDisplayedFeatures();
396 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
397 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
398 alignFrame.getViewport().setFeaturesDisplayed(fd);
399 alignFrame.getViewport().setShowSequenceFeatures(
400 ((ComplexAlignFile) source).isShowSeqFeatures());
401 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
402 colourSchemeName, al);
405 alignFrame.changeColour(cs);
410 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
411 AlignFrame.DEFAULT_HEIGHT);
412 if (source instanceof FeaturesSourceI)
414 alignFrame.getViewport().setShowSequenceFeatures(true);
417 // add metadata and update ui
418 if (!(protocol == DataSourceType.PASTE))
420 alignFrame.setFileName(file, format);
422 if (proxyColourScheme != null)
424 alignFrame.getViewport()
425 .applyFeaturesStyle(proxyColourScheme);
427 alignFrame.statusBar.setText(MessageManager.formatMessage(
428 "label.successfully_loaded_file",
429 new String[] { title }));
433 // add the window to the GUI
434 // note - this actually should happen regardless of raiseGUI
435 // status in Jalview 3
436 // TODO: define 'virtual desktop' for benefit of headless scripts
437 // that perform queries to find the 'current working alignment'
438 Desktop.addInternalFrame(alignFrame, title,
439 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
444 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
445 "SHOW_FULLSCREEN", false));
446 } catch (java.beans.PropertyVetoException ex)
453 if (Desktop.instance != null)
455 Desktop.instance.stopLoading();
458 final String errorMessage = MessageManager
459 .getString("label.couldnt_load_file")
463 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
465 if (raiseGUI && Desktop.desktop != null)
467 javax.swing.SwingUtilities.invokeLater(new Runnable()
472 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
473 errorMessage, MessageManager
474 .getString("label.error_loading_file"),
475 JvOptionPane.WARNING_MESSAGE);
481 System.err.println(errorMessage);
486 updateRecentlyOpened();
488 } catch (Exception er)
490 System.err.println("Exception whilst opening file '" + file);
491 er.printStackTrace();
494 javax.swing.SwingUtilities.invokeLater(new Runnable()
499 JvOptionPane.showInternalMessageDialog(
500 Desktop.desktop, MessageManager.formatMessage(
501 "label.problems_opening_file",
502 new String[] { file }), MessageManager
503 .getString("label.file_open_error"),
504 JvOptionPane.WARNING_MESSAGE);
509 } catch (OutOfMemoryError er)
512 er.printStackTrace();
516 javax.swing.SwingUtilities.invokeLater(new Runnable()
521 JvOptionPane.showInternalMessageDialog(
522 Desktop.desktop, MessageManager.formatMessage(
523 "warn.out_of_memory_loading_file", new String[]
524 { file }), MessageManager
525 .getString("label.out_of_memory"),
526 JvOptionPane.WARNING_MESSAGE);
530 System.err.println("Out of memory loading file " + file + "!!");
533 loadtime += System.currentTimeMillis();
534 // TODO: Estimate percentage of memory used by a newly loaded alignment -
535 // warn if more memory will be needed to work with it
538 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
543 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
545 if (alignFrame != null)
547 AlignmentI al = alignFrame.getViewport().getAlignment();
549 System.out.println("Loaded '" + title + "' in "
550 + (loadtime / 1000.0) + "s, took an additional "
551 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
552 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
556 // report that we didn't load anything probably due to an out of memory
558 System.out.println("Failed to load '" + title + "' in "
559 + (loadtime / 1000.0) + "s, took an additional "
560 + (1.0 * memused / (1024.0 * 1024.0))
561 + " MB (alignment is null)");
564 // remove the visual delay indicator
565 if (Desktop.instance != null)
567 Desktop.instance.stopLoading();
575 * @see java.lang.Object#finalize()
578 protected void finalize() throws Throwable