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.Jalview2XML;
37 import jalview.gui.JvOptionPane;
38 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
39 import jalview.schemes.ColourSchemeI;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.ws.utils.UrlDownloadClient;
45 import java.io.IOException;
46 import java.util.StringTokenizer;
47 import java.util.Vector;
49 import javax.swing.SwingUtilities;
51 public class FileLoader implements Runnable
55 DataSourceType protocol;
59 AlignmentFileReaderI source = null; // alternative specification of where data
64 AlignViewport viewport;
66 AlignFrame alignFrame;
72 boolean raiseGUI = true;
74 private File selectedFile;
77 * default constructor always raised errors in GUI dialog boxes
85 * construct a Fileloader that may raise errors non-interactively
88 * true if errors are to be raised as GUI dialog boxes
90 public FileLoader(boolean raiseGUI)
92 this.raiseGUI = raiseGUI;
95 public void LoadFile(AlignViewport viewport, String file,
96 DataSourceType protocol, FileFormatI format)
98 this.viewport = viewport;
99 LoadFile(file, protocol, format);
102 public void LoadFile(AlignViewport viewport, File selectedFile,
103 DataSourceType protocol, FileFormatI format)
105 this.viewport = viewport;
106 this.selectedFile = selectedFile;
107 LoadFile(selectedFile.getPath(), protocol, format);
110 public void LoadFile(String file, DataSourceType protocol,
114 this.protocol = protocol;
115 this.format = format;
117 final Thread loader = new Thread(this);
119 SwingUtilities.invokeLater(new Runnable()
130 * Load a (file, protocol) source of unknown type
135 public void LoadFile(String file, DataSourceType protocol)
137 LoadFile(file, protocol, null);
141 * Load alignment from (file, protocol) and wait till loaded
145 * @return alignFrame constructed from file contents
147 public AlignFrame LoadFileWaitTillLoaded(String file,
148 DataSourceType sourceType)
150 return LoadFileWaitTillLoaded(file, sourceType, null);
154 * Load alignment from (file, protocol) of type format and wait till loaded
159 * @return alignFrame constructed from file contents
161 public AlignFrame LoadFileWaitTillLoaded(String file,
162 DataSourceType sourceType, FileFormatI format)
165 this.protocol = sourceType;
166 this.format = format;
167 return _LoadFileWaitTillLoaded();
171 * Load alignment from FileParse source of type format and wait till loaded
175 * @return alignFrame constructed from file contents
177 public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
180 this.source = source;
182 file = source.getInFile();
183 protocol = source.getDataSourceType();
184 this.format = format;
185 return _LoadFileWaitTillLoaded();
189 * runs the 'run' method (in this thread), then return the alignFrame that's
190 * (hopefully) been read
194 protected AlignFrame _LoadFileWaitTillLoaded()
200 public void updateRecentlyOpened()
202 Vector<String> recent = new Vector<>();
203 if (protocol == DataSourceType.PASTE)
205 // do nothing if the file was pasted in as text... there is no filename to
210 && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
212 // ignore files loaded from the system's temporary directory
215 String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
218 String historyItems = Cache.getProperty(type);
222 if (historyItems != null)
224 st = new StringTokenizer(historyItems, "\t");
226 while (st.hasMoreTokens())
228 recent.addElement(st.nextToken().trim());
232 if (recent.contains(file))
237 StringBuffer newHistory = new StringBuffer(file);
238 for (int i = 0; i < recent.size() && i < 10; i++)
240 newHistory.append("\t");
241 newHistory.append(recent.elementAt(i));
244 Cache.setProperty(type, newHistory.toString());
246 if (protocol == DataSourceType.FILE)
248 Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
255 String title = protocol == DataSourceType.PASTE
256 ? "Copied From Clipboard"
258 Runtime rt = Runtime.getRuntime();
261 if (Desktop.instance != null)
263 Desktop.instance.startLoading(file);
267 // just in case the caller didn't identify the file for us
270 format = new IdentifyFile().identify(source, false);
271 // identify stream and rewind rather than close
273 else if (selectedFile != null) {
274 format = new IdentifyFile().identify(selectedFile, protocol);
278 format = new IdentifyFile().identify(file, protocol);
285 Desktop.instance.stopLoading();
286 System.err.println("The input file \"" + file
287 + "\" has null or unidentifiable data content!");
288 if (!Jalview.isHeadlessMode())
290 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
291 MessageManager.getString("label.couldnt_read_data")
292 + " in " + file + "\n"
293 + AppletFormatAdapter.getSupportedFormats(),
294 MessageManager.getString("label.couldnt_read_data"),
295 JvOptionPane.WARNING_MESSAGE);
299 // TODO: cache any stream datasources as a temporary file (eg. PDBs
300 // retrieved via URL)
301 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
304 memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
309 loadtime = -System.currentTimeMillis();
310 AlignmentI al = null;
312 if (FileFormat.Jalview.equals(format))
316 // Tell the user (developer?) that this is going to cause a problem
318 "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
319 // We read the data anyway - it might make sense.
321 alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
325 String error = AppletFormatAdapter.getSupportedFormats();
330 // read from the provided source
331 al = new FormatAdapter().readFromFile(source, format);
336 // open a new source and read from it
337 FormatAdapter fa = new FormatAdapter();
338 boolean downloadStructureFile = format.isStructureFile()
339 && protocol.equals(DataSourceType.URL);
340 if (downloadStructureFile)
342 String structExt = format.getExtensions().split(",")[0];
343 String urlLeafName = file.substring(
345 System.getProperty("file.separator")),
346 file.lastIndexOf("."));
347 String tempStructureFileStr = createNamedJvTempFile(
348 urlLeafName, structExt);
349 UrlDownloadClient.download(file, tempStructureFileStr);
350 al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
352 source = fa.getAlignFile();
356 if (selectedFile == null) {
357 al = fa.readFile(file, protocol, format);
360 al = fa.readFile(selectedFile, protocol, format);
362 source = fa.getAlignFile(); // keep reference for later if
367 } catch (java.io.IOException ex)
369 error = ex.getMessage();
372 if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
374 // construct and register dataset sequences
375 for (SequenceI sq : al.getSequences())
377 while (sq.getDatasetSequence() != null)
379 sq = sq.getDatasetSequence();
381 if (sq.getAllPDBEntries() != null)
383 for (PDBEntry pdbe : sq.getAllPDBEntries())
385 // register PDB entries with desktop's structure selection
387 StructureSelectionManager
388 .getStructureSelectionManager(Desktop.instance)
389 .registerPDBEntry(pdbe);
394 FeatureSettingsModelI proxyColourScheme = source
395 .getFeatureColourScheme();
396 if (viewport != null)
398 if (proxyColourScheme != null)
400 viewport.applyFeaturesStyle(proxyColourScheme);
402 // append to existing alignment
403 viewport.addAlignment(al, title);
407 // otherwise construct the alignFrame
409 if (source instanceof ComplexAlignFile)
411 HiddenColumns colSel = ((ComplexAlignFile) source)
413 SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
414 .getHiddenSequences();
415 String colourSchemeName = ((ComplexAlignFile) source)
416 .getGlobalColourScheme();
417 FeaturesDisplayedI fd = ((ComplexAlignFile) source)
418 .getDisplayedFeatures();
419 alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
420 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
421 alignFrame.getViewport().setFeaturesDisplayed(fd);
422 alignFrame.getViewport().setShowSequenceFeatures(
423 ((ComplexAlignFile) source).isShowSeqFeatures());
424 ColourSchemeI cs = ColourSchemeMapper
425 .getJalviewColourScheme(colourSchemeName, al);
428 alignFrame.changeColour(cs);
433 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
434 AlignFrame.DEFAULT_HEIGHT);
435 if (source instanceof FeaturesSourceI)
437 alignFrame.getViewport().setShowSequenceFeatures(true);
440 // add metadata and update ui
441 if (!(protocol == DataSourceType.PASTE))
443 alignFrame.setFileName(file, format);
445 if (proxyColourScheme != null)
447 alignFrame.getViewport()
448 .applyFeaturesStyle(proxyColourScheme);
450 alignFrame.statusBar.setText(MessageManager.formatMessage(
451 "label.successfully_loaded_file", new String[]
456 // add the window to the GUI
457 // note - this actually should happen regardless of raiseGUI
458 // status in Jalview 3
459 // TODO: define 'virtual desktop' for benefit of headless scripts
460 // that perform queries to find the 'current working alignment'
461 Desktop.addInternalFrame(alignFrame, title,
462 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
467 alignFrame.setMaximum(jalview.bin.Cache
468 .getDefault("SHOW_FULLSCREEN", false));
469 } catch (java.beans.PropertyVetoException ex)
476 if (Desktop.instance != null)
478 Desktop.instance.stopLoading();
481 final String errorMessage = MessageManager.getString(
482 "label.couldnt_load_file") + " " + title + "\n" + error;
483 // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
485 if (raiseGUI && Desktop.desktop != null)
487 javax.swing.SwingUtilities.invokeLater(new Runnable()
492 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
495 .getString("label.error_loading_file"),
496 JvOptionPane.WARNING_MESSAGE);
502 System.err.println(errorMessage);
507 updateRecentlyOpened();
509 } catch (Exception er)
511 System.err.println("Exception whilst opening file '" + file);
512 er.printStackTrace();
515 javax.swing.SwingUtilities.invokeLater(new Runnable()
520 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
521 MessageManager.formatMessage(
522 "label.problems_opening_file", new String[]
524 MessageManager.getString("label.file_open_error"),
525 JvOptionPane.WARNING_MESSAGE);
530 } catch (OutOfMemoryError er)
533 er.printStackTrace();
537 javax.swing.SwingUtilities.invokeLater(new Runnable()
542 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
543 MessageManager.formatMessage(
544 "warn.out_of_memory_loading_file", new String[]
546 MessageManager.getString("label.out_of_memory"),
547 JvOptionPane.WARNING_MESSAGE);
551 System.err.println("Out of memory loading file " + file + "!!");
554 loadtime += System.currentTimeMillis();
555 // TODO: Estimate percentage of memory used by a newly loaded alignment -
556 // warn if more memory will be needed to work with it
559 - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
564 if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
566 if (alignFrame != null)
568 AlignmentI al = alignFrame.getViewport().getAlignment();
570 System.out.println("Loaded '" + title + "' in "
571 + (loadtime / 1000.0) + "s, took an additional "
572 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
573 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
577 // report that we didn't load anything probably due to an out of memory
579 System.out.println("Failed to load '" + title + "' in "
580 + (loadtime / 1000.0) + "s, took an additional "
581 + (1.0 * memused / (1024.0 * 1024.0))
582 + " MB (alignment is null)");
585 // remove the visual delay indicator
586 if (Desktop.instance != null)
588 Desktop.instance.stopLoading();
594 * This method creates the file -
595 * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
596 * file name and extension
599 * the name of the temp file to be created
601 * the extension of the temp file to be created
604 private static String createNamedJvTempFile(String fileName,
605 String extension) throws IOException
607 String seprator = System.getProperty("file.separator");
608 String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
609 + seprator + System.currentTimeMillis();
610 File tempStructFile = new File(
611 jvTempDir + seprator + fileName + "." + extension);
612 tempStructFile.mkdirs();
613 return tempStructFile.toString();