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.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.util.Platform;
43 import jalview.ws.utils.UrlDownloadClient;
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.StringTokenizer;
53 import java.util.Vector;
55 import javax.swing.SwingUtilities;
57 public class FileLoader implements Runnable
59 private File selectedFile;
63 DataSourceType protocol;
67 AlignmentFileReaderI source; // alternative specification of where data
71 * It is critical that all these fields are set, as this instance is reused.
76 * @param dataSourceType
79 private void setFileFields(AlignmentFileReaderI source, File file,
80 String inFile, DataSourceType dataSourceType, FileFormatI format)
84 this.selectedFile = file;
85 this.protocol = dataSourceType;
89 AlignViewport viewport;
91 AlignFrame alignFrame;
97 boolean raiseGUI = true;
100 * default constructor always raised errors in GUI dialog boxes
108 * construct a Fileloader that may raise errors non-interactively
111 * true if errors are to be raised as GUI dialog boxes
113 public FileLoader(boolean raiseGUI)
115 this.raiseGUI = raiseGUI;
118 public void loadFile(AlignViewport viewport, Object file,
119 DataSourceType protocol, FileFormatI format)
121 this.viewport = viewport;
122 if (file instanceof File) {
123 this.selectedFile = (File) file;
124 file = selectedFile.getPath();
126 loadFile(file.toString(), protocol, format);
129 public void loadFile(String file, DataSourceType protocol,
133 this.protocol = protocol;
134 this.format = format;
136 final Thread loader = new Thread(this);
138 SwingUtilities.invokeLater(new Runnable()
149 * Load a (file, protocol) source of unknown type
154 public void LoadFile(String file, DataSourceType protocol)
156 loadFile(file, protocol, null);
160 * Load alignment from (file, protocol) and wait till loaded
164 * @return alignFrame constructed from file contents
166 public AlignFrame LoadFileWaitTillLoaded(String file,
167 DataSourceType sourceType)
169 return loadFileWaitTillLoaded(file, sourceType, null);
173 * Load alignment from (file, protocol) of type format and wait till loaded
178 * @return alignFrame constructed from file contents
180 public AlignFrame loadFileWaitTillLoaded(String file,
181 DataSourceType sourceType, FileFormatI format)
183 setFileFields(null, null, file, sourceType, format);
184 return _loadFileWaitTillLoaded();
188 * Load alignment from (file, protocol) of type format and wait till loaded
193 * @return alignFrame constructed from file contents
195 public AlignFrame loadFileWaitTillLoaded(File file,
196 DataSourceType sourceType, FileFormatI format)
198 setFileFields(null, file, null, sourceType, format);
199 return _loadFileWaitTillLoaded();
203 * Load alignment from FileParse source of type format and wait till loaded
207 * @return alignFrame constructed from file contents
209 public AlignFrame loadFileWaitTillLoaded(AlignmentFileReaderI source,
212 setFileFields(source, null, source.getInFile(),
213 source.getDataSourceType(), format);
214 return _loadFileWaitTillLoaded();
218 * runs the 'run' method (in this thread), then return the alignFrame that's
219 * (hopefully) been read
223 private AlignFrame _loadFileWaitTillLoaded()
229 public void updateRecentlyOpened()
231 Vector<String> recent = new Vector<>();
232 if (protocol == DataSourceType.PASTE)
234 // do nothing if the file was pasted in as text... there is no filename to
239 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
241 // ignore files loaded from the system's temporary directory
244 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
247 String historyItems = Cache.getProperty(type);
251 if (historyItems != null)
253 st = new StringTokenizer(historyItems, "\t");
255 while (st.hasMoreTokens())
257 recent.addElement(st.nextToken().trim());
261 if (recent.contains(file))
266 StringBuffer newHistory = new StringBuffer(file);
267 for (int i = 0; i < recent.size() && i < 10; i++)
269 newHistory.append("\t");
270 newHistory.append(recent.elementAt(i));
273 Cache.setProperty(type, newHistory.toString());
275 if (protocol == DataSourceType.FILE)
277 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
286 String title = protocol == DataSourceType.PASTE
287 ? "Copied From Clipboard"
289 Runtime rt = Runtime.getRuntime();
292 if (Desktop.getInstance() != null)
294 Desktop.getInstance().startLoading(file);
298 // just in case the caller didn't identify the file for us
301 format = new IdentifyFile().identify(source, false);
302 // identify stream and rewind rather than close
304 else if (selectedFile != null)
306 format = new IdentifyFile().identify(selectedFile, protocol);
310 format = new IdentifyFile().identify(file, protocol);
317 Desktop.getInstance().stopLoading();
318 System.err.println("The input file \"" + file
319 + "\" has null or unidentifiable data content!");
320 if (!Jalview.isHeadlessMode())
322 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
323 MessageManager.getString("label.couldnt_read_data")
324 + " in " + file + "\n"
325 + AppletFormatAdapter.getSupportedFormats(),
326 MessageManager.getString("label.couldnt_read_data"),
327 JvOptionPane.WARNING_MESSAGE);
332 // TODO: cache any stream datasources as a temporary file (eg. PDBs
333 // retrieved via URL)
334 if (Desktop.getDesktopPane() != null
335 && Desktop.getDesktopPane().isShowMemoryUsage())
338 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
343 loadtime = -System.currentTimeMillis();
344 AlignmentI al = null;
346 if (FileFormat.Jalview.equals(format))
350 // Tell the user (developer?) that this is going to cause a problem
352 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
353 // We read the data anyway - it might make sense.
355 // BH 2018 switch to File object here instead of filename
356 Platform.timeCheck(null, Platform.TIME_MARK);
357 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
358 selectedFile == null ? file : selectedFile);
359 Platform.timeCheck("JVP loaded", Platform.TIME_MARK);
364 String error = AppletFormatAdapter.getSupportedFormats();
369 // read from the provided source
370 al = new FormatAdapter().readFromFile(source, format);
375 // open a new source and read from it
376 FormatAdapter fa = new FormatAdapter();
377 boolean downloadStructureFile = format.isStructureFile()
378 && protocol.equals(DataSourceType.URL);
379 if (downloadStructureFile)
381 String structExt = format.getExtensions().split(",")[0];
382 int pt = file.lastIndexOf(file.indexOf('/') >= 0 ? "/"
383 : System.getProperty("file.separator"));
384 String urlLeafName = file.substring(pt,
385 file.lastIndexOf("."));
386 String tempStructureFileStr = createNamedJvTempFile(
387 urlLeafName, structExt);
389 // BH - switching to File object here so as to hold
390 // .秘bytes array directly
391 File tempFile = new File(tempStructureFileStr);
392 UrlDownloadClient.download(file, tempFile);
394 al = fa.readFile(tempFile, DataSourceType.FILE, format);
395 source = fa.getAlignFile();
399 if (selectedFile == null)
401 al = fa.readFile(file, protocol, format);
406 al = fa.readFile(selectedFile, protocol, format);
408 source = fa.getAlignFile(); // keep reference for later if
413 } catch (java.io.IOException ex)
415 error = ex.getMessage();
418 System.out.println("OK1");
421 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
425 // construct and register dataset sequences
427 StructureSelectionManager ssm = StructureSelectionManager
428 .getStructureSelectionManager(Desktop.getInstance());
429 for (SequenceI sq : al.getSequences())
431 while (sq.getDatasetSequence() != null)
433 sq = sq.getDatasetSequence();
435 if (sq.getAllPDBEntries() != null)
437 for (PDBEntry pdbe : sq.getAllPDBEntries())
439 // register PDB entries with desktop's structure selection
441 ssm.registerPDBEntry(pdbe);
446 FeatureSettingsModelI proxyColourScheme = source
447 .getFeatureColourScheme();
449 if (viewport != null)
452 if (proxyColourScheme != null)
454 viewport.applyFeaturesStyle(proxyColourScheme);
456 // append to existing alignment
457 viewport.addAlignment(al, title);
462 System.out.println("OK9");
463 // otherwise construct the alignFrame
465 if (source instanceof ComplexAlignFile)
467 HiddenColumns colSel = ((ComplexAlignFile) source)
469 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
470 .getHiddenSequences();
471 String colourSchemeName = ((ComplexAlignFile) source)
472 .getGlobalColourScheme();
473 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
474 .getDisplayedFeatures();
476 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
477 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
479 alignFrame.getViewport().setFeaturesDisplayed(fd);
480 alignFrame.getViewport().setShowSequenceFeatures(
481 ((ComplexAlignFile) source).isShowSeqFeatures());
482 ColourSchemeI cs = ColourSchemeMapper
483 .getJalviewColourScheme(colourSchemeName, al);
486 alignFrame.changeColour(cs);
492 // Headless start fails here in Windows
494 // Sorry, no JInternalFrame when headless, at least in Windows.
495 // Not clear why that would be, since an InternalFrame is not a
496 // top-level component. But maybe it is
498 System.out.println("FileLoader test1");
503 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
504 AlignFrame.DEFAULT_HEIGHT);
506 System.out.println("FileLoader test2");
508 } catch (Throwable t)
510 System.out.println(t);
514 if (source instanceof FeaturesSourceI)
517 System.out.println("FileLoader test3");
519 alignFrame.getViewport().setShowSequenceFeatures(true);
522 // add metadata and update ui
524 System.out.println("FileLoader test4");
526 if (!(protocol == DataSourceType.PASTE))
529 System.out.println("FileLoader test5");
530 alignFrame.setFileName(file, format);
531 alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
534 System.out.println("FileLoader test6");
536 if (proxyColourScheme != null)
538 alignFrame.getViewport()
539 .applyFeaturesStyle(proxyColourScheme);
542 System.out.println("FileLoader test7");
544 alignFrame.setStatus(MessageManager.formatMessage(
545 "label.successfully_loaded_file", new String[]
548 System.out.println("FileLoader test8" + raiseGUI);
551 // add the window to the GUI
552 // note - this actually should happen regardless of raiseGUI
553 // status in Jalview 3
554 // TODO: define 'virtual desktop' for benefit of headless scripts
555 // that perform queries to find the 'current working alignment'
556 Desktop.addInternalFrame(alignFrame, title,
557 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
562 alignFrame.setMaximum(jalview.bin.Cache
563 .getDefault("SHOW_FULLSCREEN", false));
564 } catch (java.beans.PropertyVetoException ex)
572 System.out.println("OK10");
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
585 javax.swing.SwingUtilities.invokeLater(new Runnable()
590 JvOptionPane.showInternalMessageDialog(
591 Desktop.getDesktopPane(), errorMessage,
593 .getString("label.error_loading_file"),
594 JvOptionPane.WARNING_MESSAGE);
600 System.err.println(errorMessage);
606 updateRecentlyOpened();
608 } catch (Exception er)
610 System.err.println("Exception whilst opening file '" + file);
611 er.printStackTrace();
614 javax.swing.SwingUtilities.invokeLater(new Runnable()
619 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
620 MessageManager.formatMessage(
621 "label.problems_opening_file", new String[]
623 MessageManager.getString("label.file_open_error"),
624 JvOptionPane.WARNING_MESSAGE);
629 } catch (OutOfMemoryError er)
632 er.printStackTrace();
636 javax.swing.SwingUtilities.invokeLater(new Runnable()
641 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
642 MessageManager.formatMessage(
643 "warn.out_of_memory_loading_file", new String[]
645 MessageManager.getString("label.out_of_memory"),
646 JvOptionPane.WARNING_MESSAGE);
650 System.err.println("Out of memory loading file " + file + "!!");
653 loadtime += System.currentTimeMillis();
655 // TODO: Estimate percentage of memory used by a newly loaded alignment -
656 // warn if more memory will be needed to work with it
659 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
664 if (Desktop.getDesktopPane() != null
665 && Desktop.getDesktopPane().isShowMemoryUsage())
667 if (alignFrame != null)
669 AlignmentI al = alignFrame.getViewport().getAlignment();
671 System.out.println("Loaded '" + title + "' in "
672 + (loadtime / 1000.0) + "s, took an additional "
673 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
674 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
678 // report that we didn't load anything probably due to an out of memory
680 System.out.println("Failed to load '" + title + "' in "
681 + (loadtime / 1000.0) + "s, took an additional "
682 + (1.0 * memused / (1024.0 * 1024.0))
683 + " MB (alignment is null)");
686 // remove the visual delay indicator
687 if (Desktop.getInstance() != null)
689 Desktop.getInstance().stopLoading();
695 * This method creates the file -
696 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
697 * file name and extension
700 * the name of the temp file to be created
702 * the extension of the temp file to be created
705 private static String createNamedJvTempFile(String fileName,
706 String extension) throws IOException
708 String seprator = System.getProperty("file.separator");
709 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
710 + seprator + System.currentTimeMillis();
711 File tempStructFile = new File(
712 jvTempDir + seprator + fileName + "." + extension);
713 tempStructFile.mkdirs();
714 return tempStructFile.toString();
719 * @param file a File, or a String which is a name of a file
721 * @throws FileNotFoundException
723 public static BufferedReader getBufferedReader(Object file) throws FileNotFoundException {
724 if (file instanceof String)
726 return new BufferedReader(new FileReader((String) file));
728 byte[] bytes = Platform.getFileBytes((File) file);
731 return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
733 return new BufferedReader(new FileReader((File) file));