JAL-1619 refactoring / tests to support 'align linked dna as protein'
[jalview.git] / src / jalview / io / FileLoader.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
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     file = source.getInFile();
156     protocol = source.type;
157     this.format = format;
158     return _LoadFileWaitTillLoaded();
159   }
160
161   /**
162    * start thread and wait until finished, then return the alignFrame that's
163    * (hopefully) been read.
164    * 
165    * @return
166    */
167   protected AlignFrame _LoadFileWaitTillLoaded()
168   {
169     Thread loader = new Thread(this);
170     loader.start();
171
172     while (loader.isAlive())
173     {
174       try
175       {
176         Thread.sleep(500);
177       } catch (Exception ex)
178       {
179       }
180     }
181
182     return alignFrame;
183   }
184
185   public void updateRecentlyOpened()
186   {
187     Vector recent = new Vector();
188     if (protocol.equals(FormatAdapter.PASTE))
189     {
190       // do nothing if the file was pasted in as text... there is no filename to
191       // refer to it as.
192       return;
193     }
194     String type = protocol.equals(FormatAdapter.FILE) ? "RECENT_FILE"
195             : "RECENT_URL";
196
197     String historyItems = jalview.bin.Cache.getProperty(type);
198
199     StringTokenizer st;
200
201     if (historyItems != null)
202     {
203       st = new StringTokenizer(historyItems, "\t");
204
205       while (st.hasMoreTokens())
206       {
207         recent.addElement(st.nextElement().toString().trim());
208       }
209     }
210
211     if (recent.contains(file))
212     {
213       recent.remove(file);
214     }
215
216     StringBuffer newHistory = new StringBuffer(file);
217     for (int i = 0; i < recent.size() && i < 10; i++)
218     {
219       newHistory.append("\t");
220       newHistory.append(recent.elementAt(i));
221     }
222
223     jalview.bin.Cache.setProperty(type, newHistory.toString());
224
225     if (protocol.equals(FormatAdapter.FILE))
226     {
227       jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT", format);
228     }
229   }
230
231   public void run()
232   {
233     String title = protocol.equals(AppletFormatAdapter.PASTE) ? "Copied From Clipboard"
234             : file;
235     Runtime rt = Runtime.getRuntime();
236     try
237     {
238       if (Desktop.instance != null)
239       {
240         Desktop.instance.startLoading(file);
241       }
242       if (format == null)
243       {
244         // just in case the caller didn't identify the file for us
245         if (source != null)
246         {
247           format = new IdentifyFile().Identify(source, false); // identify
248           // stream and
249           // rewind rather
250           // than close
251         }
252         else
253         {
254           format = new IdentifyFile().Identify(file, protocol);
255         }
256       }
257       // TODO: cache any stream datasources as a temporary file (eg. PDBs
258       // retrieved via URL)
259       if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
260       {
261         System.gc();
262         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
263         // memory
264         // before
265         // load
266       }
267       loadtime = -System.currentTimeMillis();
268       AlignmentI al = null;
269
270       if (format.equalsIgnoreCase("Jalview"))
271       {
272         if (source != null)
273         {
274           // Tell the user (developer?) that this is going to cause a problem
275           System.err
276                   .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
277           // We read the data anyway - it might make sense.
278         }
279         alignFrame = new Jalview2XML(raiseGUI).LoadJalviewAlign(file);
280       }
281       else
282       {
283         String error = AppletFormatAdapter.SUPPORTED_FORMATS;
284         if (FormatAdapter.isValidFormat(format))
285         {
286           try
287           {
288             if (source != null)
289             {
290               // read from the provided source
291               al = new FormatAdapter().readFromFile(source, format);
292             }
293             else
294             {
295
296               // open a new source and read from it
297               FormatAdapter fa = new FormatAdapter();
298               al = fa.readFile(file, protocol, format);
299               source = fa.afile; // keep reference for later if necessary.
300             }
301           } catch (java.io.IOException ex)
302           {
303             error = ex.getMessage();
304           }
305         }
306         else
307         {
308           if (format != null && format.length() > 7)
309           {
310             // ad hoc message in format.
311             error = format + "\n" + error;
312           }
313         }
314
315         if ((al != null) && (al.getHeight() > 0))
316         {
317           for (SequenceI sq : al.getSequences())
318           {
319             while (sq.getDatasetSequence() != null)
320             {
321               sq = sq.getDatasetSequence();
322             }
323             if (sq.getPDBId() != null)
324             {
325               for (PDBEntry pdbe : (List<PDBEntry>) sq.getPDBId())
326               {
327                 StructureSelectionManager.getStructureSelectionManager(
328                         Desktop.instance).registerPDBEntry(pdbe);
329               }
330             }
331           }
332           if (viewport != null)
333           {
334             viewport.addAlignment(al, title);
335           }
336           else
337           {
338             alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
339                     AlignFrame.DEFAULT_HEIGHT);
340
341             alignFrame.statusBar.setText(MessageManager.formatMessage(
342                     "label.successfully_loaded_file", new String[]
343                     { title }));
344
345             if (!protocol.equals(AppletFormatAdapter.PASTE))
346             {
347               alignFrame.setFileName(file, format);
348             }
349             if (raiseGUI)
350             {
351               // add the window to the GUI
352               // note - this actually should happen regardless of raiseGUI
353               // status in Jalview 3
354               // TODO: define 'virtual desktop' for benefit of headless scripts
355               // that perform queries to find the 'current working alignment'
356               Desktop.addInternalFrame(alignFrame, title,
357                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
358             }
359
360             try
361             {
362               alignFrame.setMaximum(jalview.bin.Cache.getDefault(
363                       "SHOW_FULLSCREEN", false));
364             } catch (java.beans.PropertyVetoException ex)
365             {
366             }
367           }
368         }
369         else
370         {
371           if (Desktop.instance != null)
372           {
373             Desktop.instance.stopLoading();
374           }
375
376           final String errorMessage = "Couldn't load file " + title + "\n"
377                   + error;
378           if (raiseGUI)
379           {
380             javax.swing.SwingUtilities.invokeLater(new Runnable()
381             {
382               public void run()
383               {
384                 JOptionPane.showInternalMessageDialog(Desktop.desktop,
385                         errorMessage, MessageManager
386                                 .getString("label.error_loading_file"),
387                         JOptionPane.WARNING_MESSAGE);
388               }
389             });
390           }
391           else
392           {
393             System.err.println(errorMessage);
394           }
395         }
396       }
397
398       updateRecentlyOpened();
399
400     } catch (Exception er)
401     {
402       System.err.println("Exception whilst opening file '" + file);
403       er.printStackTrace();
404       if (raiseGUI)
405       {
406         javax.swing.SwingUtilities.invokeLater(new Runnable()
407         {
408           public void run()
409           {
410             javax.swing.JOptionPane.showInternalMessageDialog(
411                     Desktop.desktop, MessageManager.formatMessage(
412                             "label.problems_opening_file", new String[]
413                             { file }), MessageManager
414                             .getString("label.file_open_error"),
415                     javax.swing.JOptionPane.WARNING_MESSAGE);
416           }
417         });
418       }
419       alignFrame = null;
420     } catch (OutOfMemoryError er)
421     {
422
423       er.printStackTrace();
424       alignFrame = null;
425       if (raiseGUI)
426       {
427         javax.swing.SwingUtilities.invokeLater(new Runnable()
428         {
429           public void run()
430           {
431             javax.swing.JOptionPane
432                     .showInternalMessageDialog(
433                             Desktop.desktop,
434                             MessageManager.formatMessage("warn.out_of_memory_loading_file", new String[]{file}),
435                             MessageManager.getString("label.out_of_memory"),
436                             javax.swing.JOptionPane.WARNING_MESSAGE);
437           }
438         });
439       }
440       System.err.println("Out of memory loading file " + file + "!!");
441
442     }
443     loadtime += System.currentTimeMillis();
444     // TODO: Estimate percentage of memory used by a newly loaded alignment -
445     // warn if more memory will be needed to work with it
446     // System.gc();
447     memused = memused
448             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
449     // in free
450     // memory
451     // after
452     // load
453     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
454     {
455       if (alignFrame != null)
456       {
457         AlignmentI al = alignFrame.getViewport().getAlignment();
458
459         System.out.println("Loaded '" + title + "' in "
460                 + (loadtime / 1000.0) + "s, took an additional "
461                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
462                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
463       }
464       else
465       {
466         // report that we didn't load anything probably due to an out of memory
467         // error
468         System.out.println("Failed to load '" + title + "' in "
469                 + (loadtime / 1000.0) + "s, took an additional "
470                 + (1.0 * memused / (1024.0 * 1024.0))
471                 + " MB (alignment is null)");
472       }
473     }
474     // remove the visual delay indicator
475     if (Desktop.instance != null)
476     {
477       Desktop.instance.stopLoading();
478     }
479
480   }
481
482   /*
483    * (non-Javadoc)
484    * 
485    * @see java.lang.Object#finalize()
486    */
487   protected void finalize() throws Throwable
488   {
489     source = null;
490     alignFrame = null;
491     viewport = null;
492     super.finalize();
493   }
494
495 }