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.Profile;
33 import jalview.datamodel.Profiles;
34 import jalview.datamodel.SequenceGroup;
35 import jalview.datamodel.SequenceI;
36 import jalview.gui.AlignFrame;
37 import jalview.gui.AlignViewport;
38 import jalview.gui.Desktop;
39 import jalview.gui.Jalview2XML;
40 import jalview.gui.JvOptionPane;
41 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
42 import jalview.schemes.ColourSchemeI;
43 import jalview.structure.StructureSelectionManager;
44 import jalview.util.MessageManager;
45 import jalview.ws.utils.UrlDownloadClient;
48 import java.io.IOException;
49 import java.util.StringTokenizer;
50 import java.util.Vector;
52 import javax.swing.SwingUtilities;
54 public class FileLoader implements Runnable
58 DataSourceType protocol;
62 AlignmentFileReaderI source = null; // alternative specification of where data
67 AlignViewport viewport;
69 AlignFrame alignFrame;
75 boolean raiseGUI = true;
78 * default constructor always raised errors in GUI dialog boxes
86 * construct a Fileloader that may raise errors non-interactively
89 * true if errors are to be raised as GUI dialog boxes
91 public FileLoader(boolean raiseGUI)
93 this.raiseGUI = raiseGUI;
96 public void LoadFile(AlignViewport viewport, String file,
97 DataSourceType protocol, FileFormatI format)
99 this.viewport = viewport;
100 LoadFile(file, protocol, format);
103 public void LoadFile(String file, DataSourceType protocol,
107 this.protocol = protocol;
108 this.format = format;
110 final Thread loader = new Thread(this);
112 SwingUtilities.invokeLater(new Runnable()
123 * Load a (file, protocol) source of unknown type
128 public void LoadFile(String file, DataSourceType protocol)
130 LoadFile(file, protocol, null);
134 * Load alignment from (file, protocol) and wait till loaded
138 * @return alignFrame constructed from file contents
140 public AlignFrame LoadFileWaitTillLoaded(String file,
141 DataSourceType sourceType)
143 return LoadFileWaitTillLoaded(file, sourceType, null);
147 * Load alignment from (file, protocol) of type format and wait till loaded
152 * @return alignFrame constructed from file contents
154 public AlignFrame LoadFileWaitTillLoaded(String file,
155 DataSourceType sourceType, FileFormatI format)
158 this.protocol = sourceType;
159 this.format = format;
160 return _LoadFileWaitTillLoaded();
164 * Load alignment from FileParse source of type format and wait till loaded
168 * @return alignFrame constructed from file contents
170 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
173 this.source = source;
175 file = source.getInFile();
176 protocol = source.getDataSourceType();
177 this.format = format;
178 return _LoadFileWaitTillLoaded();
182 * start thread and wait until finished, then return the alignFrame that's
183 * (hopefully) been read.
187 protected AlignFrame _LoadFileWaitTillLoaded()
189 Thread loader = new Thread(this);
192 while (loader.isAlive())
197 } catch (Exception ex)
205 public void LoadFileOntoAlignmentWaitTillLoaded(AlignViewport viewport,
206 String file, DataSourceType sourceType, FileFormatI format)
208 this.viewport = viewport;
210 this.protocol = sourceType;
211 this.format = format;
212 _LoadAlignmentFileWaitTillLoaded();
215 protected void _LoadAlignmentFileWaitTillLoaded()
217 Thread loader = new Thread(this);
220 while (loader.isAlive())
225 } catch (Exception ex)
231 public void updateRecentlyOpened()
233 Vector recent = new Vector();
234 if (protocol == DataSourceType.PASTE)
236 // do nothing if the file was pasted in as text... there is no filename to
241 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
243 // ignore files loaded from the system's temporary directory
246 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
249 String historyItems = jalview.bin.Cache.getProperty(type);
253 if (historyItems != null)
255 st = new StringTokenizer(historyItems, "\t");
257 while (st.hasMoreTokens())
259 recent.addElement(st.nextElement().toString().trim());
263 if (recent.contains(file))
268 StringBuffer newHistory = new StringBuffer(file);
269 for (int i = 0; i < recent.size() && i < 10; i++)
271 newHistory.append("\t");
272 newHistory.append(recent.elementAt(i));
275 Cache.setProperty(type, newHistory.toString());
277 if (protocol == DataSourceType.FILE)
279 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
286 String title = protocol == DataSourceType.PASTE ? "Copied From Clipboard"
288 Runtime rt = Runtime.getRuntime();
291 if (Desktop.instance != null)
293 Desktop.instance.startLoading(file);
297 // just in case the caller didn't identify the file for us
300 format = new IdentifyFile().identify(source, false);
301 // identify stream and rewind rather than close
305 format = new IdentifyFile().identify(file, protocol);
312 Desktop.instance.stopLoading();
313 System.err.println("The input file \"" + file
314 + "\" has null or unidentifiable data content!");
315 if (!Jalview.isHeadlessMode())
317 JvOptionPane.showInternalMessageDialog(
319 MessageManager.getString("label.couldnt_read_data")
320 + " in " + file + "\n"
321 + AppletFormatAdapter.getSupportedFormats(),
322 MessageManager.getString("label.couldnt_read_data"),
323 JvOptionPane.WARNING_MESSAGE);
327 // TODO: cache any stream datasources as a temporary file (eg. PDBs
328 // retrieved via URL)
329 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
332 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
337 loadtime = -System.currentTimeMillis();
338 AlignmentI al = null;
340 if (FileFormat.Jalview.equals(format))
344 // Tell the user (developer?) that this is going to cause a problem
346 .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
347 // We read the data anyway - it might make sense.
349 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
353 String error = AppletFormatAdapter.getSupportedFormats();
358 // read from the provided source
359 al = new FormatAdapter().readFromFile(source, format);
364 // open a new source and read from it
365 FormatAdapter fa = new FormatAdapter();
366 boolean downloadStructureFile = format.isStructureFile()
367 && protocol.equals(DataSourceType.URL);
368 if (downloadStructureFile)
370 String structExt = format.getExtensions().split(",")[0];
371 String urlLeafName = file.substring(file.lastIndexOf(System
372 .getProperty("file.separator")), file
374 String tempStructureFileStr = createNamedJvTempFile(
375 urlLeafName, structExt);
376 UrlDownloadClient.download(file, tempStructureFileStr);
377 al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
379 source = fa.getAlignFile();
383 al = fa.readFile(file, protocol, format);
384 source = fa.getAlignFile(); // keep reference for later if
388 } catch (java.io.IOException ex)
390 error = ex.getMessage();
393 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
395 // construct and register dataset sequences
396 for (SequenceI sq : al.getSequences())
398 while (sq.getDatasetSequence() != null)
400 sq = sq.getDatasetSequence();
402 if (sq.getAllPDBEntries() != null)
404 for (PDBEntry pdbe : sq.getAllPDBEntries())
406 // register PDB entries with desktop's structure selection
408 StructureSelectionManager.getStructureSelectionManager(
409 Desktop.instance).registerPDBEntry(pdbe);
414 FeatureSettingsModelI proxyColourScheme = source
415 .getFeatureColourScheme();
416 if (viewport != null)
418 if (proxyColourScheme != null)
420 viewport.applyFeaturesStyle(proxyColourScheme);
422 // append to existing alignment
423 viewport.addAlignment(al, title);
424 if (source instanceof HMMFile)
426 AlignmentI alignment = viewport.getAlignment();
427 SequenceI seq = alignment
428 .getSequenceAt(alignment.getAbsoluteHeight() - 1);
429 alignment.deleteSequence(alignment.getAbsoluteHeight() - 1);
430 SequenceGroup sg = viewport.getSelectionGroup();
433 seq.insertCharAt(0, sg.getStartRes(), '-');
434 seq.insertCharAt(sg.getEndRes() + 1,
435 alignment.getWidth() - sg.getEndRes(), '-');
436 SequenceI topSeq = sg.getSequencesInOrder(alignment)[0];
437 int topIndex = alignment.findIndex(topSeq);
438 alignment.insertSequenceAt(topIndex, seq);
440 viewport.getSelectionGroup().addSequence(seq, false);
444 alignment.insertSequenceAt(0, seq);
446 viewport.initInformation();
447 viewport.setSequenceInformationHash(
448 new Profiles(new Profile[1]), 0);
449 viewport.updateInformation(viewport.getAlignPanel());
450 viewport.getAlignPanel().adjustAnnotationHeight();
451 viewport.updateSequenceIdColours();
452 if (viewport.getAlignPanel().alignFrame
453 .getSelectedHMM() == null)
455 viewport.getAlignPanel().alignFrame
456 .setSelectedHMM(seq.getHMM());
458 viewport.alignmentChanged(viewport.getAlignPanel());
464 // otherwise construct the alignFrame
466 if (source instanceof ComplexAlignFile)
468 HiddenColumns colSel = ((ComplexAlignFile) source)
470 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
471 .getHiddenSequences();
472 String colourSchemeName = ((ComplexAlignFile) source)
473 .getGlobalColourScheme();
474 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
475 .getDisplayedFeatures();
476 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
477 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
478 alignFrame.getViewport().setFeaturesDisplayed(fd);
479 alignFrame.getViewport().setShowSequenceFeatures(
480 ((ComplexAlignFile) source).isShowSeqFeatures());
481 ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
482 colourSchemeName, al);
485 alignFrame.changeColour(cs);
490 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
491 AlignFrame.DEFAULT_HEIGHT);
492 if (source instanceof FeaturesSourceI)
494 alignFrame.getViewport().setShowSequenceFeatures(true);
497 // add metadata and update ui
498 if (!(protocol == DataSourceType.PASTE))
500 alignFrame.setFileName(file, format);
502 if (proxyColourScheme != null)
504 alignFrame.getViewport()
505 .applyFeaturesStyle(proxyColourScheme);
507 alignFrame.statusBar.setText(MessageManager.formatMessage(
508 "label.successfully_loaded_file",
509 new String[] { title }));
513 // add the window to the GUI
514 // note - this actually should happen regardless of raiseGUI
515 // status in Jalview 3
516 // TODO: define 'virtual desktop' for benefit of headless scripts
517 // that perform queries to find the 'current working alignment'
518 Desktop.addInternalFrame(alignFrame, title,
519 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
524 alignFrame.setMaximum(jalview.bin.Cache.getDefault(
525 "SHOW_FULLSCREEN", false));
526 } catch (java.beans.PropertyVetoException ex)
533 if (Desktop.instance != null)
535 Desktop.instance.stopLoading();
538 final String errorMessage = MessageManager
539 .getString("label.couldnt_load_file")
543 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
545 if (raiseGUI && Desktop.desktop != null)
547 javax.swing.SwingUtilities.invokeLater(new Runnable()
552 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
553 errorMessage, MessageManager
554 .getString("label.error_loading_file"),
555 JvOptionPane.WARNING_MESSAGE);
561 System.err.println(errorMessage);
566 updateRecentlyOpened();
568 } catch (Exception er)
570 System.err.println("Exception whilst opening file '" + file);
571 er.printStackTrace();
574 javax.swing.SwingUtilities.invokeLater(new Runnable()
579 JvOptionPane.showInternalMessageDialog(
580 Desktop.desktop, MessageManager.formatMessage(
581 "label.problems_opening_file",
582 new String[] { file }), MessageManager
583 .getString("label.file_open_error"),
584 JvOptionPane.WARNING_MESSAGE);
589 } catch (OutOfMemoryError er)
592 er.printStackTrace();
596 javax.swing.SwingUtilities.invokeLater(new Runnable()
601 JvOptionPane.showInternalMessageDialog(
602 Desktop.desktop, MessageManager.formatMessage(
603 "warn.out_of_memory_loading_file", new String[]
604 { file }), MessageManager
605 .getString("label.out_of_memory"),
606 JvOptionPane.WARNING_MESSAGE);
610 System.err.println("Out of memory loading file " + file + "!!");
613 loadtime += System.currentTimeMillis();
614 // TODO: Estimate percentage of memory used by a newly loaded alignment -
615 // warn if more memory will be needed to work with it
618 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
623 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
625 if (alignFrame != null)
627 AlignmentI al = alignFrame.getViewport().getAlignment();
629 System.out.println("Loaded '" + title + "' in "
630 + (loadtime / 1000.0) + "s, took an additional "
631 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
632 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
636 // report that we didn't load anything probably due to an out of memory
638 System.out.println("Failed to load '" + title + "' in "
639 + (loadtime / 1000.0) + "s, took an additional "
640 + (1.0 * memused / (1024.0 * 1024.0))
641 + " MB (alignment is null)");
644 // remove the visual delay indicator
645 if (Desktop.instance != null)
647 Desktop.instance.stopLoading();
653 * This method creates the file -
654 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
655 * file name and extension
658 * the name of the temp file to be created
660 * the extension of the temp file to be created
663 private static String createNamedJvTempFile(String fileName,
664 String extension) throws IOException
666 String seprator = System.getProperty("file.separator");
667 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
668 + seprator + System.currentTimeMillis();
669 File tempStructFile = new File(jvTempDir + seprator + fileName + "."
671 tempStructFile.mkdirs();
672 return tempStructFile.toString();
678 * @see java.lang.Object#finalize()
681 protected void finalize() throws Throwable