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