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