b41073c340fec150aaee9434e7203f55298b9d9e
[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.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.util.Platform;
43 import jalview.ws.utils.UrlDownloadClient;
44
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
285
286     String title = protocol == DataSourceType.PASTE
287             ? "Copied From Clipboard"
288             : file;
289     Runtime rt = Runtime.getRuntime();
290     try
291     {
292       if (Desktop.getInstance() != null)
293       {
294         Desktop.getInstance().startLoading(file);
295       }
296       if (format == null)
297       {
298         // just in case the caller didn't identify the file for us
299         if (source != null)
300         {
301           format = new IdentifyFile().identify(source, false);
302           // identify stream and rewind rather than close
303         }
304         else if (selectedFile != null)
305         {
306           format = new IdentifyFile().identify(selectedFile, protocol);
307         }
308         else
309         {
310           format = new IdentifyFile().identify(file, protocol);
311         }
312
313       }
314
315       if (format == null)
316       {
317         Desktop.getInstance().stopLoading();
318         System.err.println("The input file \"" + file
319                 + "\" has null or unidentifiable data content!");
320         if (!Jalview.isHeadlessMode())
321         {
322           JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
323                   MessageManager.getString("label.couldnt_read_data")
324                           + " in " + file + "\n"
325                           + AppletFormatAdapter.getSupportedFormats(),
326                   MessageManager.getString("label.couldnt_read_data"),
327                   JvOptionPane.WARNING_MESSAGE);
328         }
329         return;
330       }
331
332       // TODO: cache any stream datasources as a temporary file (eg. PDBs
333       // retrieved via URL)
334       if (Desktop.getDesktopPane() != null
335               && Desktop.getDesktopPane().isShowMemoryUsage())
336       {
337         System.gc();
338         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
339         // memory
340         // before
341         // load
342       }
343       loadtime = -System.currentTimeMillis();
344       AlignmentI al = null;
345
346       if (FileFormat.Jalview.equals(format))
347       {
348         if (source != null)
349         {
350           // Tell the user (developer?) that this is going to cause a problem
351           System.err.println(
352                   "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
353           // We read the data anyway - it might make sense.
354         }
355         // BH 2018 switch to File object here instead of filename
356         Platform.timeCheck(null, Platform.TIME_MARK);
357         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
358                 selectedFile == null ? file : selectedFile);
359         Platform.timeCheck("JVP loaded", Platform.TIME_MARK);
360
361       }
362       else
363       {
364         String error = AppletFormatAdapter.getSupportedFormats();
365         try
366         {
367           if (source != null)
368           {
369             // read from the provided source
370             al = new FormatAdapter().readFromFile(source, format);
371           }
372           else
373           {
374
375             // open a new source and read from it
376             FormatAdapter fa = new FormatAdapter();
377             boolean downloadStructureFile = format.isStructureFile()
378                     && protocol.equals(DataSourceType.URL);
379             if (downloadStructureFile)
380             {
381               String structExt = format.getExtensions().split(",")[0];
382               int pt = file.lastIndexOf(file.indexOf('/') >= 0 ? "/"
383                       : System.getProperty("file.separator"));
384               String urlLeafName = file.substring(pt,
385                       file.lastIndexOf("."));
386               String tempStructureFileStr = createNamedJvTempFile(
387                       urlLeafName, structExt);
388
389               // BH - switching to File object here so as to hold
390               // .秘bytes array directly
391               File tempFile = new File(tempStructureFileStr);
392               UrlDownloadClient.download(file, tempFile);
393
394               al = fa.readFile(tempFile, DataSourceType.FILE, format);
395               source = fa.getAlignFile();
396             }
397             else
398             {
399               if (selectedFile == null)
400               {
401                 al = fa.readFile(file, protocol, format);
402
403               }
404               else
405               {
406                 al = fa.readFile(selectedFile, protocol, format);
407               }
408               source = fa.getAlignFile(); // keep reference for later if
409
410               // necessary.
411             }
412           }
413         } catch (java.io.IOException ex)
414         {
415           error = ex.getMessage();
416         }
417
418         System.out.println("OK1");
419
420
421         if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
422         {
423
424
425           // construct and register dataset sequences
426
427           StructureSelectionManager ssm = StructureSelectionManager
428                   .getStructureSelectionManager(Desktop.getInstance());
429           for (SequenceI sq : al.getSequences())
430           {
431             while (sq.getDatasetSequence() != null)
432             {
433               sq = sq.getDatasetSequence();
434             }
435             if (sq.getAllPDBEntries() != null)
436             {
437               for (PDBEntry pdbe : sq.getAllPDBEntries())
438               {
439                 // register PDB entries with desktop's structure selection
440                 // manager
441                 ssm.registerPDBEntry(pdbe);
442               }
443             }
444           }
445
446           FeatureSettingsModelI proxyColourScheme = source
447                   .getFeatureColourScheme();
448
449           if (viewport != null)
450           {
451
452             if (proxyColourScheme != null)
453             {
454               viewport.applyFeaturesStyle(proxyColourScheme);
455             }
456             // append to existing alignment
457             viewport.addAlignment(al, title);
458           }
459           else
460           {
461
462             System.out.println("OK9");
463             // otherwise construct the alignFrame
464
465             if (source instanceof ComplexAlignFile)
466             {
467               HiddenColumns colSel = ((ComplexAlignFile) source)
468                       .getHiddenColumns();
469               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
470                       .getHiddenSequences();
471               String colourSchemeName = ((ComplexAlignFile) source)
472                       .getGlobalColourScheme();
473               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
474                       .getDisplayedFeatures();
475
476               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
477                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
478
479               alignFrame.getViewport().setFeaturesDisplayed(fd);
480               alignFrame.getViewport().setShowSequenceFeatures(
481                       ((ComplexAlignFile) source).isShowSeqFeatures());
482               ColourSchemeI cs = ColourSchemeMapper
483                       .getJalviewColourScheme(colourSchemeName, al);
484               if (cs != null)
485               {
486                 alignFrame.changeColour(cs);
487               }
488             }
489             else
490             {
491
492               // Headless start fails here in Windows
493
494               // Sorry, no JInternalFrame when headless, at least in Windows.
495               // Not clear why that would be, since an InternalFrame is not a
496               // top-level component. But maybe it is
497
498               System.out.println("FileLoader test1");
499
500               try
501               {
502                 //
503                 alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
504                         AlignFrame.DEFAULT_HEIGHT);
505
506                 System.out.println("FileLoader test2");
507
508               } catch (Throwable t)
509               {
510                 System.out.println(t);
511                 t.printStackTrace();
512               }
513
514               if (source instanceof FeaturesSourceI)
515               {
516
517                 System.out.println("FileLoader test3");
518
519                 alignFrame.getViewport().setShowSequenceFeatures(true);
520               }
521             }
522             // add metadata and update ui
523
524             System.out.println("FileLoader test4");
525
526             if (!(protocol == DataSourceType.PASTE))
527             {
528
529               System.out.println("FileLoader test5");
530               alignFrame.setFileName(file, format);
531               alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
532             }
533
534             System.out.println("FileLoader test6");
535
536             if (proxyColourScheme != null)
537             {
538               alignFrame.getViewport()
539                       .applyFeaturesStyle(proxyColourScheme);
540             }
541
542             System.out.println("FileLoader test7");
543
544             alignFrame.setStatus(MessageManager.formatMessage(
545                     "label.successfully_loaded_file", new String[]
546                     { title }));
547
548             System.out.println("FileLoader test8" + raiseGUI);
549             if (raiseGUI)
550             {
551               // add the window to the GUI
552               // note - this actually should happen regardless of raiseGUI
553               // status in Jalview 3
554               // TODO: define 'virtual desktop' for benefit of headless scripts
555               // that perform queries to find the 'current working alignment'
556               Desktop.addInternalFrame(alignFrame, title,
557                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
558             }
559
560             try
561             {
562               alignFrame.setMaximum(jalview.bin.Cache
563                       .getDefault("SHOW_FULLSCREEN", false));
564             } catch (java.beans.PropertyVetoException ex)
565             {
566             }
567           }
568         }
569         else
570         {
571
572           System.out.println("OK10");
573
574           if (Desktop.getInstance() != null)
575           {
576             Desktop.getInstance().stopLoading();
577           }
578
579           final String errorMessage = MessageManager.getString(
580                   "label.couldnt_load_file") + " " + title + "\n" + error;
581           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
582           // bits ?
583           if (raiseGUI)
584           {
585             javax.swing.SwingUtilities.invokeLater(new Runnable()
586             {
587               @Override
588               public void run()
589               {
590                 JvOptionPane.showInternalMessageDialog(
591                         Desktop.getDesktopPane(), errorMessage,
592                         MessageManager
593                                 .getString("label.error_loading_file"),
594                         JvOptionPane.WARNING_MESSAGE);
595               }
596             });
597           }
598           else
599           {
600             System.err.println(errorMessage);
601           }
602         }
603       }
604
605
606       updateRecentlyOpened();
607
608     } catch (Exception er)
609     {
610       System.err.println("Exception whilst opening file '" + file);
611       er.printStackTrace();
612       if (raiseGUI)
613       {
614         javax.swing.SwingUtilities.invokeLater(new Runnable()
615         {
616           @Override
617           public void run()
618           {
619             JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
620                     MessageManager.formatMessage(
621                             "label.problems_opening_file", new String[]
622                             { file }),
623                     MessageManager.getString("label.file_open_error"),
624                     JvOptionPane.WARNING_MESSAGE);
625           }
626         });
627       }
628       alignFrame = null;
629     } catch (OutOfMemoryError er)
630     {
631
632       er.printStackTrace();
633       alignFrame = null;
634       if (raiseGUI)
635       {
636         javax.swing.SwingUtilities.invokeLater(new Runnable()
637         {
638           @Override
639           public void run()
640           {
641             JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
642                     MessageManager.formatMessage(
643                             "warn.out_of_memory_loading_file", new String[]
644                             { file }),
645                     MessageManager.getString("label.out_of_memory"),
646                     JvOptionPane.WARNING_MESSAGE);
647           }
648         });
649       }
650       System.err.println("Out of memory loading file " + file + "!!");
651
652     }
653     loadtime += System.currentTimeMillis();
654
655     // TODO: Estimate percentage of memory used by a newly loaded alignment -
656     // warn if more memory will be needed to work with it
657     // System.gc();
658     memused = memused
659             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
660     // in free
661     // memory
662     // after
663     // load
664     if (Desktop.getDesktopPane() != null
665             && Desktop.getDesktopPane().isShowMemoryUsage())
666     {
667       if (alignFrame != null)
668       {
669         AlignmentI al = alignFrame.getViewport().getAlignment();
670
671         System.out.println("Loaded '" + title + "' in "
672                 + (loadtime / 1000.0) + "s, took an additional "
673                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
674                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
675       }
676       else
677       {
678         // report that we didn't load anything probably due to an out of memory
679         // error
680         System.out.println("Failed to load '" + title + "' in "
681                 + (loadtime / 1000.0) + "s, took an additional "
682                 + (1.0 * memused / (1024.0 * 1024.0))
683                 + " MB (alignment is null)");
684       }
685     }
686     // remove the visual delay indicator
687     if (Desktop.getInstance() != null)
688     {
689       Desktop.getInstance().stopLoading();
690     }
691
692   }
693
694   /**
695    * This method creates the file -
696    * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
697    * file name and extension
698    * 
699    * @param fileName
700    *          the name of the temp file to be created
701    * @param extension
702    *          the extension of the temp file to be created
703    * @return
704    */
705   private static String createNamedJvTempFile(String fileName,
706           String extension) throws IOException
707   {
708     String seprator = System.getProperty("file.separator");
709     String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
710             + seprator + System.currentTimeMillis();
711     File tempStructFile = new File(
712             jvTempDir + seprator + fileName + "." + extension);
713     tempStructFile.mkdirs();
714     return tempStructFile.toString();
715   }
716
717   /**
718    * 
719    * @param file a File, or a String which is a name of a file
720    * @return
721    * @throws FileNotFoundException 
722    */
723   public static BufferedReader getBufferedReader(Object file) throws FileNotFoundException {
724     if (file instanceof String)
725     {
726       return new BufferedReader(new FileReader((String) file));
727     }
728     byte[] bytes = Platform.getFileBytes((File) file);
729     if (bytes != null)
730     {
731       return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
732     }
733     return  new BufferedReader(new FileReader((File) file));
734   }
735
736 }