JAL-3922 convert selection events in Jmol to highlights in Jalview - still need to...
[jalview.git] / src / jalview / gui / AppJmolBinding.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.gui;
22
23 import java.awt.Container;
24 import java.io.File;
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.swing.JComponent;
30 import javax.swing.SwingUtilities;
31
32 import org.jmol.api.AtomIndexIterator;
33 import org.jmol.api.JmolAppConsoleInterface;
34 import org.jmol.modelset.Atom;
35 import org.jmol.modelset.Model;
36 import org.openscience.jmol.app.jmolpanel.console.AppConsole;
37
38 import jalview.api.AlignmentViewPanel;
39 import jalview.api.structures.JalviewStructureDisplayI;
40 import jalview.bin.Cache;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.SequenceI;
44 import jalview.ext.jmol.JalviewJmolBinding;
45 import jalview.io.DataSourceType;
46 import jalview.structure.AtomSpec;
47 import jalview.structure.StructureSelectionManager;
48 import jalview.util.MessageManager;
49 import jalview.util.Platform;
50 import jalview.ws.dbsources.EBIAlfaFold;
51 import jalview.ws.dbsources.Pdb;
52 import jalview.ws.utils.UrlDownloadClient;
53 import javajs.util.BS;
54
55 public class AppJmolBinding extends JalviewJmolBinding
56 {
57   public AppJmolBinding(AppJmol appJmol, StructureSelectionManager sSm,
58           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
59           DataSourceType protocol)
60   {
61     super(sSm, pdbentry, sequenceIs, protocol);
62     setViewer(appJmol);
63   }
64
65   @Override
66   public SequenceRenderer getSequenceRenderer(AlignmentViewPanel alignment)
67   {
68     return new SequenceRenderer(((AlignmentPanel) alignment).av);
69   }
70
71   @Override
72   public void sendConsoleEcho(String strEcho)
73   {
74     if (console != null)
75     {
76       console.sendConsoleEcho(strEcho);
77     }
78   }
79
80   @Override
81   public void sendConsoleMessage(String strStatus)
82   {
83     if (console != null && strStatus != null)
84     // && !strStatus.equals("Script completed"))
85     // should we squash the script completed string ?
86     {
87       console.sendConsoleMessage(strStatus);
88     }
89   }
90
91   @Override
92   public void showUrl(String url, String target)
93   {
94     try
95     {
96       jalview.util.BrowserLauncher.openURL(url);
97     } catch (Exception e)
98     {
99       Cache.log.error("Failed to launch Jmol-associated url " + url, e);
100       // TODO: 2.6 : warn user if browser was not configured.
101     }
102   }
103
104   @Override
105   public void refreshGUI()
106   {
107     if (getMappedStructureCount() == 0)
108     {
109       // too soon!
110       return;
111     }
112     // appJmolWindow.repaint();
113     javax.swing.SwingUtilities.invokeLater(new Runnable()
114     {
115       @Override
116       public void run()
117       {
118         JalviewStructureDisplayI theViewer = getViewer();
119         // invokes colourbySequence() via seqColour_ActionPerformed()
120         theViewer.updateTitleAndMenus();
121         ((JComponent) theViewer).revalidate();
122       }
123     });
124   }
125
126   @Override
127   public void notifyScriptTermination(String strStatus, int msWalltime)
128   {
129     // todo - script termination doesn't happen ?
130     // if (console != null)
131     // console.notifyScriptTermination(strStatus,
132     // msWalltime);
133   }
134
135   @Override
136   public void showUrl(String url)
137   {
138     showUrl(url, "jmol");
139   }
140
141   public void newJmolPopup(String menuName)
142   {
143     // jmolpopup = new JmolAwtPopup();
144     // jmolpopup.jpiInitialize((viewer), menuName);
145   }
146
147   @Override
148   public void selectionChanged(BS arg0)
149   {
150     SwingUtilities.invokeLater(new Runnable() {
151       public void run() {
152       }
153     });
154   }
155   
156   @Override
157   public void showConsole(boolean b)
158   {
159     getViewer().showConsole(b);
160   }
161
162   @Override
163   protected JmolAppConsoleInterface createJmolConsole(
164           Container consolePanel, String buttonsToShow)
165   {
166     jmolViewer.setJmolCallbackListener(this);
167     // BH comment: can't do this yet [for JS only, or generally?]
168     return Platform.isJS() ? null
169             : new AppConsole(jmolViewer, consolePanel, buttonsToShow);
170   }
171
172   @Override
173   protected void releaseUIResources()
174   {
175     setViewer(null);
176     closeConsole();
177   }
178
179   @Override
180   public void releaseReferences(Object svl)
181   {
182     if (svl instanceof SeqPanel)
183     {
184       getViewer().removeAlignmentPanel(((SeqPanel) svl).ap);
185     }
186   }
187
188   @Override
189   public Map<String, Object> getJSpecViewProperty(String arg0)
190   {
191     // TODO Auto-generated method stub
192     return null;
193   }
194
195   @SuppressWarnings("unused")
196   public void cacheFiles(List<File> files)
197   {
198     if (files == null)
199     {
200       return;
201     }
202     for (File f : files)
203     {
204       Platform.cacheFileData(f);
205     }
206   }
207
208   /**
209    * Retrieves and saves as file any modelled PDB entries for which we do not
210    * already have a file saved. Returns a list of absolute paths to structure
211    * files which were either retrieved, or already stored but not modelled in
212    * the structure viewer (i.e. files to add to the viewer display).
213    * 
214    * Currently only used by Jmol - similar but different code used for Chimera/X
215    * and Pymol so still need to refactor
216    * 
217    * @param structureViewer
218    *          UI proxy for the structure viewer
219    * @return list of absolute paths to structures retrieved that need to be
220    *         added to the display
221    */
222   public List<String> fetchPdbFiles(StructureViewerBase structureViewer)
223   {
224     // todo - record which pdbids were successfully imported.
225     StringBuilder errormsgs = new StringBuilder();
226   
227     List<String> files = new ArrayList<>();
228     String pdbid = "";
229     try
230     {
231       String[] filesInViewer = getStructureFiles();
232       // TODO: replace with reference fetching/transfer code (validate PDBentry
233       // as a DBRef?)
234       
235       for (int pi = 0; pi < getPdbCount(); pi++)
236       {
237         PDBEntry strucEntry = getPdbEntry(pi);
238
239         String file = strucEntry.getFile();
240         if (file == null)
241         {
242           pdbid = strucEntry.getId();
243           try{ 
244             file = structureViewer.fetchPdbFile(strucEntry);
245           } catch (OutOfMemoryError oomerror)
246           {
247             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
248           } catch (Exception ex)
249           {
250             ex.printStackTrace();
251             errormsgs.append("'").append(pdbid).append("'");
252           }
253           if (file!=null)
254           {
255             // success
256             files.add(file);
257           }
258           else
259           {
260             errormsgs.append("'").append(pdbid).append("' ");
261           }
262         }
263         else
264         {
265           if (filesInViewer != null && filesInViewer.length > 0)
266           {
267             structureViewer.setAddingStructures(true); // already files loaded.
268             for (int c = 0; c < filesInViewer.length; c++)
269             {
270               if (Platform.pathEquals(filesInViewer[c], file))
271               {
272                 file = null;
273                 break;
274               }
275             }
276           }
277           if (file != null)
278           {
279             files.add(file);
280           }
281         }
282       }
283     } catch (OutOfMemoryError oomerror)
284     {
285       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
286     } catch (Exception ex)
287     {
288       ex.printStackTrace();
289       errormsgs.append("When retrieving pdbfiles : current was: '")
290               .append(pdbid).append("'");
291     }
292     if (errormsgs.length() > 0)
293     {
294       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
295               MessageManager.formatMessage(
296                       "label.pdb_entries_couldnt_be_retrieved", new String[]
297                       { errormsgs.toString() }),
298               MessageManager.getString("label.couldnt_load_file"),
299               JvOptionPane.ERROR_MESSAGE);
300     }
301     return files;
302   }
303
304 }