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