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 this.viewport = viewport;
100 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();
279 if (Desktop.instance != null)
281 Desktop.instance.startLoading(file);
285 // just in case the caller didn't identify the file for us
288 format = new IdentifyFile().identify(source, false);
289 // identify stream and rewind rather than close
291 else if (selectedFile != null)
293 format = new IdentifyFile().identify(selectedFile, protocol);
297 format = new IdentifyFile().identify(file, protocol);
304 Desktop.instance.stopLoading();
305 System.err.println("The input file \"" + file
306 + "\" has null or unidentifiable data content!");
307 if (!Jalview.isHeadlessMode())
309 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
310 MessageManager.getString("label.couldnt_read_data")
311 + " in " + file + "\n"
312 + AppletFormatAdapter.getSupportedFormats(),
313 MessageManager.getString("label.couldnt_read_data"),
314 JvOptionPane.WARNING_MESSAGE);
316 this.setShouldBeSaved();
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(
343 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, format);
378 source = fa.getAlignFile();
382 if (selectedFile == null)
384 al = fa.readFile(null, file, protocol, format);
389 al = fa.readFile(selectedFile, null, protocol, format);
391 source = fa.getAlignFile(); // keep reference for later if
396 } catch (java.io.IOException ex)
398 error = ex.getMessage();
401 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
403 // construct and register dataset sequences
404 for (SequenceI sq : al.getSequences())
406 while (sq.getDatasetSequence() != null)
408 sq = sq.getDatasetSequence();
410 if (sq.getAllPDBEntries() != null)
412 for (PDBEntry pdbe : sq.getAllPDBEntries())
414 // register PDB entries with desktop's structure selection
416 StructureSelectionManager
417 .getStructureSelectionManager(Desktop.instance)
418 .registerPDBEntry(pdbe);
423 FeatureSettingsModelI proxyColourScheme = source
424 .getFeatureColourScheme();
425 if (viewport != null)
427 // append to existing alignment
428 viewport.addAlignment(al, title);
429 viewport.applyFeaturesStyle(proxyColourScheme);
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);
492 * for an Overview automatically opened with alignment,
493 * set its title now alignFrame title has been set
495 alignFrame.alignPanel.setOverviewTitle(alignFrame);
500 alignFrame.setMaximum(
501 Cache.getDefault("SHOW_FULLSCREEN", false));
502 } catch (java.beans.PropertyVetoException ex)
509 if (Desktop.instance != null)
511 Desktop.instance.stopLoading();
514 final String errorMessage = MessageManager.getString(
515 "label.couldnt_load_file") + " " + title + "\n" + error;
516 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
518 if (raiseGUI && Desktop.desktop != null)
520 javax.swing.SwingUtilities.invokeLater(new Runnable()
525 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
528 .getString("label.error_loading_file"),
529 JvOptionPane.WARNING_MESSAGE);
535 System.err.println(errorMessage);
540 updateRecentlyOpened();
542 } catch (Exception er)
544 System.err.println("Exception whilst opening file '" + file);
545 er.printStackTrace();
548 javax.swing.SwingUtilities.invokeLater(new Runnable()
553 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
554 MessageManager.formatMessage(
555 "label.problems_opening_file", new String[]
557 MessageManager.getString("label.file_open_error"),
558 JvOptionPane.WARNING_MESSAGE);
563 } catch (OutOfMemoryError er)
566 er.printStackTrace();
570 javax.swing.SwingUtilities.invokeLater(new Runnable()
575 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
576 MessageManager.formatMessage(
577 "warn.out_of_memory_loading_file", new String[]
579 MessageManager.getString("label.out_of_memory"),
580 JvOptionPane.WARNING_MESSAGE);
584 System.err.println("Out of memory loading file " + file + "!!");
587 loadtime += System.currentTimeMillis();
588 // TODO: Estimate percentage of memory used by a newly loaded alignment -
589 // warn if more memory will be needed to work with it
592 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
597 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
599 if (alignFrame != null)
601 AlignmentI al = alignFrame.getViewport().getAlignment();
603 System.out.println("Loaded '" + title + "' in "
604 + (loadtime / 1000.0) + "s, took an additional "
605 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
606 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
610 // report that we didn't load anything probably due to an out of memory
612 System.out.println("Failed to load '" + title + "' in "
613 + (loadtime / 1000.0) + "s, took an additional "
614 + (1.0 * memused / (1024.0 * 1024.0))
615 + " MB (alignment is null)");
618 // remove the visual delay indicator
619 if (Desktop.instance != null)
621 Desktop.instance.stopLoading();
624 this.setShouldBeSaved();
628 * This method creates the file -
629 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
630 * file name and extension
633 * the name of the temp file to be created
635 * the extension of the temp file to be created
638 private static String createNamedJvTempFile(String fileName,
639 String extension) throws IOException
641 String seprator = System.getProperty("file.separator");
642 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
643 + seprator + System.currentTimeMillis();
644 File tempStructFile = new File(
645 jvTempDir + seprator + fileName + "." + extension);
646 tempStructFile.mkdirs();
647 return tempStructFile.toString();
651 * set whether quit should ask to save when just loaded this source
653 private void setShouldBeSaved()
655 if (protocol == null)
657 AlignFrame af = this.alignFrame;
660 AlignViewport avp = af.getViewport();
663 avp.setSavedUpToDate(!protocol.isDynamic(),
664 QuitHandler.Message.UNSAVED_ALIGNMENTS);