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