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.JInternalFrame;
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.gui.OverviewPanel;
46 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
47 import jalview.project.Jalview2XML;
48 import jalview.schemes.ColourSchemeI;
49 import jalview.structure.StructureSelectionManager;
50 import jalview.util.MessageManager;
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.instance != null)
280 Desktop.instance.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.instance.stopLoading();
303 System.err.println("The input file \"" + file
304 + "\" has null or unidentifiable data content!");
305 if (!Jalview.isHeadlessMode())
307 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
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.desktop != null && Desktop.desktop.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.instance)
412 .registerPDBEntry(pdbe);
417 FeatureSettingsModelI proxyColourScheme = source
418 .getFeatureColourScheme();
419 if (viewport != null)
421 // append to existing alignment
422 viewport.addAlignment(al, title);
423 viewport.applyFeaturesStyle(proxyColourScheme);
427 // otherwise construct the alignFrame
429 if (source instanceof ComplexAlignFile)
431 HiddenColumns colSel = ((ComplexAlignFile) source)
433 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
434 .getHiddenSequences();
435 String colourSchemeName = ((ComplexAlignFile) source)
436 .getGlobalColourScheme();
437 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
438 .getDisplayedFeatures();
439 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
440 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
441 alignFrame.getViewport().setFeaturesDisplayed(fd);
442 alignFrame.getViewport().setShowSequenceFeatures(
443 ((ComplexAlignFile) source).isShowSeqFeatures());
444 ColourSchemeI cs = ColourSchemeMapper
445 .getJalviewColourScheme(colourSchemeName, al);
448 alignFrame.changeColour(cs);
453 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
454 AlignFrame.DEFAULT_HEIGHT);
455 if (source instanceof FeaturesSourceI)
457 alignFrame.getViewport().setShowSequenceFeatures(true);
460 // add metadata and update ui
461 if (!(protocol == DataSourceType.PASTE))
463 alignFrame.setFileName(file, format);
464 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
466 if (proxyColourScheme != null)
468 alignFrame.getViewport()
469 .applyFeaturesStyle(proxyColourScheme);
471 alignFrame.setStatus(MessageManager.formatMessage(
472 "label.successfully_loaded_file", new String[]
477 // add the window to the GUI
478 // note - this actually should happen regardless of raiseGUI
479 // status in Jalview 3
480 // TODO: define 'virtual desktop' for benefit of headless scripts
481 // that perform queries to find the 'current working alignment'
482 Desktop.addInternalFrame(alignFrame, title,
483 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
485 OverviewPanel ov = alignFrame.alignPanel.getOverviewPanel();
489 * Overview automatically opened with alignment
490 * - set its title now alignFrame title has been set
492 String ttl = alignFrame.getOverviewTitle();
493 ((JInternalFrame) SwingUtilities
494 .getAncestorOfClass(JInternalFrame.class, ov))
502 alignFrame.setMaximum(jalview.bin.Cache
503 .getDefault("SHOW_FULLSCREEN", false));
504 } catch (java.beans.PropertyVetoException ex)
511 if (Desktop.instance != null)
513 Desktop.instance.stopLoading();
516 final String errorMessage = MessageManager.getString(
517 "label.couldnt_load_file") + " " + title + "\n" + error;
518 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
520 if (raiseGUI && Desktop.desktop != null)
522 javax.swing.SwingUtilities.invokeLater(new Runnable()
527 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
530 .getString("label.error_loading_file"),
531 JvOptionPane.WARNING_MESSAGE);
537 System.err.println(errorMessage);
542 updateRecentlyOpened();
544 } catch (Exception er)
546 System.err.println("Exception whilst opening file '" + file);
547 er.printStackTrace();
550 javax.swing.SwingUtilities.invokeLater(new Runnable()
555 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
556 MessageManager.formatMessage(
557 "label.problems_opening_file", new String[]
559 MessageManager.getString("label.file_open_error"),
560 JvOptionPane.WARNING_MESSAGE);
565 } catch (OutOfMemoryError er)
568 er.printStackTrace();
572 javax.swing.SwingUtilities.invokeLater(new Runnable()
577 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
578 MessageManager.formatMessage(
579 "warn.out_of_memory_loading_file", new String[]
581 MessageManager.getString("label.out_of_memory"),
582 JvOptionPane.WARNING_MESSAGE);
586 System.err.println("Out of memory loading file " + file + "!!");
589 loadtime += System.currentTimeMillis();
590 // TODO: Estimate percentage of memory used by a newly loaded alignment -
591 // warn if more memory will be needed to work with it
594 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
599 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
601 if (alignFrame != null)
603 AlignmentI al = alignFrame.getViewport().getAlignment();
605 System.out.println("Loaded '" + title + "' in "
606 + (loadtime / 1000.0) + "s, took an additional "
607 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
608 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
612 // report that we didn't load anything probably due to an out of memory
614 System.out.println("Failed to load '" + title + "' in "
615 + (loadtime / 1000.0) + "s, took an additional "
616 + (1.0 * memused / (1024.0 * 1024.0))
617 + " MB (alignment is null)");
620 // remove the visual delay indicator
621 if (Desktop.instance != null)
623 Desktop.instance.stopLoading();
629 * This method creates the file -
630 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
631 * file name and extension
634 * the name of the temp file to be created
636 * the extension of the temp file to be created
639 private static String createNamedJvTempFile(String fileName,
640 String extension) throws IOException
642 String seprator = System.getProperty("file.separator");
643 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
644 + seprator + System.currentTimeMillis();
645 File tempStructFile = new File(
646 jvTempDir + seprator + fileName + "." + extension);
647 tempStructFile.mkdirs();
648 return tempStructFile.toString();