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.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;
45 import java.io.IOException;
46 import java.util.StringTokenizer;
47 import java.util.Vector;
49 import javax.swing.SwingUtilities;
51 public class FileLoader implements Runnable
55 DataSourceType protocol;
59 AlignmentFileReaderI source = null; // alternative specification of where data
64 AlignViewport viewport;
66 AlignFrame alignFrame;
72 boolean raiseGUI = true;
75 * default constructor always raised errors in GUI dialog boxes
83 * construct a Fileloader that may raise errors non-interactively
86 * true if errors are to be raised as GUI dialog boxes
88 public FileLoader(boolean raiseGUI)
90 this.raiseGUI = raiseGUI;
93 public void LoadFile(AlignViewport viewport, String file,
94 DataSourceType protocol, FileFormatI format)
96 this.viewport = viewport;
97 LoadFile(file, protocol, format);
100 public void LoadFile(String file, DataSourceType protocol,
104 this.protocol = protocol;
105 this.format = format;
107 final Thread loader = new Thread(this);
109 SwingUtilities.invokeLater(new Runnable()
120 * Load a (file, protocol) source of unknown type
125 public void LoadFile(String file, DataSourceType protocol)
127 LoadFile(file, protocol, null);
131 * Load alignment from (file, protocol) and wait till loaded
135 * @return alignFrame constructed from file contents
137 public AlignFrame LoadFileWaitTillLoaded(String file,
138 DataSourceType sourceType)
140 return LoadFileWaitTillLoaded(file, sourceType, null);
144 * Load alignment from (file, protocol) of type format and wait till loaded
149 * @return alignFrame constructed from file contents
151 public AlignFrame LoadFileWaitTillLoaded(String file,
152 DataSourceType sourceType, FileFormatI format)
155 this.protocol = sourceType;
156 this.format = format;
157 return _LoadFileWaitTillLoaded();
161 * Load alignment from FileParse source of type format and wait till loaded
165 * @return alignFrame constructed from file contents
167 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
170 this.source = source;
172 file = source.getInFile();
173 protocol = source.getDataSourceType();
174 this.format = format;
175 return _LoadFileWaitTillLoaded();
179 * start thread and wait until finished, then return the alignFrame that's
180 * (hopefully) been read.
184 protected AlignFrame _LoadFileWaitTillLoaded()
186 Thread loader = new Thread(this);
189 while (loader.isAlive())
194 } catch (Exception ex)
202 public void updateRecentlyOpened()
204 Vector recent = new Vector();
205 if (protocol == DataSourceType.PASTE)
207 // do nothing if the file was pasted in as text... there is no filename to
212 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
214 // ignore files loaded from the system's temporary directory
217 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
220 String historyItems = jalview.bin.Cache.getProperty(type);
224 if (historyItems != null)
226 st = new StringTokenizer(historyItems, "\t");
228 while (st.hasMoreTokens())
230 recent.addElement(st.nextElement().toString().trim());
234 if (recent.contains(file))
239 StringBuffer newHistory = new StringBuffer(file);
240 for (int i = 0; i < recent.size() && i < 10; i++)
242 newHistory.append("\t");
243 newHistory.append(recent.elementAt(i));
246 Cache.setProperty(type, newHistory.toString());
248 if (protocol == DataSourceType.FILE)
250 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
257 String title = protocol == DataSourceType.PASTE
258 ? "Copied From Clipboard"
260 Runtime rt = Runtime.getRuntime();
263 if (Desktop.instance != null)
265 Desktop.instance.startLoading(file);
269 // just in case the caller didn't identify the file for us
272 format = new IdentifyFile().identify(source, false);
273 // identify stream and rewind rather than close
277 format = new IdentifyFile().identify(file, protocol);
284 Desktop.instance.stopLoading();
285 System.err.println("The input file \"" + file
286 + "\" has null or unidentifiable data content!");
287 if (!Jalview.isHeadlessMode())
289 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
290 MessageManager.getString("label.couldnt_read_data")
291 + " in " + file + "\n"
292 + AppletFormatAdapter.getSupportedFormats(),
293 MessageManager.getString("label.couldnt_read_data"),
294 JvOptionPane.WARNING_MESSAGE);
298 // TODO: cache any stream datasources as a temporary file (eg. PDBs
299 // retrieved via URL)
300 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
303 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
308 loadtime = -System.currentTimeMillis();
309 AlignmentI al = null;
311 if (FileFormat.Bam.equals(format))
313 // ask the user which bit of the bam they want to load
316 if (FileFormat.Jalview.equals(format))
320 // Tell the user (developer?) that this is going to cause a problem
322 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
323 // We read the data anyway - it might make sense.
325 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
329 String error = AppletFormatAdapter.getSupportedFormats();
334 // read from the provided source
335 al = new FormatAdapter().readFromFile(source, format);
340 // open a new source and read from it
341 FormatAdapter fa = new FormatAdapter();
342 boolean downloadStructureFile = format.isStructureFile()
343 && protocol.equals(DataSourceType.URL);
344 if (downloadStructureFile)
346 String structExt = format.getExtensions().split(",")[0];
347 String urlLeafName = file.substring(
349 System.getProperty("file.separator")),
350 file.lastIndexOf("."));
351 String tempStructureFileStr = createNamedJvTempFile(
352 urlLeafName, structExt);
353 UrlDownloadClient.download(file, tempStructureFileStr);
354 al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
356 source = fa.getAlignFile();
360 al = fa.readFile(file, protocol, format);
361 source = fa.getAlignFile(); // keep reference for later if
365 } catch (java.io.IOException ex)
367 error = ex.getMessage();
370 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
372 // construct and register dataset sequences
373 for (SequenceI sq : al.getSequences())
375 while (sq.getDatasetSequence() != null)
377 sq = sq.getDatasetSequence();
379 if (sq.getAllPDBEntries() != null)
381 for (PDBEntry pdbe : sq.getAllPDBEntries())
383 // register PDB entries with desktop's structure selection
385 StructureSelectionManager
386 .getStructureSelectionManager(Desktop.instance)
387 .registerPDBEntry(pdbe);
392 FeatureSettingsModelI proxyColourScheme = source
393 .getFeatureColourScheme();
394 if (viewport != null)
396 if (proxyColourScheme != null)
398 viewport.applyFeaturesStyle(proxyColourScheme);
400 // append to existing alignment
401 viewport.addAlignment(al, title);
405 // otherwise construct the alignFrame
407 if (source instanceof ComplexAlignFile)
409 HiddenColumns colSel = ((ComplexAlignFile) source)
411 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
412 .getHiddenSequences();
413 String colourSchemeName = ((ComplexAlignFile) source)
414 .getGlobalColourScheme();
415 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
416 .getDisplayedFeatures();
417 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
418 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
419 alignFrame.getViewport().setFeaturesDisplayed(fd);
420 alignFrame.getViewport().setShowSequenceFeatures(
421 ((ComplexAlignFile) source).isShowSeqFeatures());
422 ColourSchemeI cs = ColourSchemeMapper
423 .getJalviewColourScheme(colourSchemeName, al);
426 alignFrame.changeColour(cs);
431 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
432 AlignFrame.DEFAULT_HEIGHT);
433 if (source instanceof FeaturesSourceI)
435 alignFrame.getViewport().setShowSequenceFeatures(true);
438 // add metadata and update ui
439 if (!(protocol == DataSourceType.PASTE))
441 alignFrame.setFileName(file, format);
443 if (proxyColourScheme != null)
445 alignFrame.getViewport()
446 .applyFeaturesStyle(proxyColourScheme);
448 alignFrame.statusBar.setText(MessageManager.formatMessage(
449 "label.successfully_loaded_file", new String[]
454 // add the window to the GUI
455 // note - this actually should happen regardless of raiseGUI
456 // status in Jalview 3
457 // TODO: define 'virtual desktop' for benefit of headless scripts
458 // that perform queries to find the 'current working alignment'
459 Desktop.addInternalFrame(alignFrame, title,
460 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
465 alignFrame.setMaximum(jalview.bin.Cache
466 .getDefault("SHOW_FULLSCREEN", false));
467 } catch (java.beans.PropertyVetoException ex)
474 if (Desktop.instance != null)
476 Desktop.instance.stopLoading();
479 final String errorMessage = MessageManager.getString(
480 "label.couldnt_load_file") + " " + title + "\n" + error;
481 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
483 if (raiseGUI && Desktop.desktop != null)
485 javax.swing.SwingUtilities.invokeLater(new Runnable()
490 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
493 .getString("label.error_loading_file"),
494 JvOptionPane.WARNING_MESSAGE);
500 System.err.println(errorMessage);
505 updateRecentlyOpened();
507 } catch (Exception er)
509 System.err.println("Exception whilst opening file '" + file);
510 er.printStackTrace();
513 javax.swing.SwingUtilities.invokeLater(new Runnable()
518 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
519 MessageManager.formatMessage(
520 "label.problems_opening_file", new String[]
522 MessageManager.getString("label.file_open_error"),
523 JvOptionPane.WARNING_MESSAGE);
528 } catch (OutOfMemoryError er)
531 er.printStackTrace();
535 javax.swing.SwingUtilities.invokeLater(new Runnable()
540 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
541 MessageManager.formatMessage(
542 "warn.out_of_memory_loading_file", new String[]
544 MessageManager.getString("label.out_of_memory"),
545 JvOptionPane.WARNING_MESSAGE);
549 System.err.println("Out of memory loading file " + file + "!!");
552 loadtime += System.currentTimeMillis();
553 // TODO: Estimate percentage of memory used by a newly loaded alignment -
554 // warn if more memory will be needed to work with it
557 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
562 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
564 if (alignFrame != null)
566 AlignmentI al = alignFrame.getViewport().getAlignment();
568 System.out.println("Loaded '" + title + "' in "
569 + (loadtime / 1000.0) + "s, took an additional "
570 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
571 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
575 // report that we didn't load anything probably due to an out of memory
577 System.out.println("Failed to load '" + title + "' in "
578 + (loadtime / 1000.0) + "s, took an additional "
579 + (1.0 * memused / (1024.0 * 1024.0))
580 + " MB (alignment is null)");
583 // remove the visual delay indicator
584 if (Desktop.instance != null)
586 Desktop.instance.stopLoading();
592 * This method creates the file -
593 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
594 * file name and extension
597 * the name of the temp file to be created
599 * the extension of the temp file to be created
602 private static String createNamedJvTempFile(String fileName,
603 String extension) throws IOException
605 String seprator = System.getProperty("file.separator");
606 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
607 + seprator + System.currentTimeMillis();
608 File tempStructFile = new File(
609 jvTempDir + seprator + fileName + "." + extension);
610 tempStructFile.mkdirs();
611 return tempStructFile.toString();