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.util.Platform;
43 import jalview.ws.utils.UrlDownloadClient;
45 import java.io.BufferedReader;
46 import java.io.ByteArrayInputStream;
48 import java.io.FileNotFoundException;
49 import java.io.FileReader;
50 import java.io.IOException;
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()
221 public void updateRecentlyOpened()
223 Vector<String> recent = new Vector<>();
224 if (protocol == DataSourceType.PASTE)
226 // do nothing if the file was pasted in as text... there is no filename to
231 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
233 // ignore files loaded from the system's temporary directory
236 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
239 String historyItems = Cache.getProperty(type);
243 if (historyItems != null)
245 st = new StringTokenizer(historyItems, "\t");
247 while (st.hasMoreTokens())
249 recent.addElement(st.nextToken().trim());
253 if (recent.contains(file))
258 StringBuffer newHistory = new StringBuffer(file);
259 for (int i = 0; i < recent.size() && i < 10; i++)
261 newHistory.append("\t");
262 newHistory.append(recent.elementAt(i));
265 Cache.setProperty(type, newHistory.toString());
267 if (protocol == DataSourceType.FILE)
269 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
276 String title = protocol == DataSourceType.PASTE
277 ? "Copied From Clipboard"
279 Runtime rt = Runtime.getRuntime();
282 if (Desktop.instance != null)
284 Desktop.instance.startLoading(file);
288 // just in case the caller didn't identify the file for us
291 format = new IdentifyFile().identify(source, false);
292 // identify stream and rewind rather than close
294 else if (selectedFile != null) {
295 format = new IdentifyFile().identify(selectedFile, protocol);
299 format = new IdentifyFile().identify(file, protocol);
306 Desktop.instance.stopLoading();
307 System.err.println("The input file \"" + file
308 + "\" has null or unidentifiable data content!");
309 if (!Jalview.isHeadlessMode())
311 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
312 MessageManager.getString("label.couldnt_read_data")
313 + " in " + file + "\n"
314 + AppletFormatAdapter.getSupportedFormats(),
315 MessageManager.getString("label.couldnt_read_data"),
316 JvOptionPane.WARNING_MESSAGE);
320 // TODO: cache any stream datasources as a temporary file (eg. PDBs
321 // retrieved via URL)
322 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
325 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
330 loadtime = -System.currentTimeMillis();
331 AlignmentI al = null;
333 if (FileFormat.Jalview.equals(format))
337 // Tell the user (developer?) that this is going to cause a problem
339 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
340 // We read the data anyway - it might make sense.
342 // BH 2018 switch to File object here instead of filename
343 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
347 String error = AppletFormatAdapter.getSupportedFormats();
352 // read from the provided source
353 al = new FormatAdapter().readFromFile(source, format);
358 // open a new source and read from it
359 FormatAdapter fa = new FormatAdapter();
360 boolean downloadStructureFile = format.isStructureFile()
361 && protocol.equals(DataSourceType.URL);
362 if (downloadStructureFile)
364 String structExt = format.getExtensions().split(",")[0];
365 String urlLeafName = file.substring(
367 System.getProperty("file.separator")),
368 file.lastIndexOf("."));
369 String tempStructureFileStr = createNamedJvTempFile(
370 urlLeafName, structExt);
372 // BH - switching to File object here so as to hold
373 // ._bytes array directly
374 File tempFile = new File(tempStructureFileStr);
375 UrlDownloadClient.download(file, tempFile);
377 al = fa.readFile(tempFile, DataSourceType.FILE,
379 source = fa.getAlignFile();
383 if (selectedFile == null) {
384 al = fa.readFile(file, protocol, format);
387 al = fa.readFile(selectedFile, protocol, format);
389 source = fa.getAlignFile(); // keep reference for later if
394 } catch (java.io.IOException ex)
396 error = ex.getMessage();
399 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
401 // construct and register dataset sequences
402 for (SequenceI sq : al.getSequences())
404 while (sq.getDatasetSequence() != null)
406 sq = sq.getDatasetSequence();
408 if (sq.getAllPDBEntries() != null)
410 for (PDBEntry pdbe : sq.getAllPDBEntries())
412 // register PDB entries with desktop's structure selection
414 StructureSelectionManager
415 .getStructureSelectionManager(Desktop.instance)
416 .registerPDBEntry(pdbe);
421 FeatureSettingsModelI proxyColourScheme = source
422 .getFeatureColourScheme();
423 if (viewport != null)
425 if (proxyColourScheme != null)
427 viewport.applyFeaturesStyle(proxyColourScheme);
429 // append to existing alignment
430 viewport.addAlignment(al, title);
434 // otherwise construct the alignFrame
436 if (source instanceof ComplexAlignFile)
438 HiddenColumns colSel = ((ComplexAlignFile) source)
440 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
441 .getHiddenSequences();
442 String colourSchemeName = ((ComplexAlignFile) source)
443 .getGlobalColourScheme();
444 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
445 .getDisplayedFeatures();
446 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
447 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
448 alignFrame.getViewport().setFeaturesDisplayed(fd);
449 alignFrame.getViewport().setShowSequenceFeatures(
450 ((ComplexAlignFile) source).isShowSeqFeatures());
451 ColourSchemeI cs = ColourSchemeMapper
452 .getJalviewColourScheme(colourSchemeName, al);
455 alignFrame.changeColour(cs);
460 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
461 AlignFrame.DEFAULT_HEIGHT);
462 if (source instanceof FeaturesSourceI)
464 alignFrame.getViewport().setShowSequenceFeatures(true);
467 // add metadata and update ui
468 if (!(protocol == DataSourceType.PASTE))
470 alignFrame.setFileName(file, format);
471 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
473 if (proxyColourScheme != null)
475 alignFrame.getViewport()
476 .applyFeaturesStyle(proxyColourScheme);
478 alignFrame.setStatus(MessageManager.formatMessage(
479 "label.successfully_loaded_file", new String[]
484 // add the window to the GUI
485 // note - this actually should happen regardless of raiseGUI
486 // status in Jalview 3
487 // TODO: define 'virtual desktop' for benefit of headless scripts
488 // that perform queries to find the 'current working alignment'
489 Desktop.addInternalFrame(alignFrame, title,
490 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
495 alignFrame.setMaximum(jalview.bin.Cache
496 .getDefault("SHOW_FULLSCREEN", false));
497 } catch (java.beans.PropertyVetoException ex)
504 if (Desktop.instance != null)
506 Desktop.instance.stopLoading();
509 final String errorMessage = MessageManager.getString(
510 "label.couldnt_load_file") + " " + title + "\n" + error;
511 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
513 if (raiseGUI && Desktop.desktop != null)
515 javax.swing.SwingUtilities.invokeLater(new Runnable()
520 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
523 .getString("label.error_loading_file"),
524 JvOptionPane.WARNING_MESSAGE);
530 System.err.println(errorMessage);
535 updateRecentlyOpened();
537 } catch (Exception er)
539 System.err.println("Exception whilst opening file '" + file);
540 er.printStackTrace();
543 javax.swing.SwingUtilities.invokeLater(new Runnable()
548 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
549 MessageManager.formatMessage(
550 "label.problems_opening_file", new String[]
552 MessageManager.getString("label.file_open_error"),
553 JvOptionPane.WARNING_MESSAGE);
558 } catch (OutOfMemoryError er)
561 er.printStackTrace();
565 javax.swing.SwingUtilities.invokeLater(new Runnable()
570 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
571 MessageManager.formatMessage(
572 "warn.out_of_memory_loading_file", new String[]
574 MessageManager.getString("label.out_of_memory"),
575 JvOptionPane.WARNING_MESSAGE);
579 System.err.println("Out of memory loading file " + file + "!!");
582 loadtime += System.currentTimeMillis();
583 // TODO: Estimate percentage of memory used by a newly loaded alignment -
584 // warn if more memory will be needed to work with it
587 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
592 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
594 if (alignFrame != null)
596 AlignmentI al = alignFrame.getViewport().getAlignment();
598 System.out.println("Loaded '" + title + "' in "
599 + (loadtime / 1000.0) + "s, took an additional "
600 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
601 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
605 // report that we didn't load anything probably due to an out of memory
607 System.out.println("Failed to load '" + title + "' in "
608 + (loadtime / 1000.0) + "s, took an additional "
609 + (1.0 * memused / (1024.0 * 1024.0))
610 + " MB (alignment is null)");
613 // remove the visual delay indicator
614 if (Desktop.instance != null)
616 Desktop.instance.stopLoading();
622 * This method creates the file -
623 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
624 * file name and extension
627 * the name of the temp file to be created
629 * the extension of the temp file to be created
632 private static String createNamedJvTempFile(String fileName,
633 String extension) throws IOException
635 String seprator = System.getProperty("file.separator");
636 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
637 + seprator + System.currentTimeMillis();
638 File tempStructFile = new File(
639 jvTempDir + seprator + fileName + "." + extension);
640 tempStructFile.mkdirs();
641 return tempStructFile.toString();
646 * @param file a File, or a String which is a name of a file
648 * @throws FileNotFoundException
650 public static BufferedReader getBufferedReader(Object file) throws FileNotFoundException {
651 if (file instanceof String)
653 return new BufferedReader(new FileReader((String) file));
655 byte[] bytes = Platform.getFileBytes((File) file);
658 return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
660 return new BufferedReader(new FileReader((File) file));