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 import java.util.ArrayList;
52 import java.util.List;
54 public class FileLoader implements Runnable
56 private static final String TAB = "\t";
60 DataSourceType protocol;
64 AlignmentFileReaderI source = null; // alternative specification of where data
69 AlignViewport viewport;
71 AlignFrame alignFrame;
77 boolean raiseGUI = true;
79 private File selectedFile;
82 * default constructor always raised errors in GUI dialog boxes
90 * construct a Fileloader that may raise errors non-interactively
93 * true if errors are to be raised as GUI dialog boxes
95 public FileLoader(boolean raiseGUI)
97 this.raiseGUI = raiseGUI;
100 public void LoadFile(AlignViewport viewport, Object file,
101 DataSourceType protocol, FileFormatI format)
103 this.viewport = viewport;
104 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)
166 this.protocol = sourceType;
167 this.format = format;
168 return _LoadFileWaitTillLoaded();
172 * Load alignment from (file, protocol) of type format and wait till loaded
177 * @return alignFrame constructed from file contents
179 public AlignFrame LoadFileWaitTillLoaded(File file,
180 DataSourceType sourceType, FileFormatI format)
182 this.selectedFile = file;
183 this.file = file.getPath();
184 this.protocol = sourceType;
185 this.format = format;
186 return _LoadFileWaitTillLoaded();
190 * Load alignment from FileParse source of type format and wait till loaded
194 * @return alignFrame constructed from file contents
196 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
199 this.source = source;
201 file = source.getInFile();
202 protocol = source.getDataSourceType();
203 this.format = format;
204 return _LoadFileWaitTillLoaded();
208 * runs the 'run' method (in this thread), then return the alignFrame that's
209 * (hopefully) been read
213 protected AlignFrame _LoadFileWaitTillLoaded()
220 public void LoadFileOntoAlignmentWaitTillLoaded(AlignViewport viewport,
221 String file, DataSourceType sourceType, FileFormatI format)
223 Vector<String> recent = new Vector<>();
224 if (protocol == DataSourceType.PASTE)
225 this.viewport = viewport;
227 this.protocol = sourceType;
228 this.format = format;
229 _LoadFileWaitTillLoaded();
234 * Updates (or creates) the tab-separated list of recently opened files held
235 * under the given property name by inserting the filePath at the front of the
236 * list. Duplicates are removed, and the list is limited to 11 entries. The
237 * method returns the updated value of the property.
242 public static String updateRecentlyOpened(String filePath,
243 DataSourceType sourceType)
245 if (sourceType != DataSourceType.FILE
246 && sourceType != DataSourceType.URL)
251 String propertyName = sourceType == DataSourceType.FILE ? "RECENT_FILE"
253 String historyItems = Cache.getProperty(propertyName);
255 && filePath.indexOf(System.getProperty("java.io.tmpdir")) > -1)
257 // ignore files loaded from the system's temporary directory
261 List<String> recent = new ArrayList<>();
263 if (historyItems != null)
265 StringTokenizer st = new StringTokenizer(historyItems, TAB);
267 while (st.hasMoreTokens())
269 String trimmed = st.nextToken().trim();
275 * if file was already in the list, it moves to the top
277 if (recent.contains(filePath))
279 recent.remove(filePath);
282 StringBuilder newHistory = new StringBuilder(filePath);
283 for (int i = 0; i < recent.size() && i < 10; i++)
285 newHistory.append(TAB);
286 newHistory.append(recent.get(i));
289 String newProperty = newHistory.toString();
290 Cache.setProperty(propertyName, newProperty);
298 String title = protocol == DataSourceType.PASTE
299 ? "Copied From Clipboard"
301 Runtime rt = Runtime.getRuntime();
304 if (Desktop.instance != null)
306 Desktop.instance.startLoading(file);
310 // just in case the caller didn't identify the file for us
313 format = new IdentifyFile().identify(source, false);
314 // identify stream and rewind rather than close
316 else if (selectedFile != null) {
317 format = new IdentifyFile().identify(selectedFile, protocol);
321 format = new IdentifyFile().identify(file, protocol);
328 Desktop.instance.stopLoading();
329 System.err.println("The input file \"" + file
330 + "\" has null or unidentifiable data content!");
331 if (!Jalview.isHeadlessMode())
333 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
334 MessageManager.getString("label.couldnt_read_data")
335 + " in " + file + "\n"
336 + AppletFormatAdapter.getSupportedFormats(),
337 MessageManager.getString("label.couldnt_read_data"),
338 JvOptionPane.WARNING_MESSAGE);
342 // TODO: cache any stream datasources as a temporary file (eg. PDBs
343 // retrieved via URL)
344 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
347 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
352 loadtime = -System.currentTimeMillis();
353 AlignmentI al = null;
355 if (FileFormat.Jalview.equals(format))
359 // Tell the user (developer?) that this is going to cause a problem
361 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
362 // We read the data anyway - it might make sense.
364 // BH 2018 switch to File object here instead of filename
365 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
369 String error = AppletFormatAdapter.getSupportedFormats();
374 // read from the provided source
375 al = new FormatAdapter().readFromFile(source, format);
380 // open a new source and read from it
381 FormatAdapter fa = new FormatAdapter();
382 boolean downloadStructureFile = format.isStructureFile()
383 && protocol.equals(DataSourceType.URL);
384 if (downloadStructureFile)
386 String structExt = format.getExtensions().split(",")[0];
387 String urlLeafName = file.substring(
389 System.getProperty("file.separator")),
390 file.lastIndexOf("."));
391 String tempStructureFileStr = createNamedJvTempFile(
392 urlLeafName, structExt);
394 // BH - switching to File object here so as to hold
395 // ._bytes array directly
396 File tempFile = new File(tempStructureFileStr);
397 UrlDownloadClient.download(file, tempFile);
399 al = fa.readFile(tempFile, DataSourceType.FILE,
401 source = fa.getAlignFile();
405 if (selectedFile == null) {
406 al = fa.readFile(file, protocol, format);
409 al = fa.readFile(selectedFile, protocol, format);
411 source = fa.getAlignFile(); // keep reference for later if
416 } catch (java.io.IOException ex)
418 error = ex.getMessage();
421 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
423 // construct and register dataset sequences
424 for (SequenceI sq : al.getSequences())
426 while (sq.getDatasetSequence() != null)
428 sq = sq.getDatasetSequence();
430 if (sq.getAllPDBEntries() != null)
432 for (PDBEntry pdbe : sq.getAllPDBEntries())
434 // register PDB entries with desktop's structure selection
436 StructureSelectionManager
437 .getStructureSelectionManager(Desktop.instance)
438 .registerPDBEntry(pdbe);
443 FeatureSettingsModelI proxyColourScheme = source
444 .getFeatureColourScheme();
445 if (viewport != null)
447 if (proxyColourScheme != null)
449 viewport.applyFeaturesStyle(proxyColourScheme);
451 // append to existing alignment
452 viewport.addAlignment(al, title);
453 if (source instanceof HMMFile)
455 AlignmentI alignment = viewport.getAlignment();
456 SequenceI seq = alignment
457 .getSequenceAt(alignment.getHeight() - 1);
458 if (seq.hasHMMProfile())
461 * fudge: move HMM consensus sequence from last to first
463 alignment.deleteSequence(alignment.getAbsoluteHeight() - 1);
464 alignment.insertSequenceAt(0, seq);
466 viewport.getAlignPanel().adjustAnnotationHeight();
467 viewport.updateSequenceIdColours();
472 // otherwise construct the alignFrame
474 if (source instanceof ComplexAlignFile)
476 HiddenColumns colSel = ((ComplexAlignFile) source)
478 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
479 .getHiddenSequences();
480 String colourSchemeName = ((ComplexAlignFile) source)
481 .getGlobalColourScheme();
482 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
483 .getDisplayedFeatures();
484 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
485 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
486 alignFrame.getViewport().setFeaturesDisplayed(fd);
487 alignFrame.getViewport().setShowSequenceFeatures(
488 ((ComplexAlignFile) source).isShowSeqFeatures());
489 ColourSchemeI cs = ColourSchemeMapper
490 .getJalviewColourScheme(colourSchemeName, al);
493 alignFrame.changeColour(cs);
498 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
499 AlignFrame.DEFAULT_HEIGHT);
500 if (source instanceof FeaturesSourceI)
502 alignFrame.getViewport().setShowSequenceFeatures(true);
505 // add metadata and update ui
506 if (!(protocol == DataSourceType.PASTE))
508 alignFrame.setFileName(file, format);
509 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
511 if (proxyColourScheme != null)
513 alignFrame.getViewport()
514 .applyFeaturesStyle(proxyColourScheme);
516 alignFrame.setStatus(MessageManager.formatMessage(
517 "label.successfully_loaded_file", new String[]
522 // add the window to the GUI
523 // note - this actually should happen regardless of raiseGUI
524 // status in Jalview 3
525 // TODO: define 'virtual desktop' for benefit of headless scripts
526 // that perform queries to find the 'current working alignment'
527 Desktop.addInternalFrame(alignFrame, title,
528 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
533 alignFrame.setMaximum(jalview.bin.Cache
534 .getDefault("SHOW_FULLSCREEN", false));
535 } catch (java.beans.PropertyVetoException ex)
542 if (Desktop.instance != null)
544 Desktop.instance.stopLoading();
547 final String errorMessage = MessageManager.getString(
548 "label.couldnt_load_file") + " " + title + "\n" + error;
549 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
551 if (raiseGUI && Desktop.desktop != null)
553 javax.swing.SwingUtilities.invokeLater(new Runnable()
558 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
561 .getString("label.error_loading_file"),
562 JvOptionPane.WARNING_MESSAGE);
568 System.err.println(errorMessage);
573 updateRecentlyOpened(file, protocol);
575 if (protocol == DataSourceType.FILE && format != null)
577 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
580 } catch (Exception er)
582 System.err.println("Exception whilst opening file '" + file);
583 er.printStackTrace();
586 javax.swing.SwingUtilities.invokeLater(new Runnable()
591 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
592 MessageManager.formatMessage(
593 "label.problems_opening_file", new String[]
595 MessageManager.getString("label.file_open_error"),
596 JvOptionPane.WARNING_MESSAGE);
601 } catch (OutOfMemoryError er)
604 er.printStackTrace();
608 javax.swing.SwingUtilities.invokeLater(new Runnable()
613 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
614 MessageManager.formatMessage(
615 "warn.out_of_memory_loading_file", new String[]
617 MessageManager.getString("label.out_of_memory"),
618 JvOptionPane.WARNING_MESSAGE);
622 System.err.println("Out of memory loading file " + file + "!!");
625 loadtime += System.currentTimeMillis();
626 // TODO: Estimate percentage of memory used by a newly loaded alignment -
627 // warn if more memory will be needed to work with it
630 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
635 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
637 if (alignFrame != null)
639 AlignmentI al = alignFrame.getViewport().getAlignment();
641 System.out.println("Loaded '" + title + "' in "
642 + (loadtime / 1000.0) + "s, took an additional "
643 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
644 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
648 // report that we didn't load anything probably due to an out of memory
650 System.out.println("Failed to load '" + title + "' in "
651 + (loadtime / 1000.0) + "s, took an additional "
652 + (1.0 * memused / (1024.0 * 1024.0))
653 + " MB (alignment is null)");
656 // remove the visual delay indicator
657 if (Desktop.instance != null)
659 Desktop.instance.stopLoading();
665 * This method creates the file -
666 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
667 * file name and extension
670 * the name of the temp file to be created
672 * the extension of the temp file to be created
675 private static String createNamedJvTempFile(String fileName,
676 String extension) throws IOException
678 String seprator = System.getProperty("file.separator");
679 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
680 + seprator + System.currentTimeMillis();
681 File tempStructFile = new File(
682 jvTempDir + seprator + fileName + "." + extension);
683 tempStructFile.mkdirs();
684 return tempStructFile.toString();