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.JvOptionPane;
37 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
38 import jalview.project.Jalview2XML;
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 (file, protocol) of type format and wait till loaded
178 * @return alignFrame constructed from file contents
180 public AlignFrame LoadFileWaitTillLoaded(File file,
181 DataSourceType sourceType, FileFormatI format)
183 this.selectedFile = file;
184 this.file = file.getPath();
185 this.protocol = sourceType;
186 this.format = format;
187 return _LoadFileWaitTillLoaded();
191 * Load alignment from FileParse source of type format and wait till loaded
195 * @return alignFrame constructed from file contents
197 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
200 this.source = source;
202 file = source.getInFile();
203 protocol = source.getDataSourceType();
204 this.format = format;
205 return _LoadFileWaitTillLoaded();
209 * runs the 'run' method (in this thread), then return the alignFrame that's
210 * (hopefully) been read
214 protected AlignFrame _LoadFileWaitTillLoaded()
220 public void updateRecentlyOpened()
222 Vector<String> recent = new Vector<>();
223 if (protocol == DataSourceType.PASTE)
225 // do nothing if the file was pasted in as text... there is no filename to
230 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
232 // ignore files loaded from the system's temporary directory
235 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
238 String historyItems = Cache.getProperty(type);
242 if (historyItems != null)
244 st = new StringTokenizer(historyItems, "\t");
246 while (st.hasMoreTokens())
248 recent.addElement(st.nextToken().trim());
252 if (recent.contains(file))
257 StringBuffer newHistory = new StringBuffer(file);
258 for (int i = 0; i < recent.size() && i < 10; i++)
260 newHistory.append("\t");
261 newHistory.append(recent.elementAt(i));
264 Cache.setProperty(type, newHistory.toString());
266 if (protocol == DataSourceType.FILE)
268 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
275 String title = protocol == DataSourceType.PASTE
276 ? "Copied From Clipboard"
278 Runtime rt = Runtime.getRuntime();
281 if (Desktop.instance != null)
283 Desktop.instance.startLoading(file);
287 // just in case the caller didn't identify the file for us
290 format = new IdentifyFile().identify(source, false);
291 // identify stream and rewind rather than close
293 else if (selectedFile != null) {
294 format = new IdentifyFile().identify(selectedFile, protocol);
298 format = new IdentifyFile().identify(file, protocol);
305 Desktop.instance.stopLoading();
306 System.err.println("The input file \"" + file
307 + "\" has null or unidentifiable data content!");
308 if (!Jalview.isHeadlessMode())
310 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
311 MessageManager.getString("label.couldnt_read_data")
312 + " in " + file + "\n"
313 + AppletFormatAdapter.getSupportedFormats(),
314 MessageManager.getString("label.couldnt_read_data"),
315 JvOptionPane.WARNING_MESSAGE);
319 // TODO: cache any stream datasources as a temporary file (eg. PDBs
320 // retrieved via URL)
321 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
324 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
329 loadtime = -System.currentTimeMillis();
330 AlignmentI al = null;
332 if (FileFormat.Jalview.equals(format))
336 // Tell the user (developer?) that this is going to cause a problem
338 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
339 // We read the data anyway - it might make sense.
341 // BH 2018 switch to File object here instead of filename
342 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
346 String error = AppletFormatAdapter.getSupportedFormats();
351 // read from the provided source
352 al = new FormatAdapter().readFromFile(source, format);
357 // open a new source and read from it
358 FormatAdapter fa = new FormatAdapter();
359 boolean downloadStructureFile = format.isStructureFile()
360 && protocol.equals(DataSourceType.URL);
361 if (downloadStructureFile)
363 String structExt = format.getExtensions().split(",")[0];
364 String urlLeafName = file.substring(
366 System.getProperty("file.separator")),
367 file.lastIndexOf("."));
368 String tempStructureFileStr = createNamedJvTempFile(
369 urlLeafName, structExt);
371 // BH - switching to File object here so as to hold
372 // ._bytes array directly
373 File tempFile = new File(tempStructureFileStr);
374 UrlDownloadClient.download(file, tempFile);
376 al = fa.readFile(tempFile, DataSourceType.FILE,
378 source = fa.getAlignFile();
382 if (selectedFile == null) {
383 al = fa.readFile(file, protocol, format);
386 al = fa.readFile(selectedFile, protocol, format);
388 source = fa.getAlignFile(); // keep reference for later if
393 } catch (java.io.IOException ex)
395 error = ex.getMessage();
398 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
400 // construct and register dataset sequences
401 for (SequenceI sq : al.getSequences())
403 while (sq.getDatasetSequence() != null)
405 sq = sq.getDatasetSequence();
407 if (sq.getAllPDBEntries() != null)
409 for (PDBEntry pdbe : sq.getAllPDBEntries())
411 // register PDB entries with desktop's structure selection
413 StructureSelectionManager
414 .getStructureSelectionManager(Desktop.instance)
415 .registerPDBEntry(pdbe);
420 FeatureSettingsModelI proxyColourScheme = source
421 .getFeatureColourScheme();
422 if (viewport != null)
424 if (proxyColourScheme != null)
426 viewport.applyFeaturesStyle(proxyColourScheme);
428 // append to existing alignment
429 viewport.addAlignment(al, title);
433 // otherwise construct the alignFrame
435 if (source instanceof ComplexAlignFile)
437 HiddenColumns colSel = ((ComplexAlignFile) source)
439 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
440 .getHiddenSequences();
441 String colourSchemeName = ((ComplexAlignFile) source)
442 .getGlobalColourScheme();
443 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
444 .getDisplayedFeatures();
445 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
446 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
447 alignFrame.getViewport().setFeaturesDisplayed(fd);
448 alignFrame.getViewport().setShowSequenceFeatures(
449 ((ComplexAlignFile) source).isShowSeqFeatures());
450 ColourSchemeI cs = ColourSchemeMapper
451 .getJalviewColourScheme(colourSchemeName, al);
454 alignFrame.changeColour(cs);
459 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
460 AlignFrame.DEFAULT_HEIGHT);
461 if (source instanceof FeaturesSourceI)
463 alignFrame.getViewport().setShowSequenceFeatures(true);
466 // add metadata and update ui
467 if (!(protocol == DataSourceType.PASTE))
469 alignFrame.setFileName(file, format);
470 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
472 if (proxyColourScheme != null)
474 alignFrame.getViewport()
475 .applyFeaturesStyle(proxyColourScheme);
477 alignFrame.setStatus(MessageManager.formatMessage(
478 "label.successfully_loaded_file", new String[]
483 // add the window to the GUI
484 // note - this actually should happen regardless of raiseGUI
485 // status in Jalview 3
486 // TODO: define 'virtual desktop' for benefit of headless scripts
487 // that perform queries to find the 'current working alignment'
488 Desktop.addInternalFrame(alignFrame, title,
489 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
494 alignFrame.setMaximum(jalview.bin.Cache
495 .getDefault("SHOW_FULLSCREEN", false));
496 } catch (java.beans.PropertyVetoException ex)
503 if (Desktop.instance != null)
505 Desktop.instance.stopLoading();
508 final String errorMessage = MessageManager.getString(
509 "label.couldnt_load_file") + " " + title + "\n" + error;
510 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
512 if (raiseGUI && Desktop.desktop != null)
514 javax.swing.SwingUtilities.invokeLater(new Runnable()
519 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
522 .getString("label.error_loading_file"),
523 JvOptionPane.WARNING_MESSAGE);
529 System.err.println(errorMessage);
534 updateRecentlyOpened();
536 } catch (Exception er)
538 System.err.println("Exception whilst opening file '" + file);
539 er.printStackTrace();
542 javax.swing.SwingUtilities.invokeLater(new Runnable()
547 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
548 MessageManager.formatMessage(
549 "label.problems_opening_file", new String[]
551 MessageManager.getString("label.file_open_error"),
552 JvOptionPane.WARNING_MESSAGE);
557 } catch (OutOfMemoryError er)
560 er.printStackTrace();
564 javax.swing.SwingUtilities.invokeLater(new Runnable()
569 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
570 MessageManager.formatMessage(
571 "warn.out_of_memory_loading_file", new String[]
573 MessageManager.getString("label.out_of_memory"),
574 JvOptionPane.WARNING_MESSAGE);
578 System.err.println("Out of memory loading file " + file + "!!");
581 loadtime += System.currentTimeMillis();
582 // TODO: Estimate percentage of memory used by a newly loaded alignment -
583 // warn if more memory will be needed to work with it
586 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
591 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
593 if (alignFrame != null)
595 AlignmentI al = alignFrame.getViewport().getAlignment();
597 System.out.println("Loaded '" + title + "' in "
598 + (loadtime / 1000.0) + "s, took an additional "
599 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
600 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
604 // report that we didn't load anything probably due to an out of memory
606 System.out.println("Failed to load '" + title + "' in "
607 + (loadtime / 1000.0) + "s, took an additional "
608 + (1.0 * memused / (1024.0 * 1024.0))
609 + " MB (alignment is null)");
612 // remove the visual delay indicator
613 if (Desktop.instance != null)
615 Desktop.instance.stopLoading();
621 * This method creates the file -
622 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
623 * file name and extension
626 * the name of the temp file to be created
628 * the extension of the temp file to be created
631 private static String createNamedJvTempFile(String fileName,
632 String extension) throws IOException
634 String seprator = System.getProperty("file.separator");
635 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
636 + seprator + System.currentTimeMillis();
637 File tempStructFile = new File(
638 jvTempDir + seprator + fileName + "." + extension);
639 tempStructFile.mkdirs();
640 return tempStructFile.toString();
645 * @param file a File, or a String which is a name of a file
647 * @throws FileNotFoundException
649 @SuppressWarnings("unused")
650 public static BufferedReader getBuffereReader(Object file) throws FileNotFoundException {
651 if (file instanceof String)
652 return new BufferedReader(new FileReader((String) file));
654 byte[] bytes = /** @j2sNative file._bytes || */ null;
656 return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
657 return new BufferedReader(new FileReader((File) file));