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 java.awt.Dimension;
25 import java.io.IOException;
26 import java.util.StringTokenizer;
27 import java.util.Vector;
29 import javax.swing.SwingUtilities;
31 import jalview.api.ComplexAlignFile;
32 import jalview.api.FeatureSettingsModelI;
33 import jalview.api.FeaturesDisplayedI;
34 import jalview.api.FeaturesSourceI;
35 import jalview.bin.Cache;
36 import jalview.bin.Jalview;
37 import jalview.datamodel.AlignmentI;
38 import jalview.datamodel.HiddenColumns;
39 import jalview.datamodel.PDBEntry;
40 import jalview.datamodel.SequenceI;
41 import jalview.gui.AlignFrame;
42 import jalview.gui.AlignViewport;
43 import jalview.gui.Desktop;
44 import jalview.gui.JvOptionPane;
45 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
46 import jalview.project.Jalview2XML;
47 import jalview.schemes.ColourSchemeI;
48 import jalview.structure.StructureSelectionManager;
49 import jalview.util.MessageManager;
50 import jalview.util.Platform;
51 import jalview.ws.utils.UrlDownloadClient;
53 public class FileLoader implements Runnable
57 DataSourceType protocol;
61 AlignmentFileReaderI source = null; // alternative specification of where data
66 AlignViewport viewport;
68 AlignFrame alignFrame;
74 boolean raiseGUI = true;
76 private File selectedFile;
79 * default constructor always raised errors in GUI dialog boxes
87 * construct a Fileloader that may raise errors non-interactively
90 * true if errors are to be raised as GUI dialog boxes
92 public FileLoader(boolean raiseGUI)
94 this.raiseGUI = raiseGUI;
97 public void LoadFile(AlignViewport viewport, Object file,
98 DataSourceType protocol, FileFormatI format)
100 this.viewport = viewport;
101 if (file instanceof File) {
102 this.selectedFile = (File) file;
103 file = selectedFile.getPath();
105 LoadFile(file.toString(), protocol, format);
108 public void LoadFile(String file, DataSourceType protocol,
112 this.protocol = protocol;
113 this.format = format;
115 final Thread loader = new Thread(this);
117 SwingUtilities.invokeLater(new Runnable()
128 * Load a (file, protocol) source of unknown type
133 public void LoadFile(String file, DataSourceType protocol)
135 LoadFile(file, protocol, null);
139 * Load alignment from (file, protocol) and wait till loaded
143 * @return alignFrame constructed from file contents
145 public AlignFrame LoadFileWaitTillLoaded(String file,
146 DataSourceType sourceType)
148 return LoadFileWaitTillLoaded(file, sourceType, null);
152 * Load alignment from (file, protocol) of type format and wait till loaded
157 * @return alignFrame constructed from file contents
159 public AlignFrame LoadFileWaitTillLoaded(String file,
160 DataSourceType sourceType, FileFormatI format)
163 this.protocol = sourceType;
164 this.format = format;
165 return _LoadFileWaitTillLoaded();
169 * Load alignment from (file, protocol) of type format and wait till loaded
174 * @return alignFrame constructed from file contents
176 public AlignFrame LoadFileWaitTillLoaded(File file,
177 DataSourceType sourceType, FileFormatI format)
179 this.selectedFile = file;
180 this.file = file.getPath();
181 this.protocol = sourceType;
182 this.format = format;
183 return _LoadFileWaitTillLoaded();
187 * Load alignment from FileParse source of type format and wait till loaded
191 * @return alignFrame constructed from file contents
193 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
196 this.source = source;
198 file = source.getInFile();
199 protocol = source.getDataSourceType();
200 this.format = format;
201 return _LoadFileWaitTillLoaded();
205 * runs the 'run' method (in this thread), then return the alignFrame that's
206 * (hopefully) been read
210 protected AlignFrame _LoadFileWaitTillLoaded()
217 public void updateRecentlyOpened()
219 Vector<String> recent = new Vector<>();
220 if (protocol == DataSourceType.PASTE)
222 // do nothing if the file was pasted in as text... there is no filename to
227 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
229 // ignore files loaded from the system's temporary directory
232 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
235 String historyItems = Cache.getProperty(type);
239 if (historyItems != null)
241 st = new StringTokenizer(historyItems, "\t");
243 while (st.hasMoreTokens())
245 recent.addElement(st.nextToken().trim());
249 if (recent.contains(file))
254 StringBuffer newHistory = new StringBuffer(file);
255 for (int i = 0; i < recent.size() && i < 10; i++)
257 newHistory.append("\t");
258 newHistory.append(recent.elementAt(i));
261 Cache.setProperty(type, newHistory.toString());
263 if (protocol == DataSourceType.FILE)
265 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
272 String title = protocol == DataSourceType.PASTE
273 ? "Copied From Clipboard"
275 Runtime rt = Runtime.getRuntime();
278 if (Desktop.getInstance() != null)
280 Desktop.getInstance().startLoading(file);
284 // just in case the caller didn't identify the file for us
287 format = new IdentifyFile().identify(source, false);
288 // identify stream and rewind rather than close
290 else if (selectedFile != null) {
291 format = new IdentifyFile().identify(selectedFile, protocol);
295 format = new IdentifyFile().identify(file, protocol);
302 Desktop.getInstance().stopLoading();
303 System.err.println("The input file \"" + file
304 + "\" has null or unidentifiable data content!");
305 if (!Jalview.isHeadlessMode())
307 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
308 MessageManager.getString("label.couldnt_read_data")
309 + " in " + file + "\n"
310 + AppletFormatAdapter.getSupportedFormats(),
311 MessageManager.getString("label.couldnt_read_data"),
312 JvOptionPane.WARNING_MESSAGE);
316 // TODO: cache any stream datasources as a temporary file (eg. PDBs
317 // retrieved via URL)
318 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
321 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
326 loadtime = -System.currentTimeMillis();
327 AlignmentI al = null;
329 if (FileFormat.Jalview.equals(format))
333 // Tell the user (developer?) that this is going to cause a problem
335 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
336 // We read the data anyway - it might make sense.
338 // BH 2018 switch to File object here instead of filename
339 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
343 String error = AppletFormatAdapter.getSupportedFormats();
348 // read from the provided source
349 al = new FormatAdapter().readFromFile(source, format);
354 // open a new source and read from it
355 FormatAdapter fa = new FormatAdapter();
356 boolean downloadStructureFile = format.isStructureFile()
357 && protocol.equals(DataSourceType.URL);
358 if (downloadStructureFile)
360 String structExt = format.getExtensions().split(",")[0];
361 String urlLeafName = file.substring(
363 System.getProperty("file.separator")),
364 file.lastIndexOf("."));
365 String tempStructureFileStr = createNamedJvTempFile(
366 urlLeafName, structExt);
368 // BH - switching to File object here so as to hold
369 // ._bytes array directly
370 File tempFile = new File(tempStructureFileStr);
371 UrlDownloadClient.download(file, tempFile);
373 al = fa.readFile(tempFile, DataSourceType.FILE,
375 source = fa.getAlignFile();
379 if (selectedFile == null) {
380 al = fa.readFile(file, protocol, format);
383 al = fa.readFile(selectedFile, protocol, format);
385 source = fa.getAlignFile(); // keep reference for later if
390 } catch (java.io.IOException ex)
392 error = ex.getMessage();
395 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
397 // construct and register dataset sequences
398 for (SequenceI sq : al.getSequences())
400 while (sq.getDatasetSequence() != null)
402 sq = sq.getDatasetSequence();
404 if (sq.getAllPDBEntries() != null)
406 for (PDBEntry pdbe : sq.getAllPDBEntries())
408 // register PDB entries with desktop's structure selection
410 StructureSelectionManager
411 .getStructureSelectionManager(Desktop.getInstance())
412 .registerPDBEntry(pdbe);
417 FeatureSettingsModelI proxyColourScheme = source
418 .getFeatureColourScheme();
419 if (viewport != null)
421 if (proxyColourScheme != null)
423 viewport.applyFeaturesStyle(proxyColourScheme);
425 // append to existing alignment
426 viewport.addAlignment(al, title);
430 // otherwise construct the alignFrame
432 if (source instanceof ComplexAlignFile)
434 HiddenColumns colSel = ((ComplexAlignFile) source)
436 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
437 .getHiddenSequences();
438 String colourSchemeName = ((ComplexAlignFile) source)
439 .getGlobalColourScheme();
440 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
441 .getDisplayedFeatures();
442 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
443 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
444 alignFrame.getViewport().setFeaturesDisplayed(fd);
445 alignFrame.getViewport().setShowSequenceFeatures(
446 ((ComplexAlignFile) source).isShowSeqFeatures());
447 ColourSchemeI cs = ColourSchemeMapper
448 .getJalviewColourScheme(colourSchemeName, al);
451 alignFrame.changeColour(cs);
456 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
457 AlignFrame.DEFAULT_HEIGHT);
458 if (source instanceof FeaturesSourceI)
460 alignFrame.getViewport().setShowSequenceFeatures(true);
463 // add metadata and update ui
464 if (!(protocol == DataSourceType.PASTE))
466 alignFrame.setFileName(file, format);
467 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
469 if (proxyColourScheme != null)
471 alignFrame.getViewport()
472 .applyFeaturesStyle(proxyColourScheme);
474 alignFrame.setStatus(MessageManager.formatMessage(
475 "label.successfully_loaded_file", new String[]
480 // add the window to the GUI
481 // note - this actually should happen regardless of raiseGUI
482 // status in Jalview 3
483 // TODO: define 'virtual desktop' for benefit of headless scripts
484 // that perform queries to find the 'current working alignment'
486 Dimension dim = Platform.getDimIfEmbedded(alignFrame,
487 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
488 alignFrame.setSize(dim);
489 Desktop.addInternalFrame(alignFrame, title, dim.width,
495 alignFrame.setMaximum(jalview.bin.Cache
496 .getDefault("SHOW_FULLSCREEN", false));
497 } catch (java.beans.PropertyVetoException ex)
504 if (Desktop.getInstance() != null)
506 Desktop.getInstance().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.getDesktopPane() != null)
515 javax.swing.SwingUtilities.invokeLater(new Runnable()
520 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
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.getDesktopPane(),
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.getDesktopPane(),
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.getDesktopPane() != null && Desktop.getDesktopPane().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.getInstance() != null)
616 Desktop.getInstance().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();