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