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;
73 private File selectedFile;
77 DataSourceType protocol;
81 AlignmentFileReaderI source; // alternative specification of where data
85 * It is critical that all these fields are set, as this instance is reused.
90 * @param dataSourceType
93 private void setFileFields(AlignmentFileReaderI source, File file,
94 String inFile, DataSourceType dataSourceType, FileFormatI format)
98 this.selectedFile = file;
99 this.protocol = dataSourceType;
100 this.format = format;
103 AlignViewport viewport;
105 AlignFrame alignFrame;
111 boolean raiseGUI = true;
114 * default constructor always raised errors in GUI dialog boxes
122 * construct a Fileloader that may raise errors non-interactively
125 * true if errors are to be raised as GUI dialog boxes
127 public FileLoader(boolean raiseGUI)
129 this.raiseGUI = raiseGUI;
132 public void loadFile(AlignViewport viewport, Object file,
133 DataSourceType protocol, FileFormatI format)
135 this.viewport = viewport;
136 if (file instanceof File) {
137 this.selectedFile = (File) file;
138 file = selectedFile.getPath();
140 loadFile(file.toString(), protocol, format);
143 public void loadFile(String file, DataSourceType protocol,
147 this.protocol = protocol;
148 this.format = format;
150 final Thread loader = new Thread(this);
152 SwingUtilities.invokeLater(new Runnable()
163 * Load alignment from (file, protocol) and wait till loaded
167 * @return alignFrame constructed from file contents
169 public AlignFrame LoadFileWaitTillLoaded(String file,
170 DataSourceType sourceType)
172 return loadFileWaitTillLoaded(file, sourceType, null);
176 * Load alignment from (file, protocol) of type format and wait till loaded
181 * @return alignFrame constructed from file contents
183 public AlignFrame loadFileWaitTillLoaded(String file,
184 DataSourceType sourceType, FileFormatI format)
186 setFileFields(null, null, file, sourceType, format);
187 return _loadFileWaitTillLoaded();
191 * Load alignment from (file, protocol) of type format and wait till loaded
196 * @return alignFrame constructed from file contents
197 * @throws NullPointerException
198 * if {@code file} is null
200 public AlignFrame loadFileWaitTillLoaded(File fileObject,
201 DataSourceType sourceType, FileFormatI format)
203 setFileFields(null, fileObject, fileObject.getPath(), sourceType, format);
204 return _loadFileWaitTillLoaded();
208 * Runs the 'run' method (in this thread), then returns the alignFrame that
209 * (hopefully) has been constructed
213 private AlignFrame _loadFileWaitTillLoaded()
220 * Updates the Jalview properties file to add the last file or URL read to the
221 * tab-separated list in property RECENT_FILE or RECENT_URL respectively. The
222 * property is created if it does not already exist. The new entry is added as
223 * the first item (without duplication). If the list exceeds some maximum
224 * length (currently 10 entries), the oldest (last) entry is dropped.
226 * Files read from the temporary file directory are not added to the property.
228 * Property DEFAULT_FILE_FORMAT (e.g. "Fasta" etc) is also set if currently
231 public void updateRecentlyOpened()
233 List<String> recent = new ArrayList<>();
234 if (protocol == DataSourceType.PASTE)
236 // do nothing if the file was pasted in as text... there is no filename to
241 || file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
243 // ignore files loaded from the system's temporary directory
246 String type = protocol == DataSourceType.FILE ? RECENT_FILE_PROPERTY
247 : RECENT_URL_PROPERTY;
249 String historyItems = Cache.getProperty(type);
251 if (historyItems != null)
253 String[] tokens = historyItems.split("\\t");
255 for (String token : tokens)
257 recent.add(token.trim());
261 if (recent.contains(file))
266 StringBuilder newHistory = new StringBuilder(file);
267 for (int i = 0; i < recent.size() && i < MAX_HISTORY - 1; i++)
269 newHistory.append(TAB);
270 newHistory.append(recent.get(i));
273 Cache.setProperty(type, newHistory.toString());
275 if (protocol == DataSourceType.FILE)
277 Cache.setProperty(DEFAULT_FILE_FORMAT_PROPERTY, format.getName());
284 String title = protocol == DataSourceType.PASTE
285 ? "Copied From Clipboard"
287 Runtime rt = Runtime.getRuntime();
290 if (Desktop.getInstance() != null)
292 Desktop.getInstance().startLoading(file);
296 // just in case the caller didn't identify the file for us
299 format = new IdentifyFile().identify(source, false);
300 // identify stream and rewind rather than close
302 else if (selectedFile != null) {
303 format = new IdentifyFile().identify(selectedFile, protocol);
307 format = new IdentifyFile().identify(file, protocol);
314 Desktop.getInstance().stopLoading();
315 System.err.println("The input file \"" + file
316 + "\" has null or unidentifiable data content!");
317 if (!Jalview.isHeadlessMode())
319 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
320 MessageManager.getString("label.couldnt_read_data")
321 + " in " + file + "\n"
322 + AppletFormatAdapter.getSupportedFormats(),
323 MessageManager.getString("label.couldnt_read_data"),
324 JvOptionPane.WARNING_MESSAGE);
328 // TODO: cache any stream datasources as a temporary file (eg. PDBs
329 // retrieved via URL)
330 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
333 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
338 loadtime = -System.currentTimeMillis();
339 AlignmentI al = null;
341 if (FileFormat.Jalview.equals(format))
345 // Tell the user (developer?) that this is going to cause a problem
347 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
348 // We read the data anyway - it might make sense.
350 // BH 2018 switch to File object here instead of filename
351 Platform.timeCheck(null, Platform.TIME_MARK);
352 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
353 Platform.timeCheck("JVP loaded", Platform.TIME_MARK);
358 String error = AppletFormatAdapter.getSupportedFormats();
363 // read from the provided source
364 al = new FormatAdapter().readFromFile(source, format);
369 // open a new source and read from it
370 FormatAdapter fa = new FormatAdapter();
371 boolean downloadStructureFile = format.isStructureFile()
372 && protocol.equals(DataSourceType.URL);
373 if (downloadStructureFile)
375 String structExt = format.getExtensions().split(",")[0];
376 int pt = file.lastIndexOf(file.indexOf('/') >= 0 ? "/"
377 : System.getProperty("file.separator"));
378 String urlLeafName = file.substring(pt,
379 file.lastIndexOf("."));
380 String tempStructureFileStr = createNamedJvTempFile(
381 urlLeafName, structExt);
383 // BH - switching to File object here so as to hold
384 // .秘bytes array directly
385 File tempFile = new File(tempStructureFileStr);
386 UrlDownloadClient.download(file, tempFile);
388 al = fa.readFile(tempFile, DataSourceType.FILE,
390 source = fa.getAlignFile();
394 if (selectedFile == null) {
395 al = fa.readFile(file, protocol, format);
398 al = fa.readFile(selectedFile, protocol, format);
400 source = fa.getAlignFile(); // keep reference for later if
405 } catch (java.io.IOException ex)
407 error = ex.getMessage();
410 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
412 // construct and register dataset sequences
413 for (SequenceI sq : al.getSequences())
415 while (sq.getDatasetSequence() != null)
417 sq = sq.getDatasetSequence();
419 if (sq.getAllPDBEntries() != null)
421 for (PDBEntry pdbe : sq.getAllPDBEntries())
423 // register PDB entries with desktop's structure selection
425 Desktop.getStructureSelectionManager()
426 .registerPDBEntry(pdbe);
431 FeatureSettingsModelI proxyColourScheme = source
432 .getFeatureColourScheme();
433 if (viewport != null)
435 if (proxyColourScheme != null)
437 viewport.applyFeaturesStyle(proxyColourScheme);
439 // append to existing alignment
440 viewport.addAlignment(al, title);
444 // otherwise construct the alignFrame
446 if (source instanceof ComplexAlignFile)
448 HiddenColumns colSel = ((ComplexAlignFile) source)
450 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
451 .getHiddenSequences();
452 String colourSchemeName = ((ComplexAlignFile) source)
453 .getGlobalColourScheme();
454 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
455 .getDisplayedFeatures();
456 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
457 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
458 alignFrame.getViewport().setFeaturesDisplayed(fd);
459 alignFrame.getViewport().setShowSequenceFeatures(
460 ((ComplexAlignFile) source).isShowSeqFeatures());
461 ColourSchemeI cs = ColourSchemeMapper
462 .getJalviewColourScheme(colourSchemeName, al);
465 alignFrame.changeColour(cs);
470 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
471 AlignFrame.DEFAULT_HEIGHT);
472 if (source instanceof FeaturesSourceI)
474 alignFrame.getViewport().setShowSequenceFeatures(true);
477 // add metadata and update ui
478 if (!(protocol == DataSourceType.PASTE))
480 alignFrame.setFileName(file, format);
481 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
483 if (proxyColourScheme != null)
485 alignFrame.getViewport()
486 .applyFeaturesStyle(proxyColourScheme);
488 alignFrame.setStatus(MessageManager.formatMessage(
489 "label.successfully_loaded_file", new String[]
494 // add the window to the GUI
495 // note - this actually should happen regardless of raiseGUI
496 // status in Jalview 3
497 // TODO: define 'virtual desktop' for benefit of headless scripts
498 // that perform queries to find the 'current working alignment'
501 Dimension dim = Platform.getDimIfEmbedded(alignFrame,
502 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
503 alignFrame.setSize(dim);
504 Desktop.addInternalFrame(alignFrame, title, dim.width,
510 alignFrame.setMaximum(jalview.bin.Cache
511 .getDefault("SHOW_FULLSCREEN", false));
512 } catch (java.beans.PropertyVetoException ex)
519 if (Desktop.getInstance() != null)
521 Desktop.getInstance().stopLoading();
524 final String errorMessage = MessageManager.getString(
525 "label.couldnt_load_file") + " " + title + "\n" + error;
526 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
528 if (raiseGUI && Desktop.getDesktopPane() != null)
530 javax.swing.SwingUtilities.invokeLater(new Runnable()
535 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
538 .getString("label.error_loading_file"),
539 JvOptionPane.WARNING_MESSAGE);
545 System.err.println(errorMessage);
550 updateRecentlyOpened();
552 } catch (Exception er)
554 System.err.println("Exception whilst opening file '" + file);
555 er.printStackTrace();
558 javax.swing.SwingUtilities.invokeLater(new Runnable()
563 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
564 MessageManager.formatMessage(
565 "label.problems_opening_file", new String[]
567 MessageManager.getString("label.file_open_error"),
568 JvOptionPane.WARNING_MESSAGE);
573 } catch (OutOfMemoryError er)
576 er.printStackTrace();
580 javax.swing.SwingUtilities.invokeLater(new Runnable()
585 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
586 MessageManager.formatMessage(
587 "warn.out_of_memory_loading_file", new String[]
589 MessageManager.getString("label.out_of_memory"),
590 JvOptionPane.WARNING_MESSAGE);
594 System.err.println("Out of memory loading file " + file + "!!");
597 loadtime += System.currentTimeMillis();
598 // TODO: Estimate percentage of memory used by a newly loaded alignment -
599 // warn if more memory will be needed to work with it
602 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
607 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
609 if (alignFrame != null)
611 AlignmentI al = alignFrame.getViewport().getAlignment();
613 System.out.println("Loaded '" + title + "' in "
614 + (loadtime / 1000.0) + "s, took an additional "
615 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
616 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
620 // report that we didn't load anything probably due to an out of memory
622 System.out.println("Failed to load '" + title + "' in "
623 + (loadtime / 1000.0) + "s, took an additional "
624 + (1.0 * memused / (1024.0 * 1024.0))
625 + " MB (alignment is null)");
628 // remove the visual delay indicator
629 if (Desktop.getInstance() != null)
631 Desktop.getInstance().stopLoading();
637 * This method creates the file -
638 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
639 * file name and extension
642 * the name of the temp file to be created
644 * the extension of the temp file to be created
647 private static String createNamedJvTempFile(String fileName,
648 String extension) throws IOException
650 String seprator = System.getProperty("file.separator");
651 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
652 + seprator + System.currentTimeMillis();
653 File tempStructFile = new File(
654 jvTempDir + seprator + fileName + "." + extension);
655 tempStructFile.mkdirs();
656 return tempStructFile.toString();
661 * @param file a File, or a String which is a name of a file
663 * @throws FileNotFoundException
665 public static BufferedReader getBufferedReader(Object file) throws FileNotFoundException {
666 if (file instanceof String)
668 return new BufferedReader(new FileReader((String) file));
670 byte[] bytes = Platform.getFileBytes((File) file);
673 return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
675 return new BufferedReader(new FileReader((File) file));