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