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.io.BufferedReader;
45 import java.io.ByteArrayInputStream;
47 import java.io.FileNotFoundException;
48 import java.io.FileReader;
49 import java.io.IOException;
50 import java.io.InputStreamReader;
51 import java.util.StringTokenizer;
52 import java.util.Vector;
54 import javax.swing.SwingUtilities;
56 public class FileLoader implements Runnable
58 private File selectedFile;
62 DataSourceType protocol;
66 AlignmentFileReaderI source; // alternative specification of where data
70 * It is critical that all these fields are set, as this instance is reused.
75 * @param dataSourceType
78 private void setFileFields(AlignmentFileReaderI source, File file,
79 String inFile, DataSourceType dataSourceType, FileFormatI format)
83 this.selectedFile = file;
84 this.protocol = dataSourceType;
88 AlignViewport viewport;
90 AlignFrame alignFrame;
96 boolean raiseGUI = true;
99 * default constructor always raised errors in GUI dialog boxes
107 * construct a Fileloader that may raise errors non-interactively
110 * true if errors are to be raised as GUI dialog boxes
112 public FileLoader(boolean raiseGUI)
114 this.raiseGUI = raiseGUI;
117 public void loadFile(AlignViewport viewport, Object file,
118 DataSourceType protocol, FileFormatI format)
120 this.viewport = viewport;
121 if (file instanceof File) {
122 this.selectedFile = (File) file;
123 file = selectedFile.getPath();
125 loadFile(file.toString(), protocol, format);
128 public void loadFile(String file, DataSourceType protocol,
132 this.protocol = protocol;
133 this.format = format;
135 final Thread loader = new Thread(this);
137 SwingUtilities.invokeLater(new Runnable()
148 * Load a (file, protocol) source of unknown type
153 public void LoadFile(String file, DataSourceType protocol)
155 loadFile(file, protocol, null);
159 * Load alignment from (file, protocol) and wait till loaded
163 * @return alignFrame constructed from file contents
165 public AlignFrame LoadFileWaitTillLoaded(String file,
166 DataSourceType sourceType)
168 return loadFileWaitTillLoaded(file, sourceType, null);
172 * Load alignment from (file, protocol) of type format and wait till loaded
177 * @return alignFrame constructed from file contents
179 public AlignFrame loadFileWaitTillLoaded(String file,
180 DataSourceType sourceType, FileFormatI format)
182 setFileFields(null, null, file, sourceType, format);
183 return _loadFileWaitTillLoaded();
187 * Load alignment from (file, protocol) of type format and wait till loaded
192 * @return alignFrame constructed from file contents
194 public AlignFrame loadFileWaitTillLoaded(File file,
195 DataSourceType sourceType, FileFormatI format)
197 setFileFields(null, file, null, sourceType, format);
198 return _loadFileWaitTillLoaded();
202 * Load alignment from FileParse source of type format and wait till loaded
206 * @return alignFrame constructed from file contents
208 public AlignFrame loadFileWaitTillLoaded(AlignmentFileReaderI source,
211 setFileFields(source, null, source.getInFile(),
212 source.getDataSourceType(), format);
213 return _loadFileWaitTillLoaded();
217 * runs the 'run' method (in this thread), then return the alignFrame that's
218 * (hopefully) been read
222 private AlignFrame _loadFileWaitTillLoaded()
228 public void updateRecentlyOpened()
230 Vector<String> recent = new Vector<>();
231 if (protocol == DataSourceType.PASTE)
233 // do nothing if the file was pasted in as text... there is no filename to
238 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
240 // ignore files loaded from the system's temporary directory
243 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
246 String historyItems = Cache.getProperty(type);
250 if (historyItems != null)
252 st = new StringTokenizer(historyItems, "\t");
254 while (st.hasMoreTokens())
256 recent.addElement(st.nextToken().trim());
260 if (recent.contains(file))
265 StringBuffer newHistory = new StringBuffer(file);
266 for (int i = 0; i < recent.size() && i < 10; i++)
268 newHistory.append("\t");
269 newHistory.append(recent.elementAt(i));
272 Cache.setProperty(type, newHistory.toString());
274 if (protocol == DataSourceType.FILE)
276 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
283 String title = protocol == DataSourceType.PASTE
284 ? "Copied From Clipboard"
286 Runtime rt = Runtime.getRuntime();
289 if (Desktop.getInstance() != null)
291 Desktop.getInstance().startLoading(file);
295 // just in case the caller didn't identify the file for us
298 format = new IdentifyFile().identify(source, false);
299 // identify stream and rewind rather than close
301 else if (selectedFile != null) {
302 format = new IdentifyFile().identify(selectedFile, protocol);
306 format = new IdentifyFile().identify(file, protocol);
313 Desktop.getInstance().stopLoading();
314 System.err.println("The input file \"" + file
315 + "\" has null or unidentifiable data content!");
316 if (!Jalview.isHeadlessMode())
318 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
319 MessageManager.getString("label.couldnt_read_data")
320 + " in " + file + "\n"
321 + AppletFormatAdapter.getSupportedFormats(),
322 MessageManager.getString("label.couldnt_read_data"),
323 JvOptionPane.WARNING_MESSAGE);
327 // TODO: cache any stream datasources as a temporary file (eg. PDBs
328 // retrieved via URL)
329 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
332 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
337 loadtime = -System.currentTimeMillis();
338 AlignmentI al = null;
340 if (FileFormat.Jalview.equals(format))
344 // Tell the user (developer?) that this is going to cause a problem
346 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
347 // We read the data anyway - it might make sense.
349 // BH 2018 switch to File object here instead of filename
350 Platform.timeCheck(null, Platform.TIME_MARK);
351 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
352 Platform.timeCheck("JVP loaded", Platform.TIME_MARK);
357 String error = AppletFormatAdapter.getSupportedFormats();
362 // read from the provided source
363 al = new FormatAdapter().readFromFile(source, format);
368 // open a new source and read from it
369 FormatAdapter fa = new FormatAdapter();
370 boolean downloadStructureFile = format.isStructureFile()
371 && protocol.equals(DataSourceType.URL);
372 if (downloadStructureFile)
374 String structExt = format.getExtensions().split(",")[0];
375 int pt = file.lastIndexOf(file.indexOf('/') >= 0 ? "/"
376 : System.getProperty("file.separator"));
377 String urlLeafName = file.substring(pt,
378 file.lastIndexOf("."));
379 String tempStructureFileStr = createNamedJvTempFile(
380 urlLeafName, structExt);
382 // BH - switching to File object here so as to hold
383 // .秘bytes array directly
384 File tempFile = new File(tempStructureFileStr);
385 UrlDownloadClient.download(file, tempFile);
387 al = fa.readFile(tempFile, DataSourceType.FILE,
389 source = fa.getAlignFile();
393 if (selectedFile == null) {
394 al = fa.readFile(file, protocol, format);
397 al = fa.readFile(selectedFile, protocol, format);
399 source = fa.getAlignFile(); // keep reference for later if
404 } catch (java.io.IOException ex)
406 error = ex.getMessage();
409 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
411 // construct and register dataset sequences
412 for (SequenceI sq : al.getSequences())
414 while (sq.getDatasetSequence() != null)
416 sq = sq.getDatasetSequence();
418 if (sq.getAllPDBEntries() != null)
420 for (PDBEntry pdbe : sq.getAllPDBEntries())
422 // register PDB entries with desktop's structure selection
424 Desktop.getStructureSelectionManager()
425 .registerPDBEntry(pdbe);
430 FeatureSettingsModelI proxyColourScheme = source
431 .getFeatureColourScheme();
432 if (viewport != null)
434 if (proxyColourScheme != null)
436 viewport.applyFeaturesStyle(proxyColourScheme);
438 // append to existing alignment
439 viewport.addAlignment(al, title);
443 // otherwise construct the alignFrame
445 if (source instanceof ComplexAlignFile)
447 HiddenColumns colSel = ((ComplexAlignFile) source)
449 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
450 .getHiddenSequences();
451 String colourSchemeName = ((ComplexAlignFile) source)
452 .getGlobalColourScheme();
453 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
454 .getDisplayedFeatures();
455 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
456 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
457 alignFrame.getViewport().setFeaturesDisplayed(fd);
458 alignFrame.getViewport().setShowSequenceFeatures(
459 ((ComplexAlignFile) source).isShowSeqFeatures());
460 ColourSchemeI cs = ColourSchemeMapper
461 .getJalviewColourScheme(colourSchemeName, al);
464 alignFrame.changeColour(cs);
469 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
470 AlignFrame.DEFAULT_HEIGHT);
471 if (source instanceof FeaturesSourceI)
473 alignFrame.getViewport().setShowSequenceFeatures(true);
476 // add metadata and update ui
477 if (!(protocol == DataSourceType.PASTE))
479 alignFrame.setFileName(file, format);
480 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
482 if (proxyColourScheme != null)
484 alignFrame.getViewport()
485 .applyFeaturesStyle(proxyColourScheme);
487 alignFrame.setStatus(MessageManager.formatMessage(
488 "label.successfully_loaded_file", new String[]
493 // add the window to the GUI
494 // note - this actually should happen regardless of raiseGUI
495 // status in Jalview 3
496 // TODO: define 'virtual desktop' for benefit of headless scripts
497 // that perform queries to find the 'current working alignment'
498 Desktop.addInternalFrame(alignFrame, title,
499 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
504 alignFrame.setMaximum(jalview.bin.Cache
505 .getDefault("SHOW_FULLSCREEN", false));
506 } catch (java.beans.PropertyVetoException ex)
513 if (Desktop.getInstance() != null)
515 Desktop.getInstance().stopLoading();
518 final String errorMessage = MessageManager.getString(
519 "label.couldnt_load_file") + " " + title + "\n" + error;
520 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
522 if (raiseGUI && Desktop.getDesktopPane() != null)
524 javax.swing.SwingUtilities.invokeLater(new Runnable()
529 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
532 .getString("label.error_loading_file"),
533 JvOptionPane.WARNING_MESSAGE);
539 System.err.println(errorMessage);
544 updateRecentlyOpened();
546 } catch (Exception er)
548 System.err.println("Exception whilst opening file '" + file);
549 er.printStackTrace();
552 javax.swing.SwingUtilities.invokeLater(new Runnable()
557 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
558 MessageManager.formatMessage(
559 "label.problems_opening_file", new String[]
561 MessageManager.getString("label.file_open_error"),
562 JvOptionPane.WARNING_MESSAGE);
567 } catch (OutOfMemoryError er)
570 er.printStackTrace();
574 javax.swing.SwingUtilities.invokeLater(new Runnable()
579 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
580 MessageManager.formatMessage(
581 "warn.out_of_memory_loading_file", new String[]
583 MessageManager.getString("label.out_of_memory"),
584 JvOptionPane.WARNING_MESSAGE);
588 System.err.println("Out of memory loading file " + file + "!!");
591 loadtime += System.currentTimeMillis();
592 // TODO: Estimate percentage of memory used by a newly loaded alignment -
593 // warn if more memory will be needed to work with it
596 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
601 if (Desktop.getDesktopPane() != null && Desktop.getDesktopPane().isShowMemoryUsage())
603 if (alignFrame != null)
605 AlignmentI al = alignFrame.getViewport().getAlignment();
607 System.out.println("Loaded '" + title + "' in "
608 + (loadtime / 1000.0) + "s, took an additional "
609 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
610 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
614 // report that we didn't load anything probably due to an out of memory
616 System.out.println("Failed to load '" + title + "' in "
617 + (loadtime / 1000.0) + "s, took an additional "
618 + (1.0 * memused / (1024.0 * 1024.0))
619 + " MB (alignment is null)");
622 // remove the visual delay indicator
623 if (Desktop.getInstance() != null)
625 Desktop.getInstance().stopLoading();
631 * This method creates the file -
632 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
633 * file name and extension
636 * the name of the temp file to be created
638 * the extension of the temp file to be created
641 private static String createNamedJvTempFile(String fileName,
642 String extension) throws IOException
644 String seprator = System.getProperty("file.separator");
645 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
646 + seprator + System.currentTimeMillis();
647 File tempStructFile = new File(
648 jvTempDir + seprator + fileName + "." + extension);
649 tempStructFile.mkdirs();
650 return tempStructFile.toString();
655 * @param file a File, or a String which is a name of a file
657 * @throws FileNotFoundException
659 public static BufferedReader getBufferedReader(Object file) throws FileNotFoundException {
660 if (file instanceof String)
662 return new BufferedReader(new FileReader((String) file));
664 byte[] bytes = Platform.getFileBytes((File) file);
667 return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
669 return new BufferedReader(new FileReader((File) file));