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