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.
24 import java.io.IOException;
25 import java.util.StringTokenizer;
26 import java.util.Vector;
28 import javax.swing.SwingUtilities;
30 import jalview.api.ComplexAlignFile;
31 import jalview.api.FeatureSettingsModelI;
32 import jalview.api.FeaturesDisplayedI;
33 import jalview.api.FeaturesSourceI;
34 import jalview.bin.Cache;
35 import jalview.bin.Jalview;
36 import jalview.datamodel.AlignmentI;
37 import jalview.datamodel.HiddenColumns;
38 import jalview.datamodel.PDBEntry;
39 import jalview.datamodel.SequenceI;
40 import jalview.gui.AlignFrame;
41 import jalview.gui.AlignViewport;
42 import jalview.gui.Desktop;
43 import jalview.gui.JvOptionPane;
44 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
45 import jalview.project.Jalview2XML;
46 import jalview.schemes.ColourSchemeI;
47 import jalview.structure.StructureSelectionManager;
48 import jalview.util.MessageManager;
49 import jalview.ws.utils.UrlDownloadClient;
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;
74 private File selectedFile;
77 * default constructor always raised errors in GUI dialog boxes
85 * construct a Fileloader that may raise errors non-interactively
88 * true if errors are to be raised as GUI dialog boxes
90 public FileLoader(boolean raiseGUI)
92 this.raiseGUI = raiseGUI;
95 public void LoadFile(AlignViewport viewport, Object file,
96 DataSourceType protocol, FileFormatI format)
98 this.viewport = viewport;
99 if (file instanceof File) {
100 this.selectedFile = (File) file;
101 file = selectedFile.getPath();
103 LoadFile(file.toString(), protocol, format);
106 public void LoadFile(String file, DataSourceType protocol,
110 this.protocol = protocol;
111 this.format = format;
113 final Thread loader = new Thread(this);
115 SwingUtilities.invokeLater(new Runnable()
126 * Load a (file, protocol) source of unknown type
131 public void LoadFile(String file, DataSourceType protocol)
133 LoadFile(file, protocol, null);
137 * Load alignment from (file, protocol) and wait till loaded
141 * @return alignFrame constructed from file contents
143 public AlignFrame LoadFileWaitTillLoaded(String file,
144 DataSourceType sourceType)
146 return LoadFileWaitTillLoaded(file, sourceType, null);
150 * Load alignment from (file, protocol) of type format and wait till loaded
155 * @return alignFrame constructed from file contents
157 public AlignFrame LoadFileWaitTillLoaded(String file,
158 DataSourceType sourceType, FileFormatI format)
161 this.protocol = sourceType;
162 this.format = format;
163 return _LoadFileWaitTillLoaded();
167 * Load alignment from (file, protocol) of type format and wait till loaded
172 * @return alignFrame constructed from file contents
174 public AlignFrame LoadFileWaitTillLoaded(File file,
175 DataSourceType sourceType, FileFormatI format)
177 this.selectedFile = file;
178 this.file = file.getPath();
179 this.protocol = sourceType;
180 this.format = format;
181 return _LoadFileWaitTillLoaded();
185 * Load alignment from FileParse source of type format and wait till loaded
189 * @return alignFrame constructed from file contents
191 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
194 this.source = source;
196 file = source.getInFile();
197 protocol = source.getDataSourceType();
198 this.format = format;
199 return _LoadFileWaitTillLoaded();
203 * runs the 'run' method (in this thread), then return the alignFrame that's
204 * (hopefully) been read
208 protected AlignFrame _LoadFileWaitTillLoaded()
215 public void updateRecentlyOpened()
217 Vector<String> recent = new Vector<>();
218 if (protocol == DataSourceType.PASTE)
220 // do nothing if the file was pasted in as text... there is no filename to
225 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
227 // ignore files loaded from the system's temporary directory
230 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
233 String historyItems = Cache.getProperty(type);
237 if (historyItems != null)
239 st = new StringTokenizer(historyItems, "\t");
241 while (st.hasMoreTokens())
243 recent.addElement(st.nextToken().trim());
247 if (recent.contains(file))
252 StringBuffer newHistory = new StringBuffer(file);
253 for (int i = 0; i < recent.size() && i < 10; i++)
255 newHistory.append("\t");
256 newHistory.append(recent.elementAt(i));
259 Cache.setProperty(type, newHistory.toString());
261 if (protocol == DataSourceType.FILE)
263 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
270 String title = protocol == DataSourceType.PASTE
271 ? "Copied From Clipboard"
273 Runtime rt = Runtime.getRuntime();
276 if (Desktop.instance != null)
278 Desktop.instance.startLoading(file);
282 // just in case the caller didn't identify the file for us
285 format = new IdentifyFile().identify(source, false);
286 // identify stream and rewind rather than close
288 else if (selectedFile != null) {
289 format = new IdentifyFile().identify(selectedFile, protocol);
293 format = new IdentifyFile().identify(file, protocol);
300 Desktop.instance.stopLoading();
301 System.err.println("The input file \"" + file
302 + "\" has null or unidentifiable data content!");
303 if (!Jalview.isHeadlessMode())
305 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
306 MessageManager.getString("label.couldnt_read_data")
307 + " in " + file + "\n"
308 + AppletFormatAdapter.getSupportedFormats(),
309 MessageManager.getString("label.couldnt_read_data"),
310 JvOptionPane.WARNING_MESSAGE);
314 // TODO: cache any stream datasources as a temporary file (eg. PDBs
315 // retrieved via URL)
316 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
319 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
324 loadtime = -System.currentTimeMillis();
325 AlignmentI al = null;
327 if (FileFormat.Jalview.equals(format))
331 // Tell the user (developer?) that this is going to cause a problem
333 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
334 // We read the data anyway - it might make sense.
336 // BH 2018 switch to File object here instead of filename
337 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
341 String error = AppletFormatAdapter.getSupportedFormats();
346 // read from the provided source
347 al = new FormatAdapter().readFromFile(source, format);
352 // open a new source and read from it
353 FormatAdapter fa = new FormatAdapter();
354 boolean downloadStructureFile = format.isStructureFile()
355 && protocol.equals(DataSourceType.URL);
356 if (downloadStructureFile)
358 String structExt = format.getExtensions().split(",")[0];
359 String urlLeafName = file.substring(
361 System.getProperty("file.separator")),
362 file.lastIndexOf("."));
363 String tempStructureFileStr = createNamedJvTempFile(
364 urlLeafName, structExt);
366 // BH - switching to File object here so as to hold
367 // ._bytes array directly
368 File tempFile = new File(tempStructureFileStr);
369 UrlDownloadClient.download(file, tempFile);
371 al = fa.readFile(tempFile, DataSourceType.FILE,
373 source = fa.getAlignFile();
377 if (selectedFile == null) {
378 al = fa.readFile(file, protocol, format);
381 al = fa.readFile(selectedFile, protocol, format);
383 source = fa.getAlignFile(); // keep reference for later if
388 } catch (java.io.IOException ex)
390 error = ex.getMessage();
393 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
395 // construct and register dataset sequences
396 for (SequenceI sq : al.getSequences())
398 while (sq.getDatasetSequence() != null)
400 sq = sq.getDatasetSequence();
402 if (sq.getAllPDBEntries() != null)
404 for (PDBEntry pdbe : sq.getAllPDBEntries())
406 // register PDB entries with desktop's structure selection
408 StructureSelectionManager
409 .getStructureSelectionManager(Desktop.instance)
410 .registerPDBEntry(pdbe);
415 FeatureSettingsModelI proxyColourScheme = source
416 .getFeatureColourScheme();
417 if (viewport != null)
419 if (proxyColourScheme != null)
421 viewport.applyFeaturesStyle(proxyColourScheme);
423 // append to existing alignment
424 viewport.addAlignment(al, title);
428 // otherwise construct the alignFrame
430 if (source instanceof ComplexAlignFile)
432 HiddenColumns colSel = ((ComplexAlignFile) source)
434 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
435 .getHiddenSequences();
436 String colourSchemeName = ((ComplexAlignFile) source)
437 .getGlobalColourScheme();
438 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
439 .getDisplayedFeatures();
440 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
441 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
442 alignFrame.getViewport().setFeaturesDisplayed(fd);
443 alignFrame.getViewport().setShowSequenceFeatures(
444 ((ComplexAlignFile) source).isShowSeqFeatures());
445 ColourSchemeI cs = ColourSchemeMapper
446 .getJalviewColourScheme(colourSchemeName, al);
449 alignFrame.changeColour(cs);
454 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
455 AlignFrame.DEFAULT_HEIGHT);
456 if (source instanceof FeaturesSourceI)
458 alignFrame.getViewport().setShowSequenceFeatures(true);
461 // add metadata and update ui
462 if (!(protocol == DataSourceType.PASTE))
464 alignFrame.setFileName(file, format);
465 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
467 if (proxyColourScheme != null)
469 alignFrame.getViewport()
470 .applyFeaturesStyle(proxyColourScheme);
472 alignFrame.setStatus(MessageManager.formatMessage(
473 "label.successfully_loaded_file", new String[]
478 // add the window to the GUI
479 // note - this actually should happen regardless of raiseGUI
480 // status in Jalview 3
481 // TODO: define 'virtual desktop' for benefit of headless scripts
482 // that perform queries to find the 'current working alignment'
483 Desktop.addInternalFrame(alignFrame, title,
484 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
489 alignFrame.setMaximum(jalview.bin.Cache
490 .getDefault("SHOW_FULLSCREEN", false));
491 } catch (java.beans.PropertyVetoException ex)
498 if (Desktop.instance != null)
500 Desktop.instance.stopLoading();
503 final String errorMessage = MessageManager.getString(
504 "label.couldnt_load_file") + " " + title + "\n" + error;
505 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
507 if (raiseGUI && Desktop.desktop != null)
509 javax.swing.SwingUtilities.invokeLater(new Runnable()
514 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
517 .getString("label.error_loading_file"),
518 JvOptionPane.WARNING_MESSAGE);
524 System.err.println(errorMessage);
529 updateRecentlyOpened();
531 } catch (Exception er)
533 System.err.println("Exception whilst opening file '" + file);
534 er.printStackTrace();
537 javax.swing.SwingUtilities.invokeLater(new Runnable()
542 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
543 MessageManager.formatMessage(
544 "label.problems_opening_file", new String[]
546 MessageManager.getString("label.file_open_error"),
547 JvOptionPane.WARNING_MESSAGE);
552 } catch (OutOfMemoryError er)
555 er.printStackTrace();
559 javax.swing.SwingUtilities.invokeLater(new Runnable()
564 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
565 MessageManager.formatMessage(
566 "warn.out_of_memory_loading_file", new String[]
568 MessageManager.getString("label.out_of_memory"),
569 JvOptionPane.WARNING_MESSAGE);
573 System.err.println("Out of memory loading file " + file + "!!");
576 loadtime += System.currentTimeMillis();
577 // TODO: Estimate percentage of memory used by a newly loaded alignment -
578 // warn if more memory will be needed to work with it
581 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
586 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
588 if (alignFrame != null)
590 AlignmentI al = alignFrame.getViewport().getAlignment();
592 System.out.println("Loaded '" + title + "' in "
593 + (loadtime / 1000.0) + "s, took an additional "
594 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
595 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
599 // report that we didn't load anything probably due to an out of memory
601 System.out.println("Failed to load '" + title + "' in "
602 + (loadtime / 1000.0) + "s, took an additional "
603 + (1.0 * memused / (1024.0 * 1024.0))
604 + " MB (alignment is null)");
607 // remove the visual delay indicator
608 if (Desktop.instance != null)
610 Desktop.instance.stopLoading();
616 * This method creates the file -
617 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
618 * file name and extension
621 * the name of the temp file to be created
623 * the extension of the temp file to be created
626 private static String createNamedJvTempFile(String fileName,
627 String extension) throws IOException
629 String seprator = System.getProperty("file.separator");
630 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
631 + seprator + System.currentTimeMillis();
632 File tempStructFile = new File(
633 jvTempDir + seprator + fileName + "." + extension);
634 tempStructFile.mkdirs();
635 return tempStructFile.toString();