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;
44 import java.io.BufferedReader;
45 import java.io.ByteArrayInputStream;
47 import java.io.FileNotFoundException;
48 import java.io.FileReader;
49 import java.io.IOException;
50 import java.io.InputStream;
51 import java.io.InputStreamReader;
52 import java.util.StringTokenizer;
53 import java.util.Vector;
55 import javax.swing.SwingUtilities;
57 public class FileLoader implements Runnable
61 DataSourceType protocol;
65 AlignmentFileReaderI source = null; // alternative specification of where data
70 AlignViewport viewport;
72 AlignFrame alignFrame;
78 boolean raiseGUI = true;
80 private File selectedFile;
83 * default constructor always raised errors in GUI dialog boxes
91 * construct a Fileloader that may raise errors non-interactively
94 * true if errors are to be raised as GUI dialog boxes
96 public FileLoader(boolean raiseGUI)
98 this.raiseGUI = raiseGUI;
101 public void LoadFile(AlignViewport viewport, Object file,
102 DataSourceType protocol, FileFormatI format)
104 this.viewport = viewport;
105 if (file instanceof File) {
106 this.selectedFile = (File) file;
107 file = selectedFile.getPath();
109 LoadFile(file.toString(), protocol, format);
112 public void LoadFile(String file, DataSourceType protocol,
116 this.protocol = protocol;
117 this.format = format;
119 final Thread loader = new Thread(this);
121 SwingUtilities.invokeLater(new Runnable()
132 * Load a (file, protocol) source of unknown type
137 public void LoadFile(String file, DataSourceType protocol)
139 LoadFile(file, protocol, null);
143 * Load alignment from (file, protocol) and wait till loaded
147 * @return alignFrame constructed from file contents
149 public AlignFrame LoadFileWaitTillLoaded(String file,
150 DataSourceType sourceType)
152 return LoadFileWaitTillLoaded(file, sourceType, null);
156 * Load alignment from (file, protocol) of type format and wait till loaded
161 * @return alignFrame constructed from file contents
163 public AlignFrame LoadFileWaitTillLoaded(String file,
164 DataSourceType sourceType, FileFormatI format)
167 this.protocol = sourceType;
168 this.format = format;
169 return _LoadFileWaitTillLoaded();
173 * Load alignment from FileParse source of type format and wait till loaded
177 * @return alignFrame constructed from file contents
179 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
182 this.source = source;
184 file = source.getInFile();
185 protocol = source.getDataSourceType();
186 this.format = format;
187 return _LoadFileWaitTillLoaded();
191 * runs the 'run' method (in this thread), then return the alignFrame that's
192 * (hopefully) been read
196 protected AlignFrame _LoadFileWaitTillLoaded()
202 public void updateRecentlyOpened()
204 Vector<String> 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 = Cache.getProperty(type);
224 if (historyItems != null)
226 st = new StringTokenizer(historyItems, "\t");
228 while (st.hasMoreTokens())
230 recent.addElement(st.nextToken().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
275 else if (selectedFile != null) {
276 format = new IdentifyFile().identify(selectedFile, protocol);
280 format = new IdentifyFile().identify(file, protocol);
287 Desktop.instance.stopLoading();
288 System.err.println("The input file \"" + file
289 + "\" has null or unidentifiable data content!");
290 if (!Jalview.isHeadlessMode())
292 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
293 MessageManager.getString("label.couldnt_read_data")
294 + " in " + file + "\n"
295 + AppletFormatAdapter.getSupportedFormats(),
296 MessageManager.getString("label.couldnt_read_data"),
297 JvOptionPane.WARNING_MESSAGE);
301 // TODO: cache any stream datasources as a temporary file (eg. PDBs
302 // retrieved via URL)
303 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
306 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
311 loadtime = -System.currentTimeMillis();
312 AlignmentI al = null;
314 if (FileFormat.Jalview.equals(format))
318 // Tell the user (developer?) that this is going to cause a problem
320 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
321 // We read the data anyway - it might make sense.
323 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
327 String error = AppletFormatAdapter.getSupportedFormats();
332 // read from the provided source
333 al = new FormatAdapter().readFromFile(source, format);
338 // open a new source and read from it
339 FormatAdapter fa = new FormatAdapter();
340 boolean downloadStructureFile = format.isStructureFile()
341 && protocol.equals(DataSourceType.URL);
342 if (downloadStructureFile)
344 String structExt = format.getExtensions().split(",")[0];
345 String urlLeafName = file.substring(
347 System.getProperty("file.separator")),
348 file.lastIndexOf("."));
349 String tempStructureFileStr = createNamedJvTempFile(
350 urlLeafName, structExt);
351 UrlDownloadClient.download(file, tempStructureFileStr);
352 al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
354 source = fa.getAlignFile();
358 if (selectedFile == null) {
359 al = fa.readFile(file, protocol, format);
362 al = fa.readFile(selectedFile, protocol, format);
364 source = fa.getAlignFile(); // keep reference for later if
369 } catch (java.io.IOException ex)
371 error = ex.getMessage();
374 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
376 // construct and register dataset sequences
377 for (SequenceI sq : al.getSequences())
379 while (sq.getDatasetSequence() != null)
381 sq = sq.getDatasetSequence();
383 if (sq.getAllPDBEntries() != null)
385 for (PDBEntry pdbe : sq.getAllPDBEntries())
387 // register PDB entries with desktop's structure selection
389 StructureSelectionManager
390 .getStructureSelectionManager(Desktop.instance)
391 .registerPDBEntry(pdbe);
396 FeatureSettingsModelI proxyColourScheme = source
397 .getFeatureColourScheme();
398 if (viewport != null)
400 if (proxyColourScheme != null)
402 viewport.applyFeaturesStyle(proxyColourScheme);
404 // append to existing alignment
405 viewport.addAlignment(al, title);
409 // otherwise construct the alignFrame
411 if (source instanceof ComplexAlignFile)
413 HiddenColumns colSel = ((ComplexAlignFile) source)
415 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
416 .getHiddenSequences();
417 String colourSchemeName = ((ComplexAlignFile) source)
418 .getGlobalColourScheme();
419 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
420 .getDisplayedFeatures();
421 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
422 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
423 alignFrame.getViewport().setFeaturesDisplayed(fd);
424 alignFrame.getViewport().setShowSequenceFeatures(
425 ((ComplexAlignFile) source).isShowSeqFeatures());
426 ColourSchemeI cs = ColourSchemeMapper
427 .getJalviewColourScheme(colourSchemeName, al);
430 alignFrame.changeColour(cs);
435 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
436 AlignFrame.DEFAULT_HEIGHT);
437 if (source instanceof FeaturesSourceI)
439 alignFrame.getViewport().setShowSequenceFeatures(true);
442 // add metadata and update ui
443 if (!(protocol == DataSourceType.PASTE))
445 alignFrame.setFileName(file, format);
447 if (proxyColourScheme != null)
449 alignFrame.getViewport()
450 .applyFeaturesStyle(proxyColourScheme);
452 alignFrame.statusBar.setText(MessageManager.formatMessage(
453 "label.successfully_loaded_file", new String[]
458 // add the window to the GUI
459 // note - this actually should happen regardless of raiseGUI
460 // status in Jalview 3
461 // TODO: define 'virtual desktop' for benefit of headless scripts
462 // that perform queries to find the 'current working alignment'
463 Desktop.addInternalFrame(alignFrame, title,
464 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
469 alignFrame.setMaximum(jalview.bin.Cache
470 .getDefault("SHOW_FULLSCREEN", false));
471 } catch (java.beans.PropertyVetoException ex)
478 if (Desktop.instance != null)
480 Desktop.instance.stopLoading();
483 final String errorMessage = MessageManager.getString(
484 "label.couldnt_load_file") + " " + title + "\n" + error;
485 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
487 if (raiseGUI && Desktop.desktop != null)
489 javax.swing.SwingUtilities.invokeLater(new Runnable()
494 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
497 .getString("label.error_loading_file"),
498 JvOptionPane.WARNING_MESSAGE);
504 System.err.println(errorMessage);
509 updateRecentlyOpened();
511 } catch (Exception er)
513 System.err.println("Exception whilst opening file '" + file);
514 er.printStackTrace();
517 javax.swing.SwingUtilities.invokeLater(new Runnable()
522 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
523 MessageManager.formatMessage(
524 "label.problems_opening_file", new String[]
526 MessageManager.getString("label.file_open_error"),
527 JvOptionPane.WARNING_MESSAGE);
532 } catch (OutOfMemoryError er)
535 er.printStackTrace();
539 javax.swing.SwingUtilities.invokeLater(new Runnable()
544 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
545 MessageManager.formatMessage(
546 "warn.out_of_memory_loading_file", new String[]
548 MessageManager.getString("label.out_of_memory"),
549 JvOptionPane.WARNING_MESSAGE);
553 System.err.println("Out of memory loading file " + file + "!!");
556 loadtime += System.currentTimeMillis();
557 // TODO: Estimate percentage of memory used by a newly loaded alignment -
558 // warn if more memory will be needed to work with it
561 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
566 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
568 if (alignFrame != null)
570 AlignmentI al = alignFrame.getViewport().getAlignment();
572 System.out.println("Loaded '" + title + "' in "
573 + (loadtime / 1000.0) + "s, took an additional "
574 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
575 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
579 // report that we didn't load anything probably due to an out of memory
581 System.out.println("Failed to load '" + title + "' in "
582 + (loadtime / 1000.0) + "s, took an additional "
583 + (1.0 * memused / (1024.0 * 1024.0))
584 + " MB (alignment is null)");
587 // remove the visual delay indicator
588 if (Desktop.instance != null)
590 Desktop.instance.stopLoading();
596 * This method creates the file -
597 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
598 * file name and extension
601 * the name of the temp file to be created
603 * the extension of the temp file to be created
606 private static String createNamedJvTempFile(String fileName,
607 String extension) throws IOException
609 String seprator = System.getProperty("file.separator");
610 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
611 + seprator + System.currentTimeMillis();
612 File tempStructFile = new File(
613 jvTempDir + seprator + fileName + "." + extension);
614 tempStructFile.mkdirs();
615 return tempStructFile.toString();
620 * @param file a File, or a String which is a name of a file
622 * @throws FileNotFoundException
624 @SuppressWarnings("unused")
625 public static BufferedReader getBuffereReader(Object file) throws FileNotFoundException {
626 if (file instanceof String)
627 return new BufferedReader(new FileReader((String) file));
629 byte[] bytes = /** @j2sNative file._bytes || */ null;
631 return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
632 return new BufferedReader(new FileReader((File) file));