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.
23 import jalview.api.ComplexAlignFile;
24 import jalview.api.FeatureSettingsModelI;
25 import jalview.api.FeaturesDisplayedI;
26 import jalview.api.FeaturesSourceI;
27 import jalview.bin.Cache;
28 import jalview.bin.Jalview;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.AlignViewport;
35 import jalview.gui.Desktop;
36 import jalview.gui.JvOptionPane;
37 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
38 import jalview.project.Jalview2XML;
39 import jalview.schemes.ColourSchemeI;
40 import jalview.util.MessageManager;
41 import jalview.util.Platform;
42 import jalview.ws.utils.UrlDownloadClient;
44 import java.awt.Dimension;
45 import java.io.BufferedReader;
46 import java.io.ByteArrayInputStream;
48 import java.io.FileNotFoundException;
49 import java.io.FileReader;
50 import java.io.IOException;
51 import java.io.InputStreamReader;
52 import java.util.ArrayList;
53 import java.util.List;
55 import javax.swing.SwingUtilities;
57 public class FileLoader implements Runnable
59 private static final String DEFAULT_FILE_FORMAT_PROPERTY = "DEFAULT_FILE_FORMAT";
61 private static final String RECENT_URL_PROPERTY = "RECENT_URL";
63 private static final String RECENT_FILE_PROPERTY = "RECENT_FILE";
65 private static final String TAB = "\t";
68 * maximum number of items in file/url history lists;
69 * pseudo-constant (not final) so amendable by Groovy if wanted
71 private static int MAX_HISTORY = 11;
75 DataSourceType protocol;
79 AlignmentFileReaderI source; // alternative specification of where data
82 AlignViewport viewport;
84 AlignFrame alignFrame;
90 boolean raiseGUI = true;
92 private File selectedFile;
95 * default constructor always raised errors in GUI dialog boxes
103 * construct a Fileloader that may raise errors non-interactively
106 * true if errors are to be raised as GUI dialog boxes
108 public FileLoader(boolean raiseGUI)
110 this.raiseGUI = raiseGUI;
114 * It is critical that all these fields are set, as this instance is reused.
119 * @param dataSourceType
122 private void setFileFields(AlignmentFileReaderI source, File file,
123 String inFile, DataSourceType dataSourceType, FileFormatI format)
125 this.source = source;
127 this.selectedFile = file;
128 this.protocol = dataSourceType;
129 this.format = format;
134 * Uppercase LoadFile is deprecated because it does not pass byte[] data to
143 public void LoadFile(AlignViewport viewport, String file,
144 DataSourceType protocol, FileFormatI format)
146 if (viewport != null)
148 this.viewport = viewport;
150 loadFile(file, protocol, format);
153 public void LoadFile(AlignViewport viewport, File file,
154 DataSourceType protocol, FileFormatI format)
156 loadFile(viewport, file, protocol, format);
160 * Uppercase LoadFile is deprecated because it does not pass byte[] data to
168 public void LoadFile(String file, DataSourceType protocol,
171 loadFile(file, protocol, format);
175 * necessary to use Object here in order to pass the file data
179 * File preferably to String
183 public void loadFile(AlignViewport viewport, File file,
184 DataSourceType protocol, FileFormatI format)
186 if (viewport != null)
188 this.viewport = viewport;
190 this.selectedFile = file;
191 loadFile(selectedFile.getPath(), protocol, format);
194 private void loadFile(String file, DataSourceType protocol,
198 this.protocol = protocol;
199 this.format = format;
201 final Thread loader = new Thread(this);
203 SwingUtilities.invokeLater(new Runnable()
214 * Load alignment from (file, protocol) and wait till loaded
218 * @return alignFrame constructed from file contents
221 public AlignFrame LoadFileWaitTillLoaded(String file,
222 DataSourceType sourceType)
224 return LoadFileWaitTillLoaded(file, sourceType, null);
228 * Load alignment from (file, protocol) of type format and wait till loaded
233 * @return alignFrame constructed from file contents
236 public AlignFrame LoadFileWaitTillLoaded(String file,
237 DataSourceType sourceType, FileFormatI format)
239 setFileFields(null, null, file, sourceType, format);
240 return _loadFileWaitTillLoaded();
244 * Load alignment from (file, protocol) of type format and wait till loaded
249 * @return alignFrame constructed from file contents
250 * @throws NullPointerException
251 * if {@code file} is null
253 public AlignFrame loadFileWaitTillLoaded(File fileObject,
254 DataSourceType sourceType, FileFormatI format)
256 setFileFields(null, fileObject, fileObject.getPath(), sourceType, format);
257 return _loadFileWaitTillLoaded();
261 * Runs the 'run' method (in this thread), then returns the alignFrame that
262 * (hopefully) has been constructed
266 private AlignFrame _loadFileWaitTillLoaded()
273 * Updates the Jalview properties file to add the last file or URL read to the
274 * tab-separated list in property RECENT_FILE or RECENT_URL respectively. The
275 * property is created if it does not already exist. The new entry is added as
276 * the first item (without duplication). If the list exceeds some maximum
277 * length (currently 10 entries), the oldest (last) entry is dropped.
279 * Files read from the temporary file directory are not added to the property.
281 * Property DEFAULT_FILE_FORMAT (e.g. "Fasta" etc) is also set if currently
284 public void updateRecentlyOpened()
286 List<String> recent = new ArrayList<>();
287 if (protocol == DataSourceType.PASTE)
289 // do nothing if the file was pasted in as text... there is no filename to
293 // BH logic change here just includes ignoring file==null
295 || file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
297 // ignore files loaded from the system's temporary directory
300 String type = protocol == DataSourceType.FILE ? RECENT_FILE_PROPERTY
301 : RECENT_URL_PROPERTY;
303 String historyItems = Cache.getProperty(type);
306 if (historyItems != null)
308 String[] tokens = historyItems.split("\\t");
310 for (String token : tokens)
312 recent.add(token.trim());
316 if (recent.contains(file))
321 StringBuilder newHistory = new StringBuilder(file);
322 for (int i = 0; i < recent.size() && i < MAX_HISTORY - 1; i++)
324 newHistory.append(TAB);
325 newHistory.append(recent.get(i));
328 Cache.setProperty(type, newHistory.toString());
330 if (protocol == DataSourceType.FILE)
332 Cache.setProperty(DEFAULT_FILE_FORMAT_PROPERTY, format.getName());
339 String title = protocol == DataSourceType.PASTE
340 ? "Copied From Clipboard"
342 Runtime rt = Runtime.getRuntime();
345 if (Desktop.getInstance() != null)
347 Desktop.getInstance().startLoading(file);
351 // just in case the caller didn't identify the file for us
354 format = new IdentifyFile().identify(source, false);
355 // identify stream and rewind rather than close
357 else if (selectedFile != null) {
358 format = new IdentifyFile().identify(selectedFile, protocol);
362 format = new IdentifyFile().identify(file, protocol);
369 Desktop.getInstance().stopLoading();
370 System.err.println("The input file \"" + file
371 + "\" has null or unidentifiable data content!");
372 if (!Jalview.isHeadlessMode())
374 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
375 MessageManager.getString("label.couldnt_read_data")
376 + " in " + file + "\n"
377 + AppletFormatAdapter.getSupportedFormats(),
378 MessageManager.getString("label.couldnt_read_data"),
379 JvOptionPane.WARNING_MESSAGE);
383 // TODO: cache any stream datasources as a temporary file (eg. PDBs
384 // retrieved via URL)
385 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
388 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
393 loadtime = -System.currentTimeMillis();
394 AlignmentI al = null;
396 if (FileFormat.Jalview.equals(format))
400 // Tell the user (developer?) that this is going to cause a problem
402 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
403 // We read the data anyway - it might make sense.
405 // BH 2018 switch to File object here instead of filename
406 Platform.timeCheck(null, Platform.TIME_MARK);
407 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
408 Platform.timeCheck("JVP loaded", Platform.TIME_MARK);
413 String error = AppletFormatAdapter.getSupportedFormats();
418 // read from the provided source
419 al = new FormatAdapter().readFromFile(source, format);
424 // open a new source and read from it
425 FormatAdapter fa = new FormatAdapter();
426 boolean downloadStructureFile = format.isStructureFile()
427 && protocol.equals(DataSourceType.URL);
428 if (downloadStructureFile)
430 String structExt = format.getExtensions().split(",")[0];
431 int pt = file.lastIndexOf(file.indexOf('/') >= 0 ? "/"
432 : System.getProperty("file.separator"));
433 String urlLeafName = file.substring(pt,
434 file.lastIndexOf("."));
435 String tempStructureFileStr = createNamedJvTempFile(
436 urlLeafName, structExt);
438 // BH - switching to File object here so as to hold on to the
439 // bytes array directly
440 File tempFile = new File(tempStructureFileStr);
441 UrlDownloadClient.download(file, tempFile);
443 al = fa.readFile(tempFile, DataSourceType.FILE,
445 source = fa.getAlignFile();
449 if (selectedFile == null) {
450 al = fa.readFile(file, protocol, format);
453 al = fa.readFile(selectedFile, protocol, format);
455 source = fa.getAlignFile(); // keep reference for later if
460 } catch (java.io.IOException ex)
462 error = ex.getMessage();
465 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
467 // construct and register dataset sequences
468 for (SequenceI sq : al.getSequences())
470 while (sq.getDatasetSequence() != null)
472 sq = sq.getDatasetSequence();
474 if (sq.getAllPDBEntries() != null)
476 for (PDBEntry pdbe : sq.getAllPDBEntries())
478 // register PDB entries with desktop's structure selection
480 Desktop.getStructureSelectionManager()
481 .registerPDBEntry(pdbe);
486 FeatureSettingsModelI proxyColourScheme = source
487 .getFeatureColourScheme();
488 if (viewport != null)
490 if (proxyColourScheme != null)
492 viewport.applyFeaturesStyle(proxyColourScheme);
494 // append to existing alignment
495 viewport.addAlignment(al, title);
499 // otherwise construct the alignFrame
501 if (source instanceof ComplexAlignFile)
503 HiddenColumns colSel = ((ComplexAlignFile) source)
505 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
506 .getHiddenSequences();
507 String colourSchemeName = ((ComplexAlignFile) source)
508 .getGlobalColourScheme();
509 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
510 .getDisplayedFeatures();
511 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
512 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
513 alignFrame.getViewport().setFeaturesDisplayed(fd);
514 alignFrame.getViewport().setShowSequenceFeatures(
515 ((ComplexAlignFile) source).isShowSeqFeatures());
516 ColourSchemeI cs = ColourSchemeMapper
517 .getJalviewColourScheme(colourSchemeName, al);
520 alignFrame.changeColour(cs);
525 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
526 AlignFrame.DEFAULT_HEIGHT);
527 if (source instanceof FeaturesSourceI)
529 alignFrame.getViewport().setShowSequenceFeatures(true);
532 // add metadata and update ui
533 if (!(protocol == DataSourceType.PASTE))
535 alignFrame.setFileName(file, format);
536 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
538 if (proxyColourScheme != null)
540 alignFrame.getViewport()
541 .applyFeaturesStyle(proxyColourScheme);
543 alignFrame.setStatus(MessageManager.formatMessage(
544 "label.successfully_loaded_file", new String[]
549 // add the window to the GUI
550 // note - this actually should happen regardless of raiseGUI
551 // status in Jalview 3
552 // TODO: define 'virtual desktop' for benefit of headless scripts
553 // that perform queries to find the 'current working alignment'
556 Dimension dim = Platform.getDimIfEmbedded(alignFrame,
557 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
558 alignFrame.setSize(dim);
559 Desktop.addInternalFrame(alignFrame, title, dim.width,
565 alignFrame.setMaximum(jalview.bin.Cache
566 .getDefault("SHOW_FULLSCREEN", false));
567 } catch (java.beans.PropertyVetoException ex)
574 if (Desktop.getInstance() != null)
576 Desktop.getInstance().stopLoading();
579 final String errorMessage = MessageManager.getString(
580 "label.couldnt_load_file") + " " + title + "\n" + error;
581 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
583 if (raiseGUI && Desktop.getDesktopPane() != null)
585 javax.swing.SwingUtilities.invokeLater(new Runnable()
590 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
593 .getString("label.error_loading_file"),
594 JvOptionPane.WARNING_MESSAGE);
600 System.err.println(errorMessage);
605 updateRecentlyOpened();
607 } catch (Exception er)
609 System.err.println("Exception whilst opening file '" + file);
610 er.printStackTrace();
613 javax.swing.SwingUtilities.invokeLater(new Runnable()
618 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
619 MessageManager.formatMessage(
620 "label.problems_opening_file", new String[]
622 MessageManager.getString("label.file_open_error"),
623 JvOptionPane.WARNING_MESSAGE);
628 } catch (OutOfMemoryError er)
631 er.printStackTrace();
635 javax.swing.SwingUtilities.invokeLater(new Runnable()
640 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
641 MessageManager.formatMessage(
642 "warn.out_of_memory_loading_file", new String[]
644 MessageManager.getString("label.out_of_memory"),
645 JvOptionPane.WARNING_MESSAGE);
649 System.err.println("Out of memory loading file " + file + "!!");
652 loadtime += System.currentTimeMillis();
653 // TODO: Estimate percentage of memory used by a newly loaded alignment -
654 // warn if more memory will be needed to work with it
657 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
662 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
664 if (alignFrame != null)
666 AlignmentI al = alignFrame.getViewport().getAlignment();
668 System.out.println("Loaded '" + title + "' in "
669 + (loadtime / 1000.0) + "s, took an additional "
670 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
671 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
675 // report that we didn't load anything probably due to an out of memory
677 System.out.println("Failed to load '" + title + "' in "
678 + (loadtime / 1000.0) + "s, took an additional "
679 + (1.0 * memused / (1024.0 * 1024.0))
680 + " MB (alignment is null)");
683 // remove the visual delay indicator
684 if (Desktop.getInstance() != null)
686 Desktop.getInstance().stopLoading();
692 * This method creates the file -
693 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
694 * file name and extension
697 * the name of the temp file to be created
699 * the extension of the temp file to be created
702 private static String createNamedJvTempFile(String fileName,
703 String extension) throws IOException
705 String seprator = System.getProperty("file.separator");
706 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
707 + seprator + System.currentTimeMillis();
708 File tempStructFile = new File(
709 jvTempDir + seprator + fileName + "." + extension);
710 tempStructFile.mkdirs();
711 return tempStructFile.toString();
716 * @param file a File, or a String which is a name of a file
718 * @throws FileNotFoundException
720 public static BufferedReader getBufferedReader(Object file) throws FileNotFoundException {
721 if (file instanceof String)
723 return new BufferedReader(new FileReader((String) file));
725 byte[] bytes = Platform.getFileBytes((File) file);
728 return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
730 return new BufferedReader(new FileReader((File) file));