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