JAL-3451 setting dimensions for AlignFrame if embedded
[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.StringTokenizer;
53 import java.util.Vector;
54
55 import javax.swing.SwingUtilities;
56
57 public class FileLoader implements Runnable
58 {
59   private File selectedFile;
60
61   String file;
62
63   DataSourceType protocol;
64
65   FileFormatI format;
66
67   AlignmentFileReaderI source; // alternative specification of where data
68                                // comes from
69
70   /**
71    * It is critical that all these fields are set, as this instance is reused.
72    * 
73    * @param source
74    * @param file
75    * @param inFile
76    * @param dataSourceType
77    * @param format
78    */
79   private void setFileFields(AlignmentFileReaderI source, File file,
80           String inFile, DataSourceType dataSourceType, FileFormatI format)
81   {
82     this.source = source;
83     this.file = inFile;
84     this.selectedFile = file;
85     this.protocol = dataSourceType;
86     this.format = format;
87   }
88
89   AlignViewport viewport;
90
91   AlignFrame alignFrame;
92
93   long loadtime;
94
95   long memused;
96
97   boolean raiseGUI = true;
98
99   /**
100    * default constructor always raised errors in GUI dialog boxes
101    */
102   public FileLoader()
103   {
104     this(true);
105   }
106
107   /**
108    * construct a Fileloader that may raise errors non-interactively
109    * 
110    * @param raiseGUI
111    *          true if errors are to be raised as GUI dialog boxes
112    */
113   public FileLoader(boolean raiseGUI)
114   {
115     this.raiseGUI = raiseGUI;
116   }
117
118   public void loadFile(AlignViewport viewport, Object file,
119           DataSourceType protocol, FileFormatI format)
120   {
121     this.viewport = viewport;
122     if (file instanceof File) {
123       this.selectedFile = (File) file;
124       file = selectedFile.getPath();
125     }
126     loadFile(file.toString(), protocol, format);
127   }
128
129   public void loadFile(String file, DataSourceType protocol,
130           FileFormatI format)
131   {
132     this.file = file;
133     this.protocol = protocol;
134     this.format = format;
135
136     final Thread loader = new Thread(this);
137
138     SwingUtilities.invokeLater(new Runnable()
139     {
140       @Override
141       public void run()
142       {
143         loader.start();
144       }
145     });
146   }
147
148   /**
149    * Load a (file, protocol) source of unknown type
150    * 
151    * @param file
152    * @param protocol
153    */
154   public void LoadFile(String file, DataSourceType protocol)
155   {
156     loadFile(file, protocol, null);
157   }
158
159   /**
160    * Load alignment from (file, protocol) and wait till loaded
161    * 
162    * @param file
163    * @param sourceType
164    * @return alignFrame constructed from file contents
165    */
166   public AlignFrame LoadFileWaitTillLoaded(String file,
167           DataSourceType sourceType)
168   {
169     return loadFileWaitTillLoaded(file, sourceType, null);
170   }
171
172   /**
173    * Load alignment from (file, protocol) of type format and wait till loaded
174    * 
175    * @param file
176    * @param sourceType
177    * @param format
178    * @return alignFrame constructed from file contents
179    */
180   public AlignFrame loadFileWaitTillLoaded(String file,
181           DataSourceType sourceType, FileFormatI format)
182   {
183     setFileFields(null, null, file, sourceType, format);
184     return _loadFileWaitTillLoaded();
185   }
186
187   /**
188    * Load alignment from (file, protocol) of type format and wait till loaded
189    * 
190    * @param file
191    * @param sourceType
192    * @param format
193    * @return alignFrame constructed from file contents
194    */
195   public AlignFrame loadFileWaitTillLoaded(File file,
196           DataSourceType sourceType, FileFormatI format)
197   {
198     setFileFields(null, file, null, sourceType, format);
199     return _loadFileWaitTillLoaded();
200   }
201
202   /**
203    * Load alignment from FileParse source of type format and wait till loaded
204    * 
205    * @param source
206    * @param format
207    * @return alignFrame constructed from file contents
208    */
209   public AlignFrame loadFileWaitTillLoaded(AlignmentFileReaderI source,
210           FileFormatI format)
211   {
212     setFileFields(source, null, source.getInFile(),
213             source.getDataSourceType(), format);
214     return _loadFileWaitTillLoaded();
215   }
216
217   /**
218    * runs the 'run' method (in this thread), then return the alignFrame that's
219    * (hopefully) been read
220    * 
221    * @return
222    */
223   private AlignFrame _loadFileWaitTillLoaded()
224   {
225     this.run();
226     return alignFrame;
227   }
228
229   public void updateRecentlyOpened()
230   {
231     Vector<String> recent = new Vector<>();
232     if (protocol == DataSourceType.PASTE)
233     {
234       // do nothing if the file was pasted in as text... there is no filename to
235       // refer to it as.
236       return;
237     }
238     if (file != null
239             && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
240     {
241       // ignore files loaded from the system's temporary directory
242       return;
243     }
244     String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
245             : "RECENT_URL";
246
247     String historyItems = Cache.getProperty(type);
248
249     StringTokenizer st;
250
251     if (historyItems != null)
252     {
253       st = new StringTokenizer(historyItems, "\t");
254
255       while (st.hasMoreTokens())
256       {
257         recent.addElement(st.nextToken().trim());
258       }
259     }
260
261     if (recent.contains(file))
262     {
263       recent.remove(file);
264     }
265
266     StringBuffer newHistory = new StringBuffer(file);
267     for (int i = 0; i < recent.size() && i < 10; i++)
268     {
269       newHistory.append("\t");
270       newHistory.append(recent.elementAt(i));
271     }
272
273     Cache.setProperty(type, newHistory.toString());
274
275     if (protocol == DataSourceType.FILE)
276     {
277       Cache.setProperty("DEFAULT_FILE_FORMAT", 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 }