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