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.AlignmentAnnotation;
37 import jalview.datamodel.AlignmentAnnotation.TFType;
38 import jalview.datamodel.AlignmentI;
39 import jalview.datamodel.HiddenColumns;
40 import jalview.datamodel.PDBEntry;
41 import jalview.datamodel.SequenceI;
42 import jalview.gui.AlignFrame;
43 import jalview.gui.AlignViewport;
44 import jalview.gui.Desktop;
45 import jalview.gui.JvOptionPane;
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;
78 private AlignmentAnnotation.TFType temperatureFactorType = null;
81 * default constructor always raised errors in GUI dialog boxes
89 * construct a Fileloader that may raise errors non-interactively
92 * true if errors are to be raised as GUI dialog boxes
94 public FileLoader(boolean raiseGUI)
96 this.raiseGUI = raiseGUI;
99 public void LoadFile(AlignViewport viewport, Object file,
100 DataSourceType protocol, FileFormatI format)
102 this.viewport = viewport;
103 if (file instanceof File)
105 this.selectedFile = (File) file;
106 file = selectedFile.getPath();
108 LoadFile(file.toString(), protocol, format);
111 public void LoadFile(String file, DataSourceType protocol,
115 this.protocol = protocol;
116 this.format = format;
118 final Thread loader = new Thread(this);
120 SwingUtilities.invokeLater(new Runnable()
131 * Load a (file, protocol) source of unknown type
136 public void LoadFile(String file, DataSourceType protocol)
138 LoadFile(file, protocol, null);
142 * Load alignment from (file, protocol) and wait till loaded
146 * @return alignFrame constructed from file contents
148 public AlignFrame LoadFileWaitTillLoaded(String file,
149 DataSourceType sourceType)
151 return LoadFileWaitTillLoaded(file, sourceType, null);
155 * Load alignment from (file, protocol) of type format and wait till loaded
160 * @return alignFrame constructed from file contents
162 public AlignFrame LoadFileWaitTillLoaded(String file,
163 DataSourceType sourceType, FileFormatI format)
165 return LoadFileWaitTillLoaded(file, sourceType, format, null);
169 * Load alignment from (file, protocol) of type format with specified
170 * temperature factor type and wait till loaded
176 * @return alignFrame constructed from file contents
178 public AlignFrame LoadFileWaitTillLoaded(String file,
179 DataSourceType sourceType, FileFormatI format, AlignmentAnnotation.TFType tempfacType)
182 this.protocol = sourceType;
183 this.format = format;
184 this.temperatureFactorType = tempfacType;
185 return _LoadFileWaitTillLoaded();
189 * Load alignment from (file, protocol) of type format and wait till loaded
194 * @return alignFrame constructed from file contents
196 public AlignFrame LoadFileWaitTillLoaded(File file,
197 DataSourceType sourceType, FileFormatI format)
199 this.selectedFile = file;
200 this.file = file.getPath();
201 this.protocol = sourceType;
202 this.format = format;
203 return _LoadFileWaitTillLoaded();
207 * Load alignment from FileParse source of type format and wait till loaded
211 * @return alignFrame constructed from file contents
213 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
216 this.source = source;
218 file = source.getInFile();
219 protocol = source.getDataSourceType();
220 this.format = format;
221 return _LoadFileWaitTillLoaded();
225 * runs the 'run' method (in this thread), then return the alignFrame that's
226 * (hopefully) been read
230 protected AlignFrame _LoadFileWaitTillLoaded()
237 public void updateRecentlyOpened()
239 Vector<String> recent = new Vector<>();
240 if (protocol == DataSourceType.PASTE)
242 // do nothing if the file was pasted in as text... there is no filename to
247 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
249 // ignore files loaded from the system's temporary directory
252 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
255 String historyItems = Cache.getProperty(type);
259 if (historyItems != null)
261 st = new StringTokenizer(historyItems, "\t");
263 while (st.hasMoreTokens())
265 recent.addElement(st.nextToken().trim());
269 if (recent.contains(file))
274 StringBuffer newHistory = new StringBuffer(file);
275 for (int i = 0; i < recent.size() && i < 10; i++)
277 newHistory.append("\t");
278 newHistory.append(recent.elementAt(i));
281 Cache.setProperty(type, newHistory.toString());
283 if (protocol == DataSourceType.FILE)
285 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
292 String title = protocol == DataSourceType.PASTE
293 ? "Copied From Clipboard"
295 Runtime rt = Runtime.getRuntime();
299 if (Desktop.instance != null)
301 Desktop.instance.startLoading(file);
305 // just in case the caller didn't identify the file for us
308 format = new IdentifyFile().identify(source, false);
309 // identify stream and rewind rather than close
311 else if (selectedFile != null)
313 format = new IdentifyFile().identify(selectedFile, protocol);
317 format = new IdentifyFile().identify(file, protocol);
324 Desktop.instance.stopLoading();
325 System.err.println("The input file \"" + file
326 + "\" has null or unidentifiable data content!");
327 if (!Jalview.isHeadlessMode())
329 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
330 MessageManager.getString("label.couldnt_read_data")
331 + " in " + file + "\n"
332 + AppletFormatAdapter.getSupportedFormats(),
333 MessageManager.getString("label.couldnt_read_data"),
334 JvOptionPane.WARNING_MESSAGE);
338 // TODO: cache any stream datasources as a temporary file (eg. PDBs
339 // retrieved via URL)
340 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
343 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
348 loadtime = -System.currentTimeMillis();
349 AlignmentI al = null;
351 if (FileFormat.Jalview.equals(format))
355 // Tell the user (developer?) that this is going to cause a problem
357 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
358 // We read the data anyway - it might make sense.
360 // BH 2018 switch to File object here instead of filename
361 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
362 selectedFile == null ? file : selectedFile);
366 String error = AppletFormatAdapter.getSupportedFormats();
371 // read from the provided source
372 al = new FormatAdapter().readFromFile(source, format);
377 // open a new source and read from it
378 FormatAdapter fa = new FormatAdapter();
379 boolean downloadStructureFile = format.isStructureFile()
380 && protocol.equals(DataSourceType.URL);
381 if (downloadStructureFile)
383 String structExt = format.getExtensions().split(",")[0];
384 String urlLeafName = file.substring(
386 System.getProperty("file.separator")),
387 file.lastIndexOf("."));
388 String tempStructureFileStr = createNamedJvTempFile(
389 urlLeafName, structExt);
391 // BH - switching to File object here so as to hold
392 // ._bytes array directly
393 File tempFile = new File(tempStructureFileStr);
394 UrlDownloadClient.download(file, tempFile);
396 al = fa.readFile(tempFile, DataSourceType.FILE, format);
397 source = fa.getAlignFile();
401 if (selectedFile == null)
403 al = fa.readFile(null, file, protocol, format,
404 temperatureFactorType);
409 al = fa.readFile(selectedFile, null, protocol, format,
410 temperatureFactorType);
412 source = fa.getAlignFile(); // keep reference for later if
417 } catch (java.io.IOException ex)
419 error = ex.getMessage();
422 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
424 // construct and register dataset sequences
425 for (SequenceI sq : al.getSequences())
427 while (sq.getDatasetSequence() != null)
429 sq = sq.getDatasetSequence();
431 if (sq.getAllPDBEntries() != null)
433 for (PDBEntry pdbe : sq.getAllPDBEntries())
435 // register PDB entries with desktop's structure selection
437 StructureSelectionManager
438 .getStructureSelectionManager(Desktop.instance)
439 .registerPDBEntry(pdbe);
444 FeatureSettingsModelI proxyColourScheme = source
445 .getFeatureColourScheme();
446 if (viewport != null)
448 // append to existing alignment
449 viewport.addAlignment(al, title);
450 viewport.applyFeaturesStyle(proxyColourScheme);
454 // otherwise construct the alignFrame
456 if (source instanceof ComplexAlignFile)
458 HiddenColumns colSel = ((ComplexAlignFile) source)
460 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
461 .getHiddenSequences();
462 String colourSchemeName = ((ComplexAlignFile) source)
463 .getGlobalColourScheme();
464 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
465 .getDisplayedFeatures();
466 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
467 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
468 alignFrame.getViewport().setFeaturesDisplayed(fd);
469 alignFrame.getViewport().setShowSequenceFeatures(
470 ((ComplexAlignFile) source).isShowSeqFeatures());
471 ColourSchemeI cs = ColourSchemeMapper
472 .getJalviewColourScheme(colourSchemeName, al);
475 alignFrame.changeColour(cs);
480 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
481 AlignFrame.DEFAULT_HEIGHT);
482 if (source instanceof FeaturesSourceI)
484 alignFrame.getViewport().setShowSequenceFeatures(true);
487 // add metadata and update ui
488 if (!(protocol == DataSourceType.PASTE))
490 alignFrame.setFileName(file, format);
491 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
493 if (proxyColourScheme != null)
495 alignFrame.getViewport()
496 .applyFeaturesStyle(proxyColourScheme);
498 alignFrame.setStatus(MessageManager.formatMessage(
499 "label.successfully_loaded_file", new String[]
504 // add the window to the GUI
505 // note - this actually should happen regardless of raiseGUI
506 // status in Jalview 3
507 // TODO: define 'virtual desktop' for benefit of headless scripts
508 // that perform queries to find the 'current working alignment'
509 Desktop.addInternalFrame(alignFrame, title,
510 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
515 alignFrame.setMaximum(
516 Cache.getDefault("SHOW_FULLSCREEN", false));
517 } catch (java.beans.PropertyVetoException ex)
524 if (Desktop.instance != null)
526 Desktop.instance.stopLoading();
529 final String errorMessage = MessageManager.getString(
530 "label.couldnt_load_file") + " " + title + "\n" + error;
531 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
533 if (raiseGUI && Desktop.desktop != null)
535 javax.swing.SwingUtilities.invokeLater(new Runnable()
540 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
543 .getString("label.error_loading_file"),
544 JvOptionPane.WARNING_MESSAGE);
550 System.err.println(errorMessage);
555 updateRecentlyOpened();
557 } catch (Exception er)
559 System.err.println("Exception whilst opening file '" + file);
560 er.printStackTrace();
563 javax.swing.SwingUtilities.invokeLater(new Runnable()
568 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
569 MessageManager.formatMessage(
570 "label.problems_opening_file", new String[]
572 MessageManager.getString("label.file_open_error"),
573 JvOptionPane.WARNING_MESSAGE);
578 } catch (OutOfMemoryError er)
581 er.printStackTrace();
585 javax.swing.SwingUtilities.invokeLater(new Runnable()
590 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
591 MessageManager.formatMessage(
592 "warn.out_of_memory_loading_file", new String[]
594 MessageManager.getString("label.out_of_memory"),
595 JvOptionPane.WARNING_MESSAGE);
599 System.err.println("Out of memory loading file " + file + "!!");
602 loadtime += System.currentTimeMillis();
603 // TODO: Estimate percentage of memory used by a newly loaded alignment -
604 // warn if more memory will be needed to work with it
607 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
612 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
614 if (alignFrame != null)
616 AlignmentI al = alignFrame.getViewport().getAlignment();
618 System.out.println("Loaded '" + title + "' in "
619 + (loadtime / 1000.0) + "s, took an additional "
620 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
621 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
625 // report that we didn't load anything probably due to an out of memory
627 System.out.println("Failed to load '" + title + "' in "
628 + (loadtime / 1000.0) + "s, took an additional "
629 + (1.0 * memused / (1024.0 * 1024.0))
630 + " MB (alignment is null)");
633 // remove the visual delay indicator
634 if (Desktop.instance != null)
636 Desktop.instance.stopLoading();
642 * This method creates the file -
643 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
644 * file name and extension
647 * the name of the temp file to be created
649 * the extension of the temp file to be created
652 private static String createNamedJvTempFile(String fileName,
653 String extension) throws IOException
655 String seprator = System.getProperty("file.separator");
656 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
657 + seprator + System.currentTimeMillis();
658 File tempStructFile = new File(
659 jvTempDir + seprator + fileName + "." + extension);
660 tempStructFile.mkdirs();
661 return tempStructFile.toString();