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, "LoadFileThread");
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()
215 public void updateRecentlyOpened()
217 Vector<String> recent = new Vector<>();
218 if (protocol == DataSourceType.PASTE)
220 // do nothing if the file was pasted in as text... there is no filename to
225 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
227 // ignore files loaded from the system's temporary directory
230 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
233 String historyItems = Cache.getProperty(type);
237 if (historyItems != null)
239 st = new StringTokenizer(historyItems, "\t");
241 while (st.hasMoreTokens())
243 recent.addElement(st.nextToken().trim());
247 if (recent.contains(file))
252 StringBuffer newHistory = new StringBuffer(file);
253 for (int i = 0; i < recent.size() && i < 10; i++)
255 newHistory.append("\t");
256 newHistory.append(recent.elementAt(i));
259 Cache.setProperty(type, newHistory.toString());
261 if (protocol == DataSourceType.FILE)
263 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
270 String title = protocol == DataSourceType.PASTE
271 ? "Copied From Clipboard"
273 Runtime rt = Runtime.getRuntime();
276 if (Desktop.instance != null)
278 Desktop.instance.startLoading(file);
282 // just in case the caller didn't identify the file for us
285 format = new IdentifyFile().identify(source, false);
286 // identify stream and rewind rather than close
288 else if (selectedFile != null)
290 format = new IdentifyFile().identify(selectedFile, protocol);
294 format = new IdentifyFile().identify(file, protocol);
301 Desktop.instance.stopLoading();
302 System.err.println("The input file \"" + file
303 + "\" has null or unidentifiable data content!");
304 if (!Jalview.isHeadlessMode())
306 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
307 MessageManager.getString("label.couldnt_read_data")
308 + " in " + file + "\n"
309 + AppletFormatAdapter.getSupportedFormats(),
310 MessageManager.getString("label.couldnt_read_data"),
311 JvOptionPane.WARNING_MESSAGE);
315 // TODO: cache any stream datasources as a temporary file (eg. PDBs
316 // retrieved via URL)
317 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
320 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
325 loadtime = -System.currentTimeMillis();
326 AlignmentI al = null;
328 if (FileFormat.Jalview.equals(format))
332 // Tell the user (developer?) that this is going to cause a problem
334 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
335 // We read the data anyway - it might make sense.
337 // BH 2018 switch to File object here instead of filename
338 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
339 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, format);
374 source = fa.getAlignFile();
378 if (selectedFile == null)
380 al = fa.readFile(file, protocol, format);
385 al = fa.readFile(selectedFile, protocol, format);
387 source = fa.getAlignFile(); // keep reference for later if
392 } catch (java.io.IOException ex)
394 error = ex.getMessage();
397 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
399 // construct and register dataset sequences
400 for (SequenceI sq : al.getSequences())
402 while (sq.getDatasetSequence() != null)
404 sq = sq.getDatasetSequence();
406 if (sq.getAllPDBEntries() != null)
408 for (PDBEntry pdbe : sq.getAllPDBEntries())
410 // register PDB entries with desktop's structure selection
412 StructureSelectionManager
413 .getStructureSelectionManager(Desktop.instance)
414 .registerPDBEntry(pdbe);
419 FeatureSettingsModelI proxyColourScheme = source
420 .getFeatureColourScheme();
421 if (viewport != null)
423 // append to existing alignment
424 viewport.addAlignment(al, title);
425 viewport.applyFeaturesStyle(proxyColourScheme);
429 // otherwise construct the alignFrame
431 if (source instanceof ComplexAlignFile)
433 HiddenColumns colSel = ((ComplexAlignFile) source)
435 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
436 .getHiddenSequences();
437 String colourSchemeName = ((ComplexAlignFile) source)
438 .getGlobalColourScheme();
439 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
440 .getDisplayedFeatures();
441 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
442 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
443 alignFrame.getViewport().setFeaturesDisplayed(fd);
444 alignFrame.getViewport().setShowSequenceFeatures(
445 ((ComplexAlignFile) source).isShowSeqFeatures());
446 ColourSchemeI cs = ColourSchemeMapper
447 .getJalviewColourScheme(colourSchemeName, al);
450 alignFrame.changeColour(cs);
455 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
456 AlignFrame.DEFAULT_HEIGHT);
457 if (source instanceof FeaturesSourceI)
459 alignFrame.getViewport().setShowSequenceFeatures(true);
462 // add metadata and update ui
463 if (!(protocol == DataSourceType.PASTE))
465 alignFrame.setFileName(file, format);
466 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
468 if (proxyColourScheme != null)
470 alignFrame.getViewport()
471 .applyFeaturesStyle(proxyColourScheme);
473 alignFrame.setStatus(MessageManager.formatMessage(
474 "label.successfully_loaded_file", new String[]
479 // add the window to the GUI
480 // note - this actually should happen regardless of raiseGUI
481 // status in Jalview 3
482 // TODO: define 'virtual desktop' for benefit of headless scripts
483 // that perform queries to find the 'current working alignment'
484 Desktop.addInternalFrame(alignFrame, title,
485 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
490 alignFrame.setMaximum(
491 Cache.getDefault("SHOW_FULLSCREEN", false));
492 } catch (java.beans.PropertyVetoException ex)
499 if (Desktop.instance != null)
501 Desktop.instance.stopLoading();
504 final String errorMessage = MessageManager.getString(
505 "label.couldnt_load_file") + " " + title + "\n" + error;
506 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
508 if (raiseGUI && Desktop.desktop != null)
510 javax.swing.SwingUtilities.invokeLater(new Runnable()
515 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
518 .getString("label.error_loading_file"),
519 JvOptionPane.WARNING_MESSAGE);
525 System.err.println(errorMessage);
530 updateRecentlyOpened();
532 } catch (Exception er)
534 System.err.println("Exception whilst opening file '" + file);
535 er.printStackTrace();
538 javax.swing.SwingUtilities.invokeLater(new Runnable()
543 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
544 MessageManager.formatMessage(
545 "label.problems_opening_file", new String[]
547 MessageManager.getString("label.file_open_error"),
548 JvOptionPane.WARNING_MESSAGE);
553 } catch (OutOfMemoryError er)
556 er.printStackTrace();
560 javax.swing.SwingUtilities.invokeLater(new Runnable()
565 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
566 MessageManager.formatMessage(
567 "warn.out_of_memory_loading_file", new String[]
569 MessageManager.getString("label.out_of_memory"),
570 JvOptionPane.WARNING_MESSAGE);
574 System.err.println("Out of memory loading file " + file + "!!");
577 loadtime += System.currentTimeMillis();
578 // TODO: Estimate percentage of memory used by a newly loaded alignment -
579 // warn if more memory will be needed to work with it
582 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
587 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
589 if (alignFrame != null)
591 AlignmentI al = alignFrame.getViewport().getAlignment();
593 System.out.println("Loaded '" + title + "' in "
594 + (loadtime / 1000.0) + "s, took an additional "
595 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
596 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
600 // report that we didn't load anything probably due to an out of memory
602 System.out.println("Failed to load '" + title + "' in "
603 + (loadtime / 1000.0) + "s, took an additional "
604 + (1.0 * memused / (1024.0 * 1024.0))
605 + " MB (alignment is null)");
608 // remove the visual delay indicator
609 if (Desktop.instance != null)
611 Desktop.instance.stopLoading();
617 * This method creates the file -
618 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
619 * file name and extension
622 * the name of the temp file to be created
624 * the extension of the temp file to be created
627 private static String createNamedJvTempFile(String fileName,
628 String extension) throws IOException
630 String seprator = System.getProperty("file.separator");
631 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
632 + seprator + System.currentTimeMillis();
633 File tempStructFile = new File(
634 jvTempDir + seprator + fileName + "." + extension);
635 tempStructFile.mkdirs();
636 return tempStructFile.toString();