JAL-3063 use JAXB for 'Save as Project' and load project from parameter
[jalview.git] / src / jalview / io / FileLoader.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.io;
22
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.ws.utils.UrlDownloadClient;
43
44 import java.io.File;
45 import java.io.IOException;
46 import java.util.StringTokenizer;
47 import java.util.Vector;
48
49 import javax.swing.SwingUtilities;
50
51 public class FileLoader implements Runnable
52 {
53   String file;
54
55   DataSourceType protocol;
56
57   FileFormatI format;
58
59   AlignmentFileReaderI source = null; // alternative specification of where data
60                                       // comes
61
62   // from
63
64   AlignViewport viewport;
65
66   AlignFrame alignFrame;
67
68   long loadtime;
69
70   long memused;
71
72   boolean raiseGUI = true;
73
74   /**
75    * default constructor always raised errors in GUI dialog boxes
76    */
77   public FileLoader()
78   {
79     this(true);
80   }
81
82   /**
83    * construct a Fileloader that may raise errors non-interactively
84    * 
85    * @param raiseGUI
86    *          true if errors are to be raised as GUI dialog boxes
87    */
88   public FileLoader(boolean raiseGUI)
89   {
90     this.raiseGUI = raiseGUI;
91   }
92
93   public void LoadFile(AlignViewport viewport, String file,
94           DataSourceType protocol, FileFormatI format)
95   {
96     this.viewport = viewport;
97     LoadFile(file, protocol, format);
98   }
99
100   public void LoadFile(String file, DataSourceType protocol,
101           FileFormatI format)
102   {
103     this.file = file;
104     this.protocol = protocol;
105     this.format = format;
106
107     final Thread loader = new Thread(this);
108
109     SwingUtilities.invokeLater(new Runnable()
110     {
111       @Override
112       public void run()
113       {
114         loader.start();
115       }
116     });
117   }
118
119   /**
120    * Load a (file, protocol) source of unknown type
121    * 
122    * @param file
123    * @param protocol
124    */
125   public void LoadFile(String file, DataSourceType protocol)
126   {
127     LoadFile(file, protocol, null);
128   }
129
130   /**
131    * Load alignment from (file, protocol) and wait till loaded
132    * 
133    * @param file
134    * @param sourceType
135    * @return alignFrame constructed from file contents
136    */
137   public AlignFrame LoadFileWaitTillLoaded(String file,
138           DataSourceType sourceType)
139   {
140     return LoadFileWaitTillLoaded(file, sourceType, null);
141   }
142
143   /**
144    * Load alignment from (file, protocol) of type format and wait till loaded
145    * 
146    * @param file
147    * @param sourceType
148    * @param format
149    * @return alignFrame constructed from file contents
150    */
151   public AlignFrame LoadFileWaitTillLoaded(String file,
152           DataSourceType sourceType, FileFormatI format)
153   {
154     this.file = file;
155     this.protocol = sourceType;
156     this.format = format;
157     return _LoadFileWaitTillLoaded();
158   }
159
160   /**
161    * Load alignment from FileParse source of type format and wait till loaded
162    * 
163    * @param source
164    * @param format
165    * @return alignFrame constructed from file contents
166    */
167   public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
168           FileFormatI format)
169   {
170     this.source = source;
171
172     file = source.getInFile();
173     protocol = source.getDataSourceType();
174     this.format = format;
175     return _LoadFileWaitTillLoaded();
176   }
177
178   /**
179    * start thread and wait until finished, then return the alignFrame that's
180    * (hopefully) been read.
181    * 
182    * @return
183    */
184   protected AlignFrame _LoadFileWaitTillLoaded()
185   {
186     Thread loader = new Thread(this);
187     loader.start();
188
189     while (loader.isAlive())
190     {
191       try
192       {
193         Thread.sleep(500);
194       } catch (Exception ex)
195       {
196       }
197     }
198
199     return alignFrame;
200   }
201
202   public void updateRecentlyOpened()
203   {
204     Vector recent = new Vector();
205     if (protocol == DataSourceType.PASTE)
206     {
207       // do nothing if the file was pasted in as text... there is no filename to
208       // refer to it as.
209       return;
210     }
211     if (file != null
212             && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
213     {
214       // ignore files loaded from the system's temporary directory
215       return;
216     }
217     String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
218             : "RECENT_URL";
219
220     String historyItems = jalview.bin.Cache.getProperty(type);
221
222     StringTokenizer st;
223
224     if (historyItems != null)
225     {
226       st = new StringTokenizer(historyItems, "\t");
227
228       while (st.hasMoreTokens())
229       {
230         recent.addElement(st.nextElement().toString().trim());
231       }
232     }
233
234     if (recent.contains(file))
235     {
236       recent.remove(file);
237     }
238
239     StringBuffer newHistory = new StringBuffer(file);
240     for (int i = 0; i < recent.size() && i < 10; i++)
241     {
242       newHistory.append("\t");
243       newHistory.append(recent.elementAt(i));
244     }
245
246     Cache.setProperty(type, newHistory.toString());
247
248     if (protocol == DataSourceType.FILE)
249     {
250       Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
251     }
252   }
253
254   @Override
255   public void run()
256   {
257     String title = protocol == DataSourceType.PASTE
258             ? "Copied From Clipboard"
259             : file;
260     Runtime rt = Runtime.getRuntime();
261     try
262     {
263       if (Desktop.instance != null)
264       {
265         Desktop.instance.startLoading(file);
266       }
267       if (format == null)
268       {
269         // just in case the caller didn't identify the file for us
270         if (source != null)
271         {
272           format = new IdentifyFile().identify(source, false);
273           // identify stream and rewind rather than close
274         }
275         else
276         {
277           format = new IdentifyFile().identify(file, protocol);
278         }
279
280       }
281
282       if (format == null)
283       {
284         Desktop.instance.stopLoading();
285         System.err.println("The input file \"" + file
286                 + "\" has null or unidentifiable data content!");
287         if (!Jalview.isHeadlessMode())
288         {
289           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
290                   MessageManager.getString("label.couldnt_read_data")
291                           + " in " + file + "\n"
292                           + AppletFormatAdapter.getSupportedFormats(),
293                   MessageManager.getString("label.couldnt_read_data"),
294                   JvOptionPane.WARNING_MESSAGE);
295         }
296         return;
297       }
298       // TODO: cache any stream datasources as a temporary file (eg. PDBs
299       // retrieved via URL)
300       if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
301       {
302         System.gc();
303         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
304         // memory
305         // before
306         // load
307       }
308       loadtime = -System.currentTimeMillis();
309       AlignmentI al = null;
310
311       if (FileFormat.Jalview.equals(format))
312       {
313         if (source != null)
314         {
315           // Tell the user (developer?) that this is going to cause a problem
316           System.err.println(
317                   "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
318           // We read the data anyway - it might make sense.
319         }
320         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
321       }
322       else
323       {
324         String error = AppletFormatAdapter.getSupportedFormats();
325         try
326         {
327           if (source != null)
328           {
329             // read from the provided source
330             al = new FormatAdapter().readFromFile(source, format);
331           }
332           else
333           {
334
335             // open a new source and read from it
336             FormatAdapter fa = new FormatAdapter();
337             boolean downloadStructureFile = format.isStructureFile()
338                     && protocol.equals(DataSourceType.URL);
339             if (downloadStructureFile)
340             {
341               String structExt = format.getExtensions().split(",")[0];
342               String urlLeafName = file.substring(
343                       file.lastIndexOf(
344                               System.getProperty("file.separator")),
345                       file.lastIndexOf("."));
346               String tempStructureFileStr = createNamedJvTempFile(
347                       urlLeafName, structExt);
348               UrlDownloadClient.download(file, tempStructureFileStr);
349               al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
350                       format);
351               source = fa.getAlignFile();
352             }
353             else
354             {
355               al = fa.readFile(file, protocol, format);
356               source = fa.getAlignFile(); // keep reference for later if
357                                           // necessary.
358             }
359           }
360         } catch (java.io.IOException ex)
361         {
362           error = ex.getMessage();
363         }
364
365         if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
366         {
367           // construct and register dataset sequences
368           for (SequenceI sq : al.getSequences())
369           {
370             while (sq.getDatasetSequence() != null)
371             {
372               sq = sq.getDatasetSequence();
373             }
374             if (sq.getAllPDBEntries() != null)
375             {
376               for (PDBEntry pdbe : sq.getAllPDBEntries())
377               {
378                 // register PDB entries with desktop's structure selection
379                 // manager
380                 StructureSelectionManager
381                         .getStructureSelectionManager(Desktop.instance)
382                         .registerPDBEntry(pdbe);
383               }
384             }
385           }
386
387           FeatureSettingsModelI proxyColourScheme = source
388                   .getFeatureColourScheme();
389           if (viewport != null)
390           {
391             if (proxyColourScheme != null)
392             {
393               viewport.applyFeaturesStyle(proxyColourScheme);
394             }
395             // append to existing alignment
396             viewport.addAlignment(al, title);
397           }
398           else
399           {
400             // otherwise construct the alignFrame
401
402             if (source instanceof ComplexAlignFile)
403             {
404               HiddenColumns colSel = ((ComplexAlignFile) source)
405                       .getHiddenColumns();
406               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
407                       .getHiddenSequences();
408               String colourSchemeName = ((ComplexAlignFile) source)
409                       .getGlobalColourScheme();
410               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
411                       .getDisplayedFeatures();
412               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
413                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
414               alignFrame.getViewport().setFeaturesDisplayed(fd);
415               alignFrame.getViewport().setShowSequenceFeatures(
416                       ((ComplexAlignFile) source).isShowSeqFeatures());
417               ColourSchemeI cs = ColourSchemeMapper
418                       .getJalviewColourScheme(colourSchemeName, al);
419               if (cs != null)
420               {
421                 alignFrame.changeColour(cs);
422               }
423             }
424             else
425             {
426               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
427                       AlignFrame.DEFAULT_HEIGHT);
428               if (source instanceof FeaturesSourceI)
429               {
430                 alignFrame.getViewport().setShowSequenceFeatures(true);
431               }
432             }
433             // add metadata and update ui
434             if (!(protocol == DataSourceType.PASTE))
435             {
436               alignFrame.setFileName(file, format);
437             }
438             if (proxyColourScheme != null)
439             {
440               alignFrame.getViewport()
441                       .applyFeaturesStyle(proxyColourScheme);
442             }
443             alignFrame.statusBar.setText(MessageManager.formatMessage(
444                     "label.successfully_loaded_file", new String[]
445                     { title }));
446
447             if (raiseGUI)
448             {
449               // add the window to the GUI
450               // note - this actually should happen regardless of raiseGUI
451               // status in Jalview 3
452               // TODO: define 'virtual desktop' for benefit of headless scripts
453               // that perform queries to find the 'current working alignment'
454               Desktop.addInternalFrame(alignFrame, title,
455                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
456             }
457
458             try
459             {
460               alignFrame.setMaximum(jalview.bin.Cache
461                       .getDefault("SHOW_FULLSCREEN", false));
462             } catch (java.beans.PropertyVetoException ex)
463             {
464             }
465           }
466         }
467         else
468         {
469           if (Desktop.instance != null)
470           {
471             Desktop.instance.stopLoading();
472           }
473
474           final String errorMessage = MessageManager.getString(
475                   "label.couldnt_load_file") + " " + title + "\n" + error;
476           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
477           // bits ?
478           if (raiseGUI && Desktop.desktop != null)
479           {
480             javax.swing.SwingUtilities.invokeLater(new Runnable()
481             {
482               @Override
483               public void run()
484               {
485                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
486                         errorMessage,
487                         MessageManager
488                                 .getString("label.error_loading_file"),
489                         JvOptionPane.WARNING_MESSAGE);
490               }
491             });
492           }
493           else
494           {
495             System.err.println(errorMessage);
496           }
497         }
498       }
499
500       updateRecentlyOpened();
501
502     } catch (Exception er)
503     {
504       System.err.println("Exception whilst opening file '" + file);
505       er.printStackTrace();
506       if (raiseGUI)
507       {
508         javax.swing.SwingUtilities.invokeLater(new Runnable()
509         {
510           @Override
511           public void run()
512           {
513             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
514                     MessageManager.formatMessage(
515                             "label.problems_opening_file", new String[]
516                             { file }),
517                     MessageManager.getString("label.file_open_error"),
518                     JvOptionPane.WARNING_MESSAGE);
519           }
520         });
521       }
522       alignFrame = null;
523     } catch (OutOfMemoryError er)
524     {
525
526       er.printStackTrace();
527       alignFrame = null;
528       if (raiseGUI)
529       {
530         javax.swing.SwingUtilities.invokeLater(new Runnable()
531         {
532           @Override
533           public void run()
534           {
535             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
536                     MessageManager.formatMessage(
537                             "warn.out_of_memory_loading_file", new String[]
538                             { file }),
539                     MessageManager.getString("label.out_of_memory"),
540                     JvOptionPane.WARNING_MESSAGE);
541           }
542         });
543       }
544       System.err.println("Out of memory loading file " + file + "!!");
545
546     }
547     loadtime += System.currentTimeMillis();
548     // TODO: Estimate percentage of memory used by a newly loaded alignment -
549     // warn if more memory will be needed to work with it
550     // System.gc();
551     memused = memused
552             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
553     // in free
554     // memory
555     // after
556     // load
557     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
558     {
559       if (alignFrame != null)
560       {
561         AlignmentI al = alignFrame.getViewport().getAlignment();
562
563         System.out.println("Loaded '" + title + "' in "
564                 + (loadtime / 1000.0) + "s, took an additional "
565                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
566                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
567       }
568       else
569       {
570         // report that we didn't load anything probably due to an out of memory
571         // error
572         System.out.println("Failed to load '" + title + "' in "
573                 + (loadtime / 1000.0) + "s, took an additional "
574                 + (1.0 * memused / (1024.0 * 1024.0))
575                 + " MB (alignment is null)");
576       }
577     }
578     // remove the visual delay indicator
579     if (Desktop.instance != null)
580     {
581       Desktop.instance.stopLoading();
582     }
583
584   }
585
586   /**
587    * This method creates the file -
588    * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
589    * file name and extension
590    * 
591    * @param fileName
592    *          the name of the temp file to be created
593    * @param extension
594    *          the extension of the temp file to be created
595    * @return
596    */
597   private static String createNamedJvTempFile(String fileName,
598           String extension) throws IOException
599   {
600     String seprator = System.getProperty("file.separator");
601     String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
602             + seprator + System.currentTimeMillis();
603     File tempStructFile = new File(
604             jvTempDir + seprator + fileName + "." + extension);
605     tempStructFile.mkdirs();
606     return tempStructFile.toString();
607   }
608
609 }