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