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)
101 this.selectedFile = (File) file;
102 file = selectedFile.getPath();
104 LoadFile(file.toString(), protocol, format);
107 public void LoadFile(String file, DataSourceType protocol,
111 this.protocol = protocol;
112 this.format = format;
114 final Thread loader = new Thread(this);
116 SwingUtilities.invokeLater(new Runnable()
127 * Load a (file, protocol) source of unknown type
132 public void LoadFile(String file, DataSourceType protocol)
134 LoadFile(file, protocol, null);
138 * Load alignment from (file, protocol) and wait till loaded
142 * @return alignFrame constructed from file contents
144 public AlignFrame LoadFileWaitTillLoaded(String file,
145 DataSourceType sourceType)
147 return LoadFileWaitTillLoaded(file, sourceType, null);
151 * Load alignment from (file, protocol) of type format and wait till loaded
156 * @return alignFrame constructed from file contents
158 public AlignFrame LoadFileWaitTillLoaded(String file,
159 DataSourceType sourceType, FileFormatI format)
162 this.protocol = sourceType;
163 this.format = format;
164 return _LoadFileWaitTillLoaded();
168 * Load alignment from (file, protocol) of type format and wait till loaded
173 * @return alignFrame constructed from file contents
175 public AlignFrame LoadFileWaitTillLoaded(File file,
176 DataSourceType sourceType, FileFormatI format)
178 this.selectedFile = file;
179 this.file = file.getPath();
180 this.protocol = sourceType;
181 this.format = format;
182 return _LoadFileWaitTillLoaded();
186 * Load alignment from FileParse source of type format and wait till loaded
190 * @return alignFrame constructed from file contents
192 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
195 this.source = source;
197 file = source.getInFile();
198 protocol = source.getDataSourceType();
199 this.format = format;
200 return _LoadFileWaitTillLoaded();
204 * runs the 'run' method (in this thread), then return the alignFrame that's
205 * (hopefully) been read
209 protected AlignFrame _LoadFileWaitTillLoaded()
216 public void updateRecentlyOpened()
218 Vector<String> recent = new Vector<>();
219 if (protocol == DataSourceType.PASTE)
221 // do nothing if the file was pasted in as text... there is no filename to
226 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
228 // ignore files loaded from the system's temporary directory
231 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
234 String historyItems = Cache.getProperty(type);
238 if (historyItems != null)
240 st = new StringTokenizer(historyItems, "\t");
242 while (st.hasMoreTokens())
244 recent.addElement(st.nextToken().trim());
248 if (recent.contains(file))
253 StringBuffer newHistory = new StringBuffer(file);
254 for (int i = 0; i < recent.size() && i < 10; i++)
256 newHistory.append("\t");
257 newHistory.append(recent.elementAt(i));
260 Cache.setProperty(type, newHistory.toString());
262 if (protocol == DataSourceType.FILE)
264 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
271 String title = protocol == DataSourceType.PASTE
272 ? "Copied From Clipboard"
274 Runtime rt = Runtime.getRuntime();
277 if (Desktop.instance != null)
279 Desktop.instance.startLoading(file);
283 // just in case the caller didn't identify the file for us
286 format = new IdentifyFile().identify(source, false);
287 // identify stream and rewind rather than close
289 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(
340 selectedFile == null ? file : selectedFile);
344 String error = AppletFormatAdapter.getSupportedFormats();
349 // read from the provided source
350 al = new FormatAdapter().readFromFile(source, format);
355 // open a new source and read from it
356 FormatAdapter fa = new FormatAdapter();
357 boolean downloadStructureFile = format.isStructureFile()
358 && protocol.equals(DataSourceType.URL);
359 if (downloadStructureFile)
361 String structExt = format.getExtensions().split(",")[0];
362 String urlLeafName = file.substring(
364 System.getProperty("file.separator")),
365 file.lastIndexOf("."));
366 String tempStructureFileStr = createNamedJvTempFile(
367 urlLeafName, structExt);
369 // BH - switching to File object here so as to hold
370 // ._bytes array directly
371 File tempFile = new File(tempStructureFileStr);
372 UrlDownloadClient.download(file, tempFile);
374 al = fa.readFile(tempFile, DataSourceType.FILE, format);
375 source = fa.getAlignFile();
379 if (selectedFile == null)
381 al = fa.readFile(file, protocol, format);
386 al = fa.readFile(selectedFile, protocol, format);
388 source = fa.getAlignFile(); // keep reference for later if
393 } catch (java.io.IOException ex)
395 error = ex.getMessage();
398 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
400 // construct and register dataset sequences
401 for (SequenceI sq : al.getSequences())
403 while (sq.getDatasetSequence() != null)
405 sq = sq.getDatasetSequence();
407 if (sq.getAllPDBEntries() != null)
409 for (PDBEntry pdbe : sq.getAllPDBEntries())
411 // register PDB entries with desktop's structure selection
413 StructureSelectionManager
414 .getStructureSelectionManager(Desktop.instance)
415 .registerPDBEntry(pdbe);
420 FeatureSettingsModelI proxyColourScheme = source
421 .getFeatureColourScheme();
422 if (viewport != null)
424 // append to existing alignment
425 viewport.addAlignment(al, title);
426 viewport.applyFeaturesStyle(proxyColourScheme);
430 // otherwise construct the alignFrame
432 if (source instanceof ComplexAlignFile)
434 HiddenColumns colSel = ((ComplexAlignFile) source)
436 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
437 .getHiddenSequences();
438 String colourSchemeName = ((ComplexAlignFile) source)
439 .getGlobalColourScheme();
440 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
441 .getDisplayedFeatures();
442 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
443 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
444 alignFrame.getViewport().setFeaturesDisplayed(fd);
445 alignFrame.getViewport().setShowSequenceFeatures(
446 ((ComplexAlignFile) source).isShowSeqFeatures());
447 ColourSchemeI cs = ColourSchemeMapper
448 .getJalviewColourScheme(colourSchemeName, al);
451 alignFrame.changeColour(cs);
456 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
457 AlignFrame.DEFAULT_HEIGHT);
458 if (source instanceof FeaturesSourceI)
460 alignFrame.getViewport().setShowSequenceFeatures(true);
463 // add metadata and update ui
464 if (!(protocol == DataSourceType.PASTE))
466 alignFrame.setFileName(file, format);
467 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
469 if (proxyColourScheme != null)
471 alignFrame.getViewport()
472 .applyFeaturesStyle(proxyColourScheme);
474 alignFrame.setStatus(MessageManager.formatMessage(
475 "label.successfully_loaded_file", new String[]
480 // add the window to the GUI
481 // note - this actually should happen regardless of raiseGUI
482 // status in Jalview 3
483 // TODO: define 'virtual desktop' for benefit of headless scripts
484 // that perform queries to find the 'current working alignment'
485 Desktop.addInternalFrame(alignFrame, title,
486 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
491 alignFrame.setMaximum(
492 Cache.getDefault("SHOW_FULLSCREEN", false));
493 } catch (java.beans.PropertyVetoException ex)
500 if (Desktop.instance != null)
502 Desktop.instance.stopLoading();
505 final String errorMessage = MessageManager.getString(
506 "label.couldnt_load_file") + " " + title + "\n" + error;
507 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
509 if (raiseGUI && Desktop.desktop != null)
511 javax.swing.SwingUtilities.invokeLater(new Runnable()
516 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
519 .getString("label.error_loading_file"),
520 JvOptionPane.WARNING_MESSAGE);
526 System.err.println(errorMessage);
531 updateRecentlyOpened();
533 } catch (Exception er)
535 System.err.println("Exception whilst opening file '" + file);
536 er.printStackTrace();
539 javax.swing.SwingUtilities.invokeLater(new Runnable()
544 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
545 MessageManager.formatMessage(
546 "label.problems_opening_file", new String[]
548 MessageManager.getString("label.file_open_error"),
549 JvOptionPane.WARNING_MESSAGE);
554 } catch (OutOfMemoryError er)
557 er.printStackTrace();
561 javax.swing.SwingUtilities.invokeLater(new Runnable()
566 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
567 MessageManager.formatMessage(
568 "warn.out_of_memory_loading_file", new String[]
570 MessageManager.getString("label.out_of_memory"),
571 JvOptionPane.WARNING_MESSAGE);
575 System.err.println("Out of memory loading file " + file + "!!");
578 loadtime += System.currentTimeMillis();
579 // TODO: Estimate percentage of memory used by a newly loaded alignment -
580 // warn if more memory will be needed to work with it
583 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
588 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
590 if (alignFrame != null)
592 AlignmentI al = alignFrame.getViewport().getAlignment();
594 System.out.println("Loaded '" + title + "' in "
595 + (loadtime / 1000.0) + "s, took an additional "
596 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
597 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
601 // report that we didn't load anything probably due to an out of memory
603 System.out.println("Failed to load '" + title + "' in "
604 + (loadtime / 1000.0) + "s, took an additional "
605 + (1.0 * memused / (1024.0 * 1024.0))
606 + " MB (alignment is null)");
609 // remove the visual delay indicator
610 if (Desktop.instance != null)
612 Desktop.instance.stopLoading();
618 * This method creates the file -
619 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
620 * file name and extension
623 * the name of the temp file to be created
625 * the extension of the temp file to be created
628 private static String createNamedJvTempFile(String fileName,
629 String extension) throws IOException
631 String seprator = System.getProperty("file.separator");
632 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
633 + seprator + System.currentTimeMillis();
634 File tempStructFile = new File(
635 jvTempDir + seprator + fileName + "." + extension);
636 tempStructFile.mkdirs();
637 return tempStructFile.toString();