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();
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)
292 format = new IdentifyFile().identify(selectedFile, protocol);
296 format = new IdentifyFile().identify(file, protocol);
303 Desktop.instance.stopLoading();
304 System.err.println("The input file \"" + file
305 + "\" has null or unidentifiable data content!");
306 if (!Jalview.isHeadlessMode())
308 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
309 MessageManager.getString("label.couldnt_read_data")
310 + " in " + file + "\n"
311 + AppletFormatAdapter.getSupportedFormats(),
312 MessageManager.getString("label.couldnt_read_data"),
313 JvOptionPane.WARNING_MESSAGE);
317 // TODO: cache any stream datasources as a temporary file (eg. PDBs
318 // retrieved via URL)
319 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
322 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
327 loadtime = -System.currentTimeMillis();
328 AlignmentI al = null;
330 if (FileFormat.Jalview.equals(format))
334 // Tell the user (developer?) that this is going to cause a problem
336 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
337 // We read the data anyway - it might make sense.
339 // BH 2018 switch to File object here instead of filename
340 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
341 selectedFile == null ? file : selectedFile);
345 String error = AppletFormatAdapter.getSupportedFormats();
350 // read from the provided source
351 al = new FormatAdapter().readFromFile(source, format);
356 // open a new source and read from it
357 FormatAdapter fa = new FormatAdapter();
358 boolean downloadStructureFile = format.isStructureFile()
359 && protocol.equals(DataSourceType.URL);
360 if (downloadStructureFile)
362 String structExt = format.getExtensions().split(",")[0];
363 String urlLeafName = file.substring(
365 System.getProperty("file.separator")),
366 file.lastIndexOf("."));
367 String tempStructureFileStr = createNamedJvTempFile(
368 urlLeafName, structExt);
370 // BH - switching to File object here so as to hold
371 // ._bytes array directly
372 File tempFile = new File(tempStructureFileStr);
373 UrlDownloadClient.download(file, tempFile);
375 al = fa.readFile(tempFile, DataSourceType.FILE, format);
376 source = fa.getAlignFile();
380 if (selectedFile == null)
382 al = fa.readFile(null, file, protocol, format);
387 al = fa.readFile(selectedFile, null, protocol, format);
389 source = fa.getAlignFile(); // keep reference for later if
394 } catch (java.io.IOException ex)
396 error = ex.getMessage();
399 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
401 // construct and register dataset sequences
402 for (SequenceI sq : al.getSequences())
404 while (sq.getDatasetSequence() != null)
406 sq = sq.getDatasetSequence();
408 if (sq.getAllPDBEntries() != null)
410 for (PDBEntry pdbe : sq.getAllPDBEntries())
412 // register PDB entries with desktop's structure selection
414 StructureSelectionManager
415 .getStructureSelectionManager(Desktop.instance)
416 .registerPDBEntry(pdbe);
421 FeatureSettingsModelI proxyColourScheme = source
422 .getFeatureColourScheme();
423 if (viewport != null)
425 // append to existing alignment
426 viewport.addAlignment(al, title);
427 viewport.applyFeaturesStyle(proxyColourScheme);
431 // otherwise construct the alignFrame
433 if (source instanceof ComplexAlignFile)
435 HiddenColumns colSel = ((ComplexAlignFile) source)
437 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
438 .getHiddenSequences();
439 String colourSchemeName = ((ComplexAlignFile) source)
440 .getGlobalColourScheme();
441 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
442 .getDisplayedFeatures();
443 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
444 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
445 alignFrame.getViewport().setFeaturesDisplayed(fd);
446 alignFrame.getViewport().setShowSequenceFeatures(
447 ((ComplexAlignFile) source).isShowSeqFeatures());
448 ColourSchemeI cs = ColourSchemeMapper
449 .getJalviewColourScheme(colourSchemeName, al);
452 alignFrame.changeColour(cs);
457 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
458 AlignFrame.DEFAULT_HEIGHT);
459 if (source instanceof FeaturesSourceI)
461 alignFrame.getViewport().setShowSequenceFeatures(true);
464 // add metadata and update ui
465 if (!(protocol == DataSourceType.PASTE))
467 alignFrame.setFileName(file, format);
468 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
470 if (proxyColourScheme != null)
472 alignFrame.getViewport()
473 .applyFeaturesStyle(proxyColourScheme);
475 alignFrame.setStatus(MessageManager.formatMessage(
476 "label.successfully_loaded_file", new String[]
481 // add the window to the GUI
482 // note - this actually should happen regardless of raiseGUI
483 // status in Jalview 3
484 // TODO: define 'virtual desktop' for benefit of headless scripts
485 // that perform queries to find the 'current working alignment'
486 Desktop.addInternalFrame(alignFrame, title,
487 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
492 alignFrame.setMaximum(
493 Cache.getDefault("SHOW_FULLSCREEN", false));
494 } catch (java.beans.PropertyVetoException ex)
501 if (Desktop.instance != null)
503 Desktop.instance.stopLoading();
506 final String errorMessage = MessageManager.getString(
507 "label.couldnt_load_file") + " " + title + "\n" + error;
508 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
510 if (raiseGUI && Desktop.desktop != null)
512 javax.swing.SwingUtilities.invokeLater(new Runnable()
517 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
520 .getString("label.error_loading_file"),
521 JvOptionPane.WARNING_MESSAGE);
527 System.err.println(errorMessage);
532 updateRecentlyOpened();
534 } catch (Exception er)
536 System.err.println("Exception whilst opening file '" + file);
537 er.printStackTrace();
540 javax.swing.SwingUtilities.invokeLater(new Runnable()
545 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
546 MessageManager.formatMessage(
547 "label.problems_opening_file", new String[]
549 MessageManager.getString("label.file_open_error"),
550 JvOptionPane.WARNING_MESSAGE);
555 } catch (OutOfMemoryError er)
558 er.printStackTrace();
562 javax.swing.SwingUtilities.invokeLater(new Runnable()
567 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
568 MessageManager.formatMessage(
569 "warn.out_of_memory_loading_file", new String[]
571 MessageManager.getString("label.out_of_memory"),
572 JvOptionPane.WARNING_MESSAGE);
576 System.err.println("Out of memory loading file " + file + "!!");
579 loadtime += System.currentTimeMillis();
580 // TODO: Estimate percentage of memory used by a newly loaded alignment -
581 // warn if more memory will be needed to work with it
584 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
589 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
591 if (alignFrame != null)
593 AlignmentI al = alignFrame.getViewport().getAlignment();
595 System.out.println("Loaded '" + title + "' in "
596 + (loadtime / 1000.0) + "s, took an additional "
597 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
598 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
602 // report that we didn't load anything probably due to an out of memory
604 System.out.println("Failed to load '" + title + "' in "
605 + (loadtime / 1000.0) + "s, took an additional "
606 + (1.0 * memused / (1024.0 * 1024.0))
607 + " MB (alignment is null)");
610 // remove the visual delay indicator
611 if (Desktop.instance != null)
613 Desktop.instance.stopLoading();
619 * This method creates the file -
620 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
621 * file name and extension
624 * the name of the temp file to be created
626 * the extension of the temp file to be created
629 private static String createNamedJvTempFile(String fileName,
630 String extension) throws IOException
632 String seprator = System.getProperty("file.separator");
633 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
634 + seprator + System.currentTimeMillis();
635 File tempStructFile = new File(
636 jvTempDir + seprator + fileName + "." + extension);
637 tempStructFile.mkdirs();
638 return tempStructFile.toString();