JAL-674 friendly name for PDB file included in secondary structure tooltip
[jalview.git] / src / jalview / ext / jmol / PDBFileWithJmol.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.ext.jmol;
22
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceI;
28 import jalview.io.AlignFile;
29 import jalview.io.FileParse;
30 import jalview.schemes.ResidueProperties;
31 import jalview.util.MessageManager;
32
33 import java.io.IOException;
34 import java.util.Hashtable;
35 import java.util.Map;
36
37 import org.jmol.api.JmolStatusListener;
38 import org.jmol.api.JmolViewer;
39 import org.jmol.constant.EnumCallback;
40 import org.jmol.modelset.Group;
41 import org.jmol.modelset.Model;
42 import org.jmol.modelset.ModelSet;
43 import org.jmol.modelset.Polymer;
44 import org.jmol.modelsetbio.BioPolymer;
45 import org.jmol.viewer.Viewer;
46 import org.openscience.jmol.app.JmolApp;
47
48 /**
49  * Import and process PDB files with Jmol
50  * 
51  * @author jprocter
52  * 
53  */
54 public class PDBFileWithJmol extends AlignFile implements
55         JmolStatusListener
56 {
57
58   JmolApp jmolApp = null;
59
60   Viewer viewer = null;
61
62   public PDBFileWithJmol(String inFile, String type) throws IOException
63   {
64     super(inFile, type);
65   }
66
67   public PDBFileWithJmol(FileParse fp) throws IOException
68   {
69     super(fp);
70   }
71
72   public PDBFileWithJmol()
73   {
74     // TODO Auto-generated constructor stub
75   }
76
77   /**
78    * create a headless jmol instance for dataprocessing
79    * 
80    * @return
81    */
82   private Viewer getJmolData()
83   {
84     if (viewer == null)
85     { // note that -o -n -x are all implied
86       jmolApp = new JmolApp();
87       jmolApp.isDataOnly = true;
88       jmolApp.haveConsole = false;
89       jmolApp.haveDisplay = false;
90       jmolApp.exitUponCompletion = true;
91       try
92       {
93         viewer = (Viewer) JmolViewer.allocateViewer(null, null, null, null,
94                 null, jmolApp.commandOptions, this);
95         viewer.setScreenDimension(jmolApp.startupWidth,
96                 jmolApp.startupHeight);
97         jmolApp.startViewer(viewer, null);
98       } catch (ClassCastException x)
99       {
100         throw new Error(MessageManager.formatMessage("error.jmol_version_not_compatible_with_jalview_version", new String[]{JmolViewer.getJmolVersion()}),
101                 x);
102       }
103     }
104     return viewer;
105   }
106
107   private void waitForScript(Viewer jmd)
108   {
109     while (jmd.isScriptExecuting())
110     {
111       try
112       {
113         Thread.sleep(50);
114
115       } catch (InterruptedException x)
116       {
117       }
118     }
119   }
120
121   /*
122    * (non-Javadoc)
123    * 
124    * @see jalview.io.AlignFile#parse()
125    */
126   @Override
127   public void parse() throws IOException
128   {
129     Viewer jmd = getJmolData();
130     jmd.openReader(getDataName(), getDataName(), getReader());
131     waitForScript(jmd);
132     if (jmd.getModelCount() > 0)
133     {
134       ModelSet ms = jmd.getModelSet();
135       String structs = ms.calculateStructures(null, true, false, true);
136       // System.out.println("Structs\n"+structs);
137       for (Model model : ms.getModels())
138       {
139         for (int _bp = 0, _bpc = model.getBioPolymerCount(); _bp < _bpc; _bp++)
140         {
141           Polymer bp = model.getBioPolymer(_bp);
142           if (bp instanceof BioPolymer)
143           {
144             BioPolymer biopoly = (BioPolymer) bp;
145             char _lastChainId = 0;
146             int[] groups = biopoly.getLeadAtomIndices();
147             Group[] bpgrp = biopoly.getGroups();
148             char seq[] = new char[groups.length], secstr[] = new char[groups.length], secstrcode[] = new char[groups.length];
149             int groupc = 0, len = 0, firstrnum = 1, lastrnum = 0;
150             do
151             {
152               if (groupc >= groups.length
153                       || ms.atoms[groups[groupc]].getChainID() != _lastChainId)
154               {
155                 if (len > 0)
156                 {
157                   boolean isNa = (biopoly.isDna() || biopoly.isRna());
158                   // normalise sequence from Jmol to jalview 
159                   int[] cinds = isNa ? ResidueProperties.nucleotideIndex : ResidueProperties.aaIndex;
160                   int nonGap = isNa ? ResidueProperties.maxNucleotideIndex
161                           : ResidueProperties.maxProteinIndex;
162                   char ngc = 'X';
163                   char newseq[] = new char[len];
164                   Annotation asecstr[] = new Annotation[len+firstrnum-1];
165                   for (int p = 0; p < len; p++)
166                   {
167                     newseq[p] = cinds[seq[p]] == nonGap ? ngc : seq[p];
168                     if (secstr[p] >= 'A' && secstr[p] <= 'z')
169                     {
170                       asecstr[p] = new Annotation("" + secstr[p], null,
171                               secstrcode[p], Float.NaN);
172                     }
173                   }
174                   SequenceI sq = new Sequence("" + getDataName() + "|"
175                           + model.getModelTitle() + "|" + _lastChainId,
176                           newseq, firstrnum, lastrnum);
177                   PDBEntry pdbe = new PDBEntry();
178                   pdbe.setFile(getDataName());
179                   pdbe.setId(getDataName());
180                   sq.addPDBId(pdbe);
181                   pdbe.setProperty(new Hashtable());
182                   pdbe.getProperty().put("CHAIN", "" + _lastChainId);
183                   // JAL-1533
184                   // Need to put the number of models for this polymer somewhere for Chimera/others to grab
185                   //                  pdbe.getProperty().put("PDBMODELS", biopoly.)
186                   seqs.add(sq);
187                   if (!isNa)
188                   {
189                     String mt = model.getModelTitle() == null ? getDataName()
190                             : model.getModelTitle();
191                     mt += _lastChainId;
192                     AlignmentAnnotation ann = new AlignmentAnnotation(
193                             "Secondary Structure",
194                             "Secondary Structure for " + mt, asecstr);
195                     ann.belowAlignment=true;
196                     ann.visible=true;
197                     ann.autoCalculated=false;
198                     ann.setCalcId(getClass().getName());
199                     sq.addAlignmentAnnotation(ann);
200                     ann.adjustForAlignment();
201                     ann.validateRangeAndDisplay();
202                     annotations.add(ann);
203                   }
204                 }
205                 len = 0;
206                 firstrnum = 1;
207                 lastrnum = 0;
208               }
209               if (groupc < groups.length)
210               {
211                 if (len == 0)
212                 {
213                   firstrnum = bpgrp[groupc].getResno();
214                   _lastChainId = bpgrp[groupc].getChainID();
215                 }
216                 else
217                 {
218                   lastrnum = bpgrp[groupc].getResno();
219                 }
220                 seq[len] = bpgrp[groupc].getGroup1();
221                 switch (bpgrp[groupc].getProteinStructureSubType())
222                 {
223                 case HELIX_310:
224                   if (secstr[len] == 0)
225                   {
226                     secstr[len] = '3';
227                   }
228                 case HELIX_ALPHA:
229                   if (secstr[len] == 0)
230                   {
231                     secstr[len] = 'H';
232                   }
233                 case HELIX_PI:
234                   if (secstr[len] == 0)
235                   {
236                     secstr[len] = 'P';
237                   }
238                 case HELIX:
239                   if (secstr[len] == 0)
240                   {
241                     secstr[len] = 'H';
242                   }
243                   secstrcode[len] = 'H';
244                   break;
245                 case SHEET:
246                   secstr[len] = 'E';
247                   secstrcode[len] = 'E';
248                   break;
249                 default:
250                   secstr[len] = 0;
251                   secstrcode[len] = 0;
252                 }
253                 len++;
254               }
255             } while (groupc++ < groups.length);
256
257           }
258         }
259       }
260
261       /*
262        * lastScriptTermination = -9465; String dsspOut =
263        * jmd.evalString("calculate STRUCTURE"); if (dsspOut.equals("pending")) {
264        * while (lastScriptTermination == -9465) { try { Thread.sleep(50); }
265        * catch (Exception x) { } ; } } System.out.println(lastConsoleEcho);
266        */
267     }
268   }
269
270   /*
271    * (non-Javadoc)
272    * 
273    * @see jalview.io.AlignFile#print()
274    */
275   @Override
276   public String print()
277   {
278     // TODO Auto-generated method stub
279     return null;
280   }
281
282   @Override
283   public void setCallbackFunction(String callbackType,
284           String callbackFunction)
285   {
286     // TODO Auto-generated method stub
287
288   }
289
290   /*
291    * @Override public void notifyCallback(EnumCallback type, Object[] data) {
292    * try { switch (type) { case ERROR: case SCRIPT:
293    * notifyScriptTermination((String) data[2], ((Integer) data[3]).intValue());
294    * break; case MESSAGE: sendConsoleMessage((data == null) ? ((String) null) :
295    * (String) data[1]); break; case LOADSTRUCT: notifyFileLoaded((String)
296    * data[1], (String) data[2], (String) data[3], (String) data[4], ((Integer)
297    * data[5]).intValue());
298    * 
299    * break; default: // System.err.println("Unhandled callback " + type + " " //
300    * + data[1].toString()); break; } } catch (Exception e) {
301    * System.err.println("Squashed Jmol callback handler error:");
302    * e.printStackTrace(); } }
303    */
304   public void notifyCallback(EnumCallback type, Object[] data)
305   {
306     String strInfo = (data == null || data[1] == null ? null : data[1]
307             .toString());
308     switch (type)
309     {
310     case ECHO:
311       sendConsoleEcho(strInfo);
312       break;
313     case SCRIPT:
314       notifyScriptTermination((String) data[2],
315               ((Integer) data[3]).intValue());
316       break;
317     case MEASURE:
318       String mystatus = (String) data[3];
319       if (mystatus.indexOf("Picked") >= 0
320               || mystatus.indexOf("Sequence") >= 0)
321       {
322         // Picking mode
323         sendConsoleMessage(strInfo);
324       }
325       else if (mystatus.indexOf("Completed") >= 0)
326       {
327         sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
328                 strInfo.length() - 1));
329       }
330       break;
331     case MESSAGE:
332       sendConsoleMessage(data == null ? null : strInfo);
333       break;
334     case PICK:
335       sendConsoleMessage(strInfo);
336       break;
337     default:
338       break;
339     }
340   }
341
342   private void notifyFileLoaded(String string, String string2,
343           String string3, String string4, int intValue)
344   {
345     // TODO Auto-generated method stub
346
347   }
348
349   String lastConsoleEcho = "";
350
351   private void sendConsoleEcho(String string)
352   {
353     lastConsoleEcho += string;
354     lastConsoleEcho += "\n";
355   }
356
357   String lastConsoleMessage = "";
358
359   private void sendConsoleMessage(String string)
360   {
361     lastConsoleMessage += string;
362     lastConsoleMessage += "\n";
363   }
364
365   int lastScriptTermination = -1;
366
367   String lastScriptMessage = "";
368
369   private void notifyScriptTermination(String string, int intValue)
370   {
371     lastScriptMessage += string;
372     lastScriptMessage += "\n";
373     lastScriptTermination = intValue;
374   }
375
376   @Override
377   public boolean notifyEnabled(EnumCallback callbackPick)
378   {
379     switch (callbackPick)
380     {
381     case MESSAGE:
382     case SCRIPT:
383     case ECHO:
384     case LOADSTRUCT:
385     case ERROR:
386       return true;
387     case MEASURE:
388     case PICK:
389     case HOVER:
390     case RESIZE:
391     case SYNC:
392     case CLICK:
393     case ANIMFRAME:
394     case MINIMIZATION:
395     }
396     return false;
397   }
398
399   @Override
400   public String eval(String strEval)
401   {
402     // TODO Auto-generated method stub
403     return null;
404   }
405
406   @Override
407   public float[][] functionXY(String functionName, int x, int y)
408   {
409     // TODO Auto-generated method stub
410     return null;
411   }
412
413   @Override
414   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
415   {
416     // TODO Auto-generated method stub
417     return null;
418   }
419
420   @Override
421   public String createImage(String fileName, String type,
422           Object text_or_bytes, int quality)
423   {
424     // TODO Auto-generated method stub
425     return null;
426   }
427
428   @Override
429   public Map<String, Object> getRegistryInfo()
430   {
431     // TODO Auto-generated method stub
432     return null;
433   }
434
435   @Override
436   public void showUrl(String url)
437   {
438     // TODO Auto-generated method stub
439
440   }
441
442   @Override
443   public void resizeInnerPanel(String data)
444   {
445     // TODO Auto-generated method stub
446
447   }
448
449 }