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.HiddenColumns;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.AlignViewport;
35 import jalview.gui.BamFileOptionsChooser;
36 import jalview.gui.Desktop;
37 import jalview.gui.Jalview2XML;
38 import jalview.gui.JvOptionPane;
39 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
40 import jalview.schemes.ColourSchemeI;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.util.MessageManager;
43 import jalview.ws.utils.UrlDownloadClient;
46 import java.io.IOException;
47 import java.util.StringTokenizer;
48 import java.util.Vector;
50 import javax.swing.SwingUtilities;
52 public class FileLoader implements Runnable
56 DataSourceType protocol;
60 AlignmentFileReaderI source = null; // alternative specification of where data
65 AlignViewport viewport;
67 AlignFrame alignFrame;
73 boolean raiseGUI = true;
76 * default constructor always raised errors in GUI dialog boxes
84 * construct a Fileloader that may raise errors non-interactively
87 * true if errors are to be raised as GUI dialog boxes
89 public FileLoader(boolean raiseGUI)
91 this.raiseGUI = raiseGUI;
94 public void LoadFile(AlignViewport viewport, String file,
95 DataSourceType protocol, FileFormatI format)
97 this.viewport = viewport;
98 LoadFile(file, protocol, format);
101 public void LoadFile(String file, DataSourceType protocol,
105 this.protocol = protocol;
106 this.format = format;
108 final Thread loader = new Thread(this);
110 SwingUtilities.invokeLater(new Runnable()
121 * Load a (file, protocol) source of unknown type
126 public void LoadFile(String file, DataSourceType protocol)
128 LoadFile(file, protocol, null);
132 * Load alignment from (file, protocol) and wait till loaded
136 * @return alignFrame constructed from file contents
138 public AlignFrame LoadFileWaitTillLoaded(String file,
139 DataSourceType sourceType)
141 return LoadFileWaitTillLoaded(file, sourceType, null);
145 * Load alignment from (file, protocol) of type format and wait till loaded
150 * @return alignFrame constructed from file contents
152 public AlignFrame LoadFileWaitTillLoaded(String file,
153 DataSourceType sourceType, FileFormatI format)
156 this.protocol = sourceType;
157 this.format = format;
158 return _LoadFileWaitTillLoaded();
162 * Load alignment from FileParse source of type format and wait till loaded
166 * @return alignFrame constructed from file contents
168 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
171 this.source = source;
173 file = source.getInFile();
174 protocol = source.getDataSourceType();
175 this.format = format;
176 return _LoadFileWaitTillLoaded();
180 * start thread and wait until finished, then return the alignFrame that's
181 * (hopefully) been read.
185 protected AlignFrame _LoadFileWaitTillLoaded()
187 Thread loader = new Thread(this);
190 while (loader.isAlive())
195 } catch (Exception ex)
203 public void updateRecentlyOpened()
205 Vector recent = new Vector();
206 if (protocol == DataSourceType.PASTE)
208 // do nothing if the file was pasted in as text... there is no filename to
213 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
215 // ignore files loaded from the system's temporary directory
218 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
221 String historyItems = jalview.bin.Cache.getProperty(type);
225 if (historyItems != null)
227 st = new StringTokenizer(historyItems, "\t");
229 while (st.hasMoreTokens())
231 recent.addElement(st.nextElement().toString().trim());
235 if (recent.contains(file))
240 StringBuffer newHistory = new StringBuffer(file);
241 for (int i = 0; i < recent.size() && i < 10; i++)
243 newHistory.append("\t");
244 newHistory.append(recent.elementAt(i));
247 Cache.setProperty(type, newHistory.toString());
249 if (protocol == DataSourceType.FILE)
251 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
258 String title = protocol == DataSourceType.PASTE
259 ? "Copied From Clipboard"
261 Runtime rt = Runtime.getRuntime();
264 if (Desktop.instance != null)
266 Desktop.instance.startLoading(file);
270 // just in case the caller didn't identify the file for us
273 format = new IdentifyFile().identify(source, false);
274 // identify stream and rewind rather than close
278 format = new IdentifyFile().identify(file, protocol);
285 Desktop.instance.stopLoading();
286 System.err.println("The input file \"" + file
287 + "\" has null or unidentifiable data content!");
288 if (!Jalview.isHeadlessMode())
290 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
291 MessageManager.getString("label.couldnt_read_data")
292 + " in " + file + "\n"
293 + AppletFormatAdapter.getSupportedFormats(),
294 MessageManager.getString("label.couldnt_read_data"),
295 JvOptionPane.WARNING_MESSAGE);
299 // TODO: cache any stream datasources as a temporary file (eg. PDBs
300 // retrieved via URL)
301 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
304 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
309 loadtime = -System.currentTimeMillis();
310 AlignmentI al = null;
312 if (FileFormat.Bam.equals(format))
314 FormatAdapter fa = new FormatAdapter();
317 fa.prepareFileReader(file, protocol, format);
318 source = fa.getAlignFile();
321 BamFileOptionsChooser bamoptions = new BamFileOptionsChooser(
324 // ask the user which bit of the bam they want to load
325 int confirm = JvOptionPane.showConfirmDialog(null,
327 MessageManager.getString("label.bam_file_options"),
328 JvOptionPane.OK_CANCEL_OPTION,
329 JvOptionPane.PLAIN_MESSAGE);
331 if (confirm == JvOptionPane.CANCEL_OPTION
332 || confirm == JvOptionPane.CLOSED_OPTION)
334 Desktop.instance.stopLoading();
339 bamoptions.update(source);
340 al = fa.readFile(file, protocol, format);
344 if (FileFormat.Jalview.equals(format))
348 // Tell the user (developer?) that this is going to cause a problem
350 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
351 // We read the data anyway - it might make sense.
353 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
357 String error = AppletFormatAdapter.getSupportedFormats();
364 // read from the provided source
365 al = new FormatAdapter().readFromFile(source, format);
370 // open a new source and read from it
371 FormatAdapter fa = new FormatAdapter();
372 boolean downloadStructureFile = format.isStructureFile()
373 && protocol.equals(DataSourceType.URL);
374 if (downloadStructureFile)
376 String structExt = format.getExtensions().split(",")[0];
377 String urlLeafName = file.substring(
379 System.getProperty("file.separator")),
380 file.lastIndexOf("."));
381 String tempStructureFileStr = createNamedJvTempFile(
382 urlLeafName, structExt);
383 UrlDownloadClient.download(file, tempStructureFileStr);
384 al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
386 source = fa.getAlignFile();
390 al = fa.readFile(file, protocol, format);
391 source = fa.getAlignFile(); // keep reference for later if
396 } catch (java.io.IOException ex)
398 error = ex.getMessage();
401 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
403 // construct and register dataset sequences
404 for (SequenceI sq : al.getSequences())
406 while (sq.getDatasetSequence() != null)
408 sq = sq.getDatasetSequence();
410 if (sq.getAllPDBEntries() != null)
412 for (PDBEntry pdbe : sq.getAllPDBEntries())
414 // register PDB entries with desktop's structure selection
416 StructureSelectionManager
417 .getStructureSelectionManager(Desktop.instance)
418 .registerPDBEntry(pdbe);
423 FeatureSettingsModelI proxyColourScheme = source
424 .getFeatureColourScheme();
425 if (viewport != null)
427 if (proxyColourScheme != null)
429 viewport.applyFeaturesStyle(proxyColourScheme);
431 // append to existing alignment
432 viewport.addAlignment(al, title);
436 // otherwise construct the alignFrame
438 if (source instanceof ComplexAlignFile)
440 HiddenColumns colSel = ((ComplexAlignFile) source)
442 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
443 .getHiddenSequences();
444 String colourSchemeName = ((ComplexAlignFile) source)
445 .getGlobalColourScheme();
446 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
447 .getDisplayedFeatures();
448 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
449 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
450 alignFrame.getViewport().setFeaturesDisplayed(fd);
451 alignFrame.getViewport().setShowSequenceFeatures(
452 ((ComplexAlignFile) source).isShowSeqFeatures());
453 ColourSchemeI cs = ColourSchemeMapper
454 .getJalviewColourScheme(colourSchemeName, al);
457 alignFrame.changeColour(cs);
462 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
463 AlignFrame.DEFAULT_HEIGHT);
464 if (source instanceof FeaturesSourceI)
466 alignFrame.getViewport().setShowSequenceFeatures(true);
469 // add metadata and update ui
470 if (!(protocol == DataSourceType.PASTE))
472 alignFrame.setFileName(file, format);
474 if (proxyColourScheme != null)
476 alignFrame.getViewport()
477 .applyFeaturesStyle(proxyColourScheme);
479 alignFrame.statusBar.setText(MessageManager.formatMessage(
480 "label.successfully_loaded_file", new String[]
485 // add the window to the GUI
486 // note - this actually should happen regardless of raiseGUI
487 // status in Jalview 3
488 // TODO: define 'virtual desktop' for benefit of headless scripts
489 // that perform queries to find the 'current working alignment'
490 Desktop.addInternalFrame(alignFrame, title,
491 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
496 alignFrame.setMaximum(jalview.bin.Cache
497 .getDefault("SHOW_FULLSCREEN", false));
498 } catch (java.beans.PropertyVetoException ex)
505 if (Desktop.instance != null)
507 Desktop.instance.stopLoading();
510 final String errorMessage = MessageManager.getString(
511 "label.couldnt_load_file") + " " + title + "\n" + error;
512 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
514 if (raiseGUI && Desktop.desktop != null)
516 javax.swing.SwingUtilities.invokeLater(new Runnable()
521 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
524 .getString("label.error_loading_file"),
525 JvOptionPane.WARNING_MESSAGE);
531 System.err.println(errorMessage);
536 updateRecentlyOpened();
538 } catch (Exception er)
540 System.err.println("Exception whilst opening file '" + file);
541 er.printStackTrace();
544 javax.swing.SwingUtilities.invokeLater(new Runnable()
549 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
550 MessageManager.formatMessage(
551 "label.problems_opening_file", new String[]
553 MessageManager.getString("label.file_open_error"),
554 JvOptionPane.WARNING_MESSAGE);
559 } catch (OutOfMemoryError er)
562 er.printStackTrace();
566 javax.swing.SwingUtilities.invokeLater(new Runnable()
571 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
572 MessageManager.formatMessage(
573 "warn.out_of_memory_loading_file", new String[]
575 MessageManager.getString("label.out_of_memory"),
576 JvOptionPane.WARNING_MESSAGE);
580 System.err.println("Out of memory loading file " + file + "!!");
583 loadtime += System.currentTimeMillis();
584 // TODO: Estimate percentage of memory used by a newly loaded alignment -
585 // warn if more memory will be needed to work with it
588 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
593 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
595 if (alignFrame != null)
597 AlignmentI al = alignFrame.getViewport().getAlignment();
599 System.out.println("Loaded '" + title + "' in "
600 + (loadtime / 1000.0) + "s, took an additional "
601 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
602 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
606 // report that we didn't load anything probably due to an out of memory
608 System.out.println("Failed to load '" + title + "' in "
609 + (loadtime / 1000.0) + "s, took an additional "
610 + (1.0 * memused / (1024.0 * 1024.0))
611 + " MB (alignment is null)");
614 // remove the visual delay indicator
615 if (Desktop.instance != null)
617 Desktop.instance.stopLoading();
623 * This method creates the file -
624 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
625 * file name and extension
628 * the name of the temp file to be created
630 * the extension of the temp file to be created
633 private static String createNamedJvTempFile(String fileName,
634 String extension) throws IOException
636 String seprator = System.getProperty("file.separator");
637 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
638 + seprator + System.currentTimeMillis();
639 File tempStructFile = new File(
640 jvTempDir + seprator + fileName + "." + extension);
641 tempStructFile.mkdirs();
642 return tempStructFile.toString();