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.gui.QuitHandler;
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.ws.utils.UrlDownloadClient;
52 public class FileLoader implements Runnable
56 DataSourceType protocol;
60 AlignmentFileReaderI source = null; // alternative specification of where data
65 AlignViewport viewport;
67 AlignFrame alignFrame;
73 boolean raiseGUI = true;
75 private File selectedFile;
78 * default constructor always raised errors in GUI dialog boxes
86 * construct a Fileloader that may raise errors non-interactively
89 * true if errors are to be raised as GUI dialog boxes
91 public FileLoader(boolean raiseGUI)
93 this.raiseGUI = raiseGUI;
96 public void LoadFile(AlignViewport viewport, Object file,
97 DataSourceType protocol, FileFormatI format)
99 LoadFile(viewport, file, protocol, format, true);
102 public void LoadFile(AlignViewport viewport, Object file,
103 DataSourceType protocol, FileFormatI format, boolean async)
105 this.viewport = viewport;
106 if (file instanceof File)
108 this.selectedFile = (File) file;
109 file = selectedFile.getPath();
111 LoadFile(file.toString(), protocol, format, async);
114 public void LoadFile(String file, DataSourceType protocol,
117 LoadFile(file, protocol, format, true);
120 public void LoadFile(String file, DataSourceType protocol,
121 FileFormatI format, boolean async)
124 this.protocol = protocol;
125 this.format = format;
129 final Thread loader = new Thread(this);
131 SwingUtilities.invokeLater(new Runnable()
147 * Load a (file, protocol) source of unknown type
152 public void LoadFile(String file, DataSourceType protocol)
154 LoadFile(file, protocol, null);
158 * Load alignment from (file, protocol) and wait till loaded
162 * @return alignFrame constructed from file contents
164 public AlignFrame LoadFileWaitTillLoaded(String file,
165 DataSourceType sourceType)
167 return LoadFileWaitTillLoaded(file, sourceType, null);
171 * Load alignment from (file, protocol) of type format and wait till loaded
176 * @return alignFrame constructed from file contents
178 public AlignFrame LoadFileWaitTillLoaded(String file,
179 DataSourceType sourceType, FileFormatI format)
182 this.protocol = sourceType;
183 this.format = format;
184 return _LoadFileWaitTillLoaded();
188 * Load alignment from (file, protocol) of type format and wait till loaded
193 * @return alignFrame constructed from file contents
195 public AlignFrame LoadFileWaitTillLoaded(File file,
196 DataSourceType sourceType, FileFormatI format)
198 this.selectedFile = file;
199 this.file = file.getPath();
200 this.protocol = sourceType;
201 this.format = format;
202 return _LoadFileWaitTillLoaded();
206 * Load alignment from FileParse source of type format and wait till loaded
210 * @return alignFrame constructed from file contents
212 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
215 this.source = source;
217 file = source.getInFile();
218 protocol = source.getDataSourceType();
219 this.format = format;
220 return _LoadFileWaitTillLoaded();
224 * runs the 'run' method (in this thread), then return the alignFrame that's
225 * (hopefully) been read
229 protected AlignFrame _LoadFileWaitTillLoaded()
236 public void updateRecentlyOpened()
238 Vector<String> recent = new Vector<>();
239 if (protocol == DataSourceType.PASTE)
241 // do nothing if the file was pasted in as text... there is no filename to
246 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
248 // ignore files loaded from the system's temporary directory
251 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
254 String historyItems = Cache.getProperty(type);
258 if (historyItems != null)
260 st = new StringTokenizer(historyItems, "\t");
262 while (st.hasMoreTokens())
264 recent.addElement(st.nextToken().trim());
268 if (recent.contains(file))
273 StringBuffer newHistory = new StringBuffer(file);
274 for (int i = 0; i < recent.size() && i < 10; i++)
276 newHistory.append("\t");
277 newHistory.append(recent.elementAt(i));
280 Cache.setProperty(type, newHistory.toString());
282 if (protocol == DataSourceType.FILE)
284 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
291 String title = protocol == DataSourceType.PASTE
292 ? "Copied From Clipboard"
294 Runtime rt = Runtime.getRuntime();
298 if (Desktop.instance != null)
300 Desktop.instance.startLoading(file);
304 // just in case the caller didn't identify the file for us
307 format = new IdentifyFile().identify(source, false);
308 // identify stream and rewind rather than close
310 else if (selectedFile != null)
312 format = new IdentifyFile().identify(selectedFile, protocol);
316 format = new IdentifyFile().identify(file, protocol);
323 Desktop.instance.stopLoading();
324 System.err.println("The input file \"" + file
325 + "\" has null or unidentifiable data content!");
326 if (!Jalview.isHeadlessMode())
328 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
329 MessageManager.getString("label.couldnt_read_data")
330 + " in " + file + "\n"
331 + AppletFormatAdapter.getSupportedFormats(),
332 MessageManager.getString("label.couldnt_read_data"),
333 JvOptionPane.WARNING_MESSAGE);
335 // don't set shouldBeSaved if didn't load anything
336 // this.setShouldBeSaved();
339 // TODO: cache any stream datasources as a temporary file (eg. PDBs
340 // retrieved via URL)
341 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
344 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
349 loadtime = -System.currentTimeMillis();
350 AlignmentI al = null;
352 if (FileFormat.Jalview.equals(format))
356 // Tell the user (developer?) that this is going to cause a problem
358 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
359 // We read the data anyway - it might make sense.
361 // BH 2018 switch to File object here instead of filename
362 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
363 selectedFile == null ? file : selectedFile);
367 String error = AppletFormatAdapter.getSupportedFormats();
372 // read from the provided source
373 al = new FormatAdapter().readFromFile(source, format);
378 // open a new source and read from it
379 FormatAdapter fa = new FormatAdapter();
380 boolean downloadStructureFile = format.isStructureFile()
381 && protocol.equals(DataSourceType.URL);
382 if (downloadStructureFile)
384 String structExt = format.getExtensions().split(",")[0];
385 String urlLeafName = file.substring(
387 System.getProperty("file.separator")),
388 file.lastIndexOf("."));
389 String tempStructureFileStr = createNamedJvTempFile(
390 urlLeafName, structExt);
392 // BH - switching to File object here so as to hold
393 // ._bytes array directly
394 File tempFile = new File(tempStructureFileStr);
395 UrlDownloadClient.download(file, tempFile);
397 al = fa.readFile(tempFile, DataSourceType.FILE, format);
398 source = fa.getAlignFile();
402 if (selectedFile == null)
404 al = fa.readFile(null, file, protocol, format);
409 al = fa.readFile(selectedFile, null, protocol, format);
411 source = fa.getAlignFile(); // keep reference for later if
416 } catch (java.io.IOException ex)
418 error = ex.getMessage();
421 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
423 // construct and register dataset sequences
424 for (SequenceI sq : al.getSequences())
426 while (sq.getDatasetSequence() != null)
428 sq = sq.getDatasetSequence();
430 if (sq.getAllPDBEntries() != null)
432 for (PDBEntry pdbe : sq.getAllPDBEntries())
434 // register PDB entries with desktop's structure selection
436 StructureSelectionManager
437 .getStructureSelectionManager(Desktop.instance)
438 .registerPDBEntry(pdbe);
443 FeatureSettingsModelI proxyColourScheme = source
444 .getFeatureColourScheme();
445 if (viewport != null)
447 // append to existing alignment
448 viewport.addAlignment(al, title);
449 viewport.applyFeaturesStyle(proxyColourScheme);
453 // otherwise construct the alignFrame
455 if (source instanceof ComplexAlignFile)
457 HiddenColumns colSel = ((ComplexAlignFile) source)
459 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
460 .getHiddenSequences();
461 String colourSchemeName = ((ComplexAlignFile) source)
462 .getGlobalColourScheme();
463 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
464 .getDisplayedFeatures();
465 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
466 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
467 alignFrame.getViewport().setFeaturesDisplayed(fd);
468 alignFrame.getViewport().setShowSequenceFeatures(
469 ((ComplexAlignFile) source).isShowSeqFeatures());
470 ColourSchemeI cs = ColourSchemeMapper
471 .getJalviewColourScheme(colourSchemeName, al);
474 alignFrame.changeColour(cs);
479 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
480 AlignFrame.DEFAULT_HEIGHT);
481 if (source instanceof FeaturesSourceI)
483 alignFrame.getViewport().setShowSequenceFeatures(true);
486 // add metadata and update ui
487 if (!(protocol == DataSourceType.PASTE))
489 alignFrame.setFileName(file, format);
490 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
492 if (proxyColourScheme != null)
494 alignFrame.getViewport()
495 .applyFeaturesStyle(proxyColourScheme);
497 alignFrame.setStatus(MessageManager.formatMessage(
498 "label.successfully_loaded_file", new String[]
503 // add the window to the GUI
504 // note - this actually should happen regardless of raiseGUI
505 // status in Jalview 3
506 // TODO: define 'virtual desktop' for benefit of headless scripts
507 // that perform queries to find the 'current working alignment'
508 Desktop.addInternalFrame(alignFrame, title,
509 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
512 * for an Overview automatically opened with alignment,
513 * set its title now alignFrame title has been set
515 alignFrame.alignPanel.setOverviewTitle(alignFrame);
520 alignFrame.setMaximum(
521 Cache.getDefault("SHOW_FULLSCREEN", false));
522 } catch (java.beans.PropertyVetoException ex)
529 if (Desktop.instance != null)
531 Desktop.instance.stopLoading();
534 final String errorMessage = MessageManager.getString(
535 "label.couldnt_load_file") + " " + title + "\n" + error;
536 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
538 if (raiseGUI && Desktop.desktop != null)
540 javax.swing.SwingUtilities.invokeLater(new Runnable()
545 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
548 .getString("label.error_loading_file"),
549 JvOptionPane.WARNING_MESSAGE);
555 System.err.println(errorMessage);
560 updateRecentlyOpened();
562 } catch (Exception er)
564 System.err.println("Exception whilst opening file '" + file);
565 er.printStackTrace();
568 javax.swing.SwingUtilities.invokeLater(new Runnable()
573 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
574 MessageManager.formatMessage(
575 "label.problems_opening_file", new String[]
577 MessageManager.getString("label.file_open_error"),
578 JvOptionPane.WARNING_MESSAGE);
583 } catch (OutOfMemoryError er)
586 er.printStackTrace();
590 javax.swing.SwingUtilities.invokeLater(new Runnable()
595 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
596 MessageManager.formatMessage(
597 "warn.out_of_memory_loading_file", new String[]
599 MessageManager.getString("label.out_of_memory"),
600 JvOptionPane.WARNING_MESSAGE);
604 System.err.println("Out of memory loading file " + file + "!!");
607 loadtime += System.currentTimeMillis();
608 // TODO: Estimate percentage of memory used by a newly loaded alignment -
609 // warn if more memory will be needed to work with it
612 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
617 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
619 if (alignFrame != null)
621 AlignmentI al = alignFrame.getViewport().getAlignment();
623 System.out.println("Loaded '" + title + "' in "
624 + (loadtime / 1000.0) + "s, took an additional "
625 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
626 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
630 // report that we didn't load anything probably due to an out of memory
632 System.out.println("Failed to load '" + title + "' in "
633 + (loadtime / 1000.0) + "s, took an additional "
634 + (1.0 * memused / (1024.0 * 1024.0))
635 + " MB (alignment is null)");
638 // remove the visual delay indicator
639 if (Desktop.instance != null)
641 Desktop.instance.stopLoading();
644 this.setShouldBeSaved();
648 * This method creates the file -
649 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
650 * file name and extension
653 * the name of the temp file to be created
655 * the extension of the temp file to be created
658 private static String createNamedJvTempFile(String fileName,
659 String extension) throws IOException
661 String seprator = System.getProperty("file.separator");
662 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
663 + seprator + System.currentTimeMillis();
664 File tempStructFile = new File(
665 jvTempDir + seprator + fileName + "." + extension);
666 tempStructFile.mkdirs();
667 return tempStructFile.toString();
671 * set whether quit should ask to save when just loaded this source
673 private void setShouldBeSaved()
675 if (protocol == null)
677 AlignFrame af = this.alignFrame;
680 AlignViewport avp = af.getViewport();
683 avp.setSavedUpToDate(!protocol.isDynamic(),
684 QuitHandler.Message.UNSAVED_ALIGNMENTS);