JAL-1528 bug fixes and adjustments to Chimera interface
[jalview.git] / src / jalview / ext / rbvi / chimera / JalviewChimeraBinding.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.rbvi.chimera;
22
23 import jalview.api.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
25 import jalview.api.SequenceRenderer;
26 import jalview.api.SequenceStructureBinding;
27 import jalview.api.StructureSelectionManagerProvider;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SequenceI;
32 import jalview.io.AppletFormatAdapter;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.StructureListener;
36 import jalview.structure.StructureMapping;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.structures.models.SequenceStructureBindingModel;
39 import jalview.util.MessageManager;
40
41 import java.awt.Color;
42 import java.awt.event.ComponentEvent;
43 import java.io.File;
44 import java.util.ArrayList;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.LinkedHashMap;
48 import java.util.List;
49 import java.util.Map;
50
51 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
52 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
53 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
54 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
55
56 public abstract class JalviewChimeraBinding extends
57         SequenceStructureBindingModel implements StructureListener,
58         SequenceStructureBinding, StructureSelectionManagerProvider
59
60 {
61   private static final String PHOSPHORUS = "P";
62
63   private static final String ALPHACARBON = "CA";
64
65   private StructureManager csm;
66
67   private ChimeraManager viewer;
68
69   /**
70    * set if chimera state is being restored from some source - instructs binding
71    * not to apply default display style when structure set is updated for first
72    * time.
73    */
74   private boolean loadingFromArchive = false;
75
76   /**
77    * second flag to indicate if the jmol viewer should ignore sequence colouring
78    * events from the structure manager because the GUI is still setting up
79    */
80   private boolean loadingFinished = true;
81
82   /**
83    * state flag used to check if the Jmol viewer's paint method can be called
84    */
85   private boolean finishedInit = false;
86
87   public boolean isFinishedInit()
88   {
89     return finishedInit;
90   }
91
92   public void setFinishedInit(boolean finishedInit)
93   {
94     this.finishedInit = finishedInit;
95   }
96
97   boolean allChainsSelected = false;
98
99   /**
100    * when true, try to search the associated datamodel for sequences that are
101    * associated with any unknown structures in the Chimera view.
102    */
103   private boolean associateNewStructs = false;
104
105   List<String> atomsPicked = new ArrayList<String>();
106
107   public List<String> chainNames;
108
109   private Map<String, String> chainFile;
110
111   /**
112    * array of target chains for sequences - tied to pdbentry and sequence[]
113    */
114   protected String[][] chains;
115
116   boolean colourBySequence = true;
117
118   StringBuffer eval = new StringBuffer();
119
120   public String fileLoadingError;
121
122   private Map<String, List<ChimeraModel>> chimmaps = new LinkedHashMap<String, List<ChimeraModel>>();
123
124   private List<String> mdlToFile = new ArrayList<String>();
125
126   /**
127    * the default or current model displayed if the model cannot be identified
128    * from the selection message
129    */
130   int frameNo = 0;
131
132   String lastCommand;
133
134   String lastMessage;
135
136   boolean loadedInline;
137
138   public boolean openFile(PDBEntry pe)
139   {
140     String file = pe.getFile();
141     try
142     {
143       List<ChimeraModel> oldList = viewer.getModelList();
144       viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
145       List<ChimeraModel> newList = viewer.getModelList();
146       if (oldList.size() < newList.size())
147       {
148         while (oldList.size() > 0)
149         {
150           oldList.remove(0);
151           newList.remove(0);
152         }
153         chimmaps.put(file, newList);
154         for (ChimeraModel cm : newList)
155         {
156           while (mdlToFile.size() < 1 + cm.getModelNumber())
157           {
158             mdlToFile.add(new String(""));
159           }
160           mdlToFile.set(cm.getModelNumber(), file);
161         }
162
163         File fl = new File(file);
164         String protocol = AppletFormatAdapter.URL;
165         try
166         {
167           if (fl.exists())
168           {
169             protocol = AppletFormatAdapter.FILE;
170           }
171         } catch (Exception e)
172         {
173         } catch (Error e)
174         {
175         }
176         // Explicitly map to the filename used by Jmol ;
177         // pdbentry[pe].getFile(), protocol);
178
179         if (ssm != null)
180         {
181           ssm.addStructureViewerListener(this);
182           // ssm.addSelectionListener(this);
183           FeatureRenderer fr = getFeatureRenderer(null);
184           if (fr != null)
185           {
186             fr.featuresAdded();
187           }
188           refreshGUI();
189         }
190         return true;
191       }
192     } catch (Exception q)
193     {
194       log("Exception when trying to open model " + file + "\n"
195               + q.toString());
196       q.printStackTrace();
197     }
198     return false;
199   }
200
201   /**
202    * current set of model filenames loaded
203    */
204   String[] modelFileNames = null;
205
206   public PDBEntry[] pdbentry;
207
208   /**
209    * datasource protocol for access to PDBEntrylatest
210    */
211   String protocol = null;
212
213   StringBuffer resetLastRes = new StringBuffer();
214
215   /**
216    * sequences mapped to each pdbentry
217    */
218   public SequenceI[][] sequence;
219
220   public StructureSelectionManager ssm;
221
222   private List<String> lastReply;
223
224   public JalviewChimeraBinding(StructureSelectionManager ssm,
225           PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
226           String protocol)
227   {
228     this.ssm = ssm;
229     this.sequence = sequenceIs;
230     this.chains = chains;
231     this.pdbentry = pdbentry;
232     this.protocol = protocol;
233     if (chains == null)
234     {
235       this.chains = new String[pdbentry.length][];
236     }
237     viewer = new ChimeraManager(
238             csm = new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
239     /*
240      * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(),
241      * "jalviewJmol", ap.av.applet .getDocumentBase(),
242      * ap.av.applet.getCodeBase(), "", this);
243      * 
244      * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true);
245      */
246   }
247
248   public JalviewChimeraBinding(StructureSelectionManager ssm,
249           ChimeraManager viewer2)
250   {
251     this.ssm = ssm;
252     viewer = viewer2;
253     csm = viewer.getStructureManager();
254   }
255
256   /**
257    * construct a title string for the viewer window based on the data jalview
258    * knows about
259    * 
260    * @return
261    */
262   public String getViewerTitle()
263   {
264     if (sequence == null || pdbentry == null || sequence.length < 1
265             || pdbentry.length < 1 || sequence[0].length < 1)
266     {
267       return ("Jalview Chimera Window");
268     }
269     // TODO: give a more informative title when multiple structures are
270     // displayed.
271     StringBuffer title = new StringBuffer("Chimera view for "
272             + sequence[0][0].getName() + ":" + pdbentry[0].getId());
273
274     if (pdbentry[0].getProperty() != null)
275     {
276       if (pdbentry[0].getProperty().get("method") != null)
277       {
278         title.append(" Method: ");
279         title.append(pdbentry[0].getProperty().get("method"));
280       }
281       if (pdbentry[0].getProperty().get("chains") != null)
282       {
283         title.append(" Chain:");
284         title.append(pdbentry[0].getProperty().get("chains"));
285       }
286     }
287     return title.toString();
288   }
289
290   /**
291    * prepare the view for a given set of models/chains. chainList contains
292    * strings of the form 'pdbfilename:Chaincode'
293    * 
294    * @param toshow
295    *          list of chains to make visible
296    */
297   public void centerViewer(List<String> toshow)
298   {
299     StringBuilder cmd = new StringBuilder(64);
300     int mlength, p;
301     for (String lbl : toshow)
302     {
303       mlength = 0;
304       do
305       {
306         p = mlength;
307         mlength = lbl.indexOf(":", p);
308       } while (p < mlength && mlength < (lbl.length() - 2));
309       // TODO: lookup each pdb id and recover proper model number for it.
310       cmd.append("#" + getModelNum(chainFile.get(lbl)) + "."
311               + lbl.substring(mlength + 1) + " or ");
312     }
313     if (cmd.length() > 0)
314     {
315       cmd.setLength(cmd.length() - 4);
316     }
317     String cmdstring = cmd.toString();
318     evalStateCommand("~display #*; ~ribbon #*; ribbon " + cmdstring
319             + ";focus " + cmdstring, false);
320   }
321
322   public void closeViewer()
323   {
324     ssm.removeStructureViewerListener(this, this.getPdbFile());
325     // and shut down Chimera
326     viewer.exitChimera();
327     // viewer.evalStringQuiet("zap");
328     // viewer.setJmolStatusListener(null);
329     lastCommand = null;
330     viewer = null;
331     releaseUIResources();
332   }
333
334   /**
335    * called by JalviewJmolbinding after closeViewer is called - release any
336    * resources and references so they can be garbage collected.
337    */
338   protected abstract void releaseUIResources();
339
340   public void colourByChain()
341   {
342     colourBySequence = false;
343     // TODO: colour by chain should colour each chain distinctly across all
344     // visible models
345     // TODO: http://issues.jalview.org/browse/JAL-628
346     evalStateCommand("select *;color chain",false);
347   }
348
349   public void colourByCharge()
350   {
351     colourBySequence = false;
352     evalStateCommand("colour *;color white;select ASP,GLU;color red;"
353             + "select LYS,ARG;color blue;select CYS;color yellow", false);
354   }
355
356   /**
357    * superpose the structures associated with sequences in the alignment
358    * according to their corresponding positions.
359    */
360   public void superposeStructures(AlignmentI alignment)
361   {
362     superposeStructures(alignment, -1, null);
363   }
364
365   /**
366    * superpose the structures associated with sequences in the alignment
367    * according to their corresponding positions. ded)
368    * 
369    * @param refStructure
370    *          - select which pdb file to use as reference (default is -1 - the
371    *          first structure in the alignment)
372    */
373   public void superposeStructures(AlignmentI alignment, int refStructure)
374   {
375     superposeStructures(alignment, refStructure, null);
376   }
377
378   /**
379    * superpose the structures associated with sequences in the alignment
380    * according to their corresponding positions. ded)
381    * 
382    * @param refStructure
383    *          - select which pdb file to use as reference (default is -1 - the
384    *          first structure in the alignment)
385    * @param hiddenCols
386    *          TODO
387    */
388   public void superposeStructures(AlignmentI alignment, int refStructure,
389           ColumnSelection hiddenCols)
390   {
391     superposeStructures(new AlignmentI[]
392     { alignment }, new int[]
393     { refStructure }, new ColumnSelection[]
394     { hiddenCols });
395   }
396
397   public void superposeStructures(AlignmentI[] _alignment,
398           int[] _refStructure, ColumnSelection[] _hiddenCols)
399   {
400     assert (_alignment.length == _refStructure.length && _alignment.length != _hiddenCols.length);
401     StringBuilder allComs = new StringBuilder(128); // Chimera superposition cmd
402     String[] files = getPdbFile();
403     // check to see if we are still waiting for Jmol files
404     long starttime = System.currentTimeMillis();
405     boolean waiting = true;
406     do
407     {
408       waiting = false;
409       for (String file : files)
410       {
411         try
412         {
413           // HACK - in Jalview 2.8 this call may not be threadsafe so we catch
414           // every possible exception
415           StructureMapping[] sm = ssm.getMapping(file);
416           if (sm == null || sm.length == 0)
417           {
418             waiting = true;
419           }
420         } catch (Exception x)
421         {
422           waiting = true;
423         } catch (Error q)
424         {
425           waiting = true;
426         }
427       }
428       // we wait around for a reasonable time before we give up
429     } while (waiting
430             && System.currentTimeMillis() < (10000 + 1000 * files.length + starttime));
431     if (waiting)
432     {
433       System.err
434               .println("RUNTIME PROBLEM: Chimera seems to be taking a long time to process all the structures.");
435       return;
436     }
437     refreshPdbEntries();
438     StringBuffer selectioncom = new StringBuffer();
439     for (int a = 0; a < _alignment.length; a++)
440     {
441       int refStructure = _refStructure[a];
442       AlignmentI alignment = _alignment[a];
443       ColumnSelection hiddenCols = _hiddenCols[a];
444       if (a > 0
445               && selectioncom.length() > 0
446               && !selectioncom.substring(selectioncom.length() - 1).equals(
447                       " "))
448       {
449         selectioncom.append(" ");
450       }
451       // process this alignment
452       if (refStructure >= files.length)
453       {
454         System.err.println("Invalid reference structure value "
455                 + refStructure);
456         refStructure = -1;
457       }
458       if (refStructure < -1)
459       {
460         refStructure = -1;
461       }
462
463       boolean matched[] = new boolean[alignment.getWidth()];
464       for (int m = 0; m < matched.length; m++)
465       {
466
467         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
468       }
469
470       int commonrpositions[][] = new int[files.length][alignment.getWidth()];
471       String isel[] = new String[files.length];
472       String[] targetC = new String[files.length];
473       String[] chainNames = new String[files.length];
474       String[] atomSpec = new String[files.length];
475       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
476       {
477         StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
478         // RACE CONDITION - getMapping only returns Jmol loaded filenames once
479         // Jmol callback has completed.
480         if (mapping == null || mapping.length < 1)
481         {
482           throw new Error(MessageManager.getString("error.implementation_error_chimera_getting_data"));
483         }
484         int lastPos = -1;
485         for (int s = 0; s < sequence[pdbfnum].length; s++)
486         {
487           for (int sp, m = 0; m < mapping.length; m++)
488           {
489             if (mapping[m].getSequence() == sequence[pdbfnum][s]
490                     && (sp = alignment.findIndex(sequence[pdbfnum][s])) > -1)
491             {
492               if (refStructure == -1)
493               {
494                 refStructure = pdbfnum;
495               }
496               SequenceI asp = alignment.getSequenceAt(sp);
497               for (int r = 0; r < matched.length; r++)
498               {
499                 if (!matched[r])
500                 {
501                   continue;
502                 }
503                 matched[r] = false; // assume this is not a good site
504                 if (r >= asp.getLength())
505                 {
506                   continue;
507                 }
508
509                 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
510                 {
511                   // no mapping to gaps in sequence
512                   continue;
513                 }
514                 int t = asp.findPosition(r); // sequence position
515                 int apos = mapping[m].getAtomNum(t);
516                 int pos = mapping[m].getPDBResNum(t);
517
518                 if (pos < 1 || pos == lastPos)
519                 {
520                   // can't align unmapped sequence
521                   continue;
522                 }
523                 matched[r] = true; // this is a good ite
524                 lastPos = pos;
525                 // just record this residue position
526                 commonrpositions[pdbfnum][r] = pos;
527               }
528               // create model selection suffix
529               isel[pdbfnum] = "#" + pdbfnum;
530               if (mapping[m].getChain() == null
531                       || mapping[m].getChain().trim().length() == 0)
532               {
533                 targetC[pdbfnum] = "";
534               }
535               else
536               {
537                 targetC[pdbfnum] = "." + mapping[m].getChain();
538               }
539               chainNames[pdbfnum] = mapping[m].getPdbId()
540                       + targetC[pdbfnum];
541               atomSpec[pdbfnum] = asp.getRNA() != null ? PHOSPHORUS : ALPHACARBON;
542               // move on to next pdb file
543               s = sequence[pdbfnum].length;
544               break;
545             }
546           }
547         }
548       }
549
550       // TODO: consider bailing if nmatched less than 4 because superposition
551       // not
552       // well defined.
553       // TODO: refactor superposable position search (above) from jmol selection
554       // construction (below)
555
556       String[] selcom = new String[files.length];
557       int nmatched = 0;
558       String sep = "";
559       // generate select statements to select regions to superimpose structures
560       {
561         for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
562         {
563           String chainCd = targetC[pdbfnum];
564           int lpos = -1;
565           boolean run = false;
566           StringBuffer molsel = new StringBuffer();
567           for (int r = 0; r < matched.length; r++)
568           {
569             if (matched[r])
570             {
571               if (pdbfnum == 0)
572               {
573                 nmatched++;
574               }
575               if (lpos != commonrpositions[pdbfnum][r] - 1)
576               {
577                 // discontinuity
578                 if (lpos != -1)
579                 {
580                   molsel.append((run ? "" : ":") + lpos);
581                   molsel.append(chainCd);
582                   molsel.append(",");
583                 }
584               }
585               else
586               {
587                 // continuous run - and lpos >-1
588                 if (!run)
589                 {
590                   // at the beginning, so add dash
591                   molsel.append(":" + lpos);
592                   molsel.append("-");
593                 }
594                 run = true;
595               }
596               lpos = commonrpositions[pdbfnum][r];
597               // molsel.append(lpos);
598             }
599           }
600           // add final selection phrase
601           if (lpos != -1)
602           {
603             molsel.append((run ? "" : ":") + lpos);
604             molsel.append(chainCd);
605             // molsel.append("");
606           }
607           if (molsel.length() > 1)
608           {
609             selcom[pdbfnum] = molsel.toString();
610             selectioncom.append("#" + pdbfnum);
611             selectioncom.append(selcom[pdbfnum]);
612             selectioncom.append(" ");
613             if (pdbfnum < files.length - 1)
614             {
615               selectioncom.append("| ");
616             }
617           }
618           else
619           {
620             selcom[pdbfnum] = null;
621           }
622         }
623       }
624       StringBuilder command = new StringBuilder(256);
625       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
626       {
627         if (pdbfnum == refStructure || selcom[pdbfnum] == null
628                 || selcom[refStructure] == null)
629         {
630           continue;
631         }
632         if (command.length() > 0)
633         {
634           command.append(";");
635         }
636
637         /*
638          * Form Chimera match command, from the 'new' structure to the
639          * 'reference' structure e.g. (residues 1-91, chain B/A, alphacarbons):
640          * 
641          * match #1:1-91.B@CA #0:1-91.A@CA
642          * 
643          * @see
644          * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
645          */
646         command.append("match #" + pdbfnum /* +".1" */);
647         // TODO: handle sub-models
648         command.append(selcom[pdbfnum]);
649         command.append("@" + atomSpec[pdbfnum]);
650         command.append(" #" + refStructure /* +".1" */);
651         command.append(selcom[refStructure]);
652         command.append("@" + atomSpec[refStructure]);
653       }
654       if (selectioncom.length() > 0)
655       {
656         // TODO remove debug output
657         System.out.println("Select regions:\n" + selectioncom.toString());
658         System.out
659                 .println("Superimpose command(s):\n" + command.toString());
660         allComs.append("~display all; chain @CA|P; ribbon "
661                 + selectioncom.toString() + ";"+command.toString());
662         // selcom.append("; ribbons; ");
663       }
664     }
665     if (selectioncom.length() > 0)
666     {// finally, mark all regions that were superposed.
667       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
668       {
669         selectioncom.setLength(selectioncom.length() - 1);
670       }
671       System.out.println("Select regions:\n" + selectioncom.toString());
672       allComs.append("; ~display all; chain @CA|P; ribbon "
673               + selectioncom.toString() + "");
674       // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
675       evalStateCommand(allComs.toString(), true /* false */);
676     }
677     
678   }
679
680   private void checkLaunched()
681   {
682     if (!viewer.isChimeraLaunched())
683     {
684       viewer.launchChimera(csm.getChimeraPaths());
685     }
686     if (!viewer.isChimeraLaunched())
687     {
688       log("Failed to launch Chimera!");
689     }
690   }
691
692   public void evalStateCommand(final String command, boolean resp)
693   {
694     viewerCommandHistory(false);
695     checkLaunched();
696     if (lastCommand == null || !lastCommand.equals(command))
697     {
698 //      Thread t = new Thread(new Runnable()
699 //      {
700 //        @Override
701 //        public void run()
702 //        {
703       // trim command or it may never find a match in the replyLog!!
704       lastReply = viewer.sendChimeraCommand(command.trim(), resp);
705       if (debug && resp)
706           {
707             log("Response from command ('" + command + "') was:\n"
708                     + lastReply);
709           }
710 //        }
711 //      });
712       // TODO - use j7/8 thread management
713 //      try
714 //      {
715 //        t.join();
716 //      } catch (InterruptedException foo)
717 //      {
718 //      }
719 //      ;
720     }
721     viewerCommandHistory(true);
722     lastCommand = command;
723   }
724
725   /**
726    * colour any structures associated with sequences in the given alignment
727    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
728    * if colourBySequence is enabled.
729    */
730   public void colourBySequence(boolean showFeatures,
731           jalview.api.AlignmentViewPanel alignmentv)
732   {
733     if (!colourBySequence || !loadingFinished)
734     {
735       return;
736     }
737     if (ssm == null)
738     {
739       return;
740     }
741     String[] files = getPdbFile();
742
743     SequenceRenderer sr = getSequenceRenderer(alignmentv);
744
745     FeatureRenderer fr = null;
746     if (showFeatures)
747     {
748       fr = getFeatureRenderer(alignmentv);
749     }
750     AlignmentI alignment = alignmentv.getAlignment();
751
752     for (jalview.structure.StructureMappingcommandSet cpdbbyseq : ChimeraCommands
753             .getColourBySequenceCommand(ssm, files, sequence, sr, fr,
754                     alignment))
755     {
756       for (String cbyseq : cpdbbyseq.commands)
757       {
758         waitForChimera();
759         evalStateCommand(cbyseq, false);
760         waitForChimera();
761       }
762     }
763   }
764
765   private void waitForChimera()
766   {
767     while (viewer.isBusy())
768     {
769       try {
770         Thread.sleep(15);
771       } catch (InterruptedException q)
772       {}
773     }
774   }
775
776   public boolean isColourBySequence()
777   {
778     return colourBySequence;
779   }
780
781   public void setColourBySequence(boolean colourBySequence)
782   {
783     this.colourBySequence = colourBySequence;
784   }
785
786   // End StructureListener
787   // //////////////////////////
788
789   public float[][] functionXY(String functionName, int x, int y)
790   {
791     return null;
792   }
793
794   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
795   {
796     // TODO Auto-generated method stub
797     return null;
798   }
799
800   public Color getColour(int atomIndex, int pdbResNum, String chain,
801           String pdbfile)
802   {
803     if (getModelNum(pdbfile) < 0)
804     {
805       return null;
806     }
807     log("get model / residue colour attribute unimplemented");
808     return null;
809   }
810
811   /**
812    * returns the current featureRenderer that should be used to colour the
813    * structures
814    * 
815    * @param alignment
816    * 
817    * @return
818    */
819   public abstract FeatureRenderer getFeatureRenderer(
820           AlignmentViewPanel alignment);
821
822   /**
823    * instruct the Jalview binding to update the pdbentries vector if necessary
824    * prior to matching the jmol view's contents to the list of structure files
825    * Jalview knows about.
826    */
827   public abstract void refreshPdbEntries();
828
829   private int getModelNum(String modelFileName)
830   {
831     String[] mfn = getPdbFile();
832     if (mfn == null)
833     {
834       return -1;
835     }
836     for (int i = 0; i < mfn.length; i++)
837     {
838       if (mfn[i].equalsIgnoreCase(modelFileName))
839       {
840         return i;
841       }
842     }
843     return -1;
844   }
845
846   /**
847    * map between index of model filename returned from getPdbFile and the first
848    * index of models from this file in the viewer. Note - this is not trimmed -
849    * use getPdbFile to get number of unique models.
850    */
851   private int _modelFileNameMap[];
852
853   // ////////////////////////////////
854   // /StructureListener
855   public synchronized String[] getPdbFile()
856   {
857     if (viewer == null)
858     {
859       return new String[0];
860     }
861     // if (modelFileNames == null)
862     // {
863     // Collection<ChimeraModel> chimodels = viewer.getChimeraModels();
864     // _modelFileNameMap = new int[chimodels.size()];
865     // int j = 0;
866     // for (ChimeraModel chimodel : chimodels)
867     // {
868     // String mdlName = chimodel.getModelName();
869     // }
870     // modelFileNames = new String[j];
871     // // System.arraycopy(mset, 0, modelFileNames, 0, j);
872     // }
873
874     return chimmaps.keySet().toArray(
875             modelFileNames = new String[chimmaps.size()]);
876   }
877
878   /**
879    * map from string to applet
880    */
881   public Map getRegistryInfo()
882   {
883     // TODO Auto-generated method stub
884     return null;
885   }
886
887   /**
888    * returns the current sequenceRenderer that should be used to colour the
889    * structures
890    * 
891    * @param alignment
892    * 
893    * @return
894    */
895   public abstract SequenceRenderer getSequenceRenderer(
896           AlignmentViewPanel alignment);
897
898   // jmol/ssm only
899   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
900           String pdbfile)
901   {
902     List<ChimeraModel> cms = chimmaps.get(pdbfile);
903     if (cms != null)
904     {
905       int mdlNum = cms.get(0).getModelNumber();
906
907       viewerCommandHistory(false);
908       // viewer.stopListening();
909       if (resetLastRes.length() > 0)
910       {
911         eval.setLength(0);
912         eval.append(resetLastRes.toString() + ";");
913       }
914
915       eval.append("display "); // +modelNum
916
917       resetLastRes.setLength(0);
918       resetLastRes.append("~display ");
919       {
920         eval.append(" #" + (mdlNum));
921         resetLastRes.append(" #" + (mdlNum));
922       }
923       // complete select string
924
925       eval.append(":" + pdbResNum);
926       resetLastRes.append(":" + pdbResNum);
927       if (!chain.equals(" "))
928       {
929         eval.append("." + chain);
930         resetLastRes.append("." + chain);
931       }
932       
933       viewer.sendChimeraCommand(eval.toString(), false);
934       viewerCommandHistory(true);
935       // viewer.startListening();
936     }
937   }
938
939   boolean debug = true;
940
941   private void log(String message)
942   {
943     System.err.println("## Chimera log: " + message);
944   }
945
946   private void viewerCommandHistory(boolean enable)
947   {
948     log("(Not yet implemented) History "
949             + ((debug || enable) ? "on" : "off"));
950   }
951
952   public void loadInline(String string)
953   {
954     loadedInline = true;
955     // TODO: re JAL-623
956     // viewer.loadInline(strModel, isAppend);
957     // could do this:
958     // construct fake fullPathName and fileName so we can identify the file
959     // later.
960     // Then, construct pass a reader for the string to Jmol.
961     // ((org.jmol.Viewer.Viewer) viewer).loadModelFromFile(fullPathName,
962     // fileName, null, reader, false, null, null, 0);
963     // viewer.openStringInline(string);
964     log("cannot load inline in Chimera, yet");
965   }
966
967   public void mouseOverStructure(int atomIndex, String strInfo)
968   {
969     // function to parse a mouseOver event from Chimera
970     //
971     int pdbResNum;
972     int alocsep = strInfo.indexOf("^");
973     int mdlSep = strInfo.indexOf("/");
974     int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
975
976     if (chainSeparator == -1)
977     {
978       chainSeparator = strInfo.indexOf(".");
979       if (mdlSep > -1 && mdlSep < chainSeparator)
980       {
981         chainSeparator1 = chainSeparator;
982         chainSeparator = mdlSep;
983       }
984     }
985     // handle insertion codes
986     if (alocsep != -1)
987     {
988       pdbResNum = Integer.parseInt(strInfo.substring(
989               strInfo.indexOf("]") + 1, alocsep));
990
991     }
992     else
993     {
994       pdbResNum = Integer.parseInt(strInfo.substring(
995               strInfo.indexOf("]") + 1, chainSeparator));
996     }
997     String chainId;
998
999     if (strInfo.indexOf(":") > -1)
1000     {
1001       chainId = strInfo.substring(strInfo.indexOf(":") + 1,
1002               strInfo.indexOf("."));
1003     }
1004     else
1005     {
1006       chainId = " ";
1007     }
1008
1009     String pdbfilename = modelFileNames[frameNo]; // default is first or current
1010     // model
1011     if (mdlSep > -1)
1012     {
1013       if (chainSeparator1 == -1)
1014       {
1015         chainSeparator1 = strInfo.indexOf(".", mdlSep);
1016       }
1017       String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
1018               chainSeparator1) : strInfo.substring(mdlSep + 1);
1019       try
1020       {
1021         // recover PDB filename for the model hovered over.
1022         int _mp = _modelFileNameMap.length - 1, mnumber = new Integer(mdlId)
1023                 .intValue() - 1;
1024         while (mnumber < _modelFileNameMap[_mp])
1025         {
1026           _mp--;
1027         }
1028         pdbfilename = modelFileNames[_mp];
1029         if (pdbfilename == null)
1030         {
1031           // pdbfilename = new File(viewer.getModelFileName(mnumber))
1032           // .getAbsolutePath();
1033         }
1034
1035       } catch (Exception e)
1036       {
1037       }
1038       ;
1039     }
1040     if (lastMessage == null || !lastMessage.equals(strInfo))
1041     {
1042       ssm.mouseOverStructure(pdbResNum, chainId, pdbfilename);
1043     }
1044
1045     lastMessage = strInfo;
1046   }
1047
1048   public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
1049   {
1050     /**
1051      * this implements the toggle label behaviour copied from the original
1052      * structure viewer, MCView
1053      */
1054     if (strData != null)
1055     {
1056       System.err.println("Ignoring additional pick data string " + strData);
1057     }
1058     // rewrite these selections for chimera (DNA, RNA and protein)
1059     int chainSeparator = strInfo.indexOf(":");
1060     int p = 0;
1061     if (chainSeparator == -1)
1062     {
1063       chainSeparator = strInfo.indexOf(".");
1064     }
1065
1066     String picked = strInfo.substring(strInfo.indexOf("]") + 1,
1067             chainSeparator);
1068     String mdlString = "";
1069     if ((p = strInfo.indexOf(":")) > -1)
1070     {
1071       picked += strInfo.substring(p + 1, strInfo.indexOf("."));
1072     }
1073
1074     if ((p = strInfo.indexOf("/")) > -1)
1075     {
1076       mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
1077     }
1078     picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
1079             + mdlString + "))";
1080     viewerCommandHistory(false);
1081
1082     if (!atomsPicked.contains(picked))
1083     {
1084       viewer.select(picked);
1085       atomsPicked.add(picked);
1086     }
1087     else
1088     {
1089       viewer.select("not " + picked);
1090       atomsPicked.remove(picked);
1091     }
1092     viewerCommandHistory(true);
1093     // TODO: in application this happens
1094     //
1095     // if (scriptWindow != null)
1096     // {
1097     // scriptWindow.sendConsoleMessage(strInfo);
1098     // scriptWindow.sendConsoleMessage("\n");
1099     // }
1100
1101   }
1102
1103   // incremented every time a load notification is successfully handled -
1104   // lightweight mechanism for other threads to detect when they can start
1105   // referring to new structures.
1106   private long loadNotifiesHandled = 0;
1107
1108   public long getLoadNotifiesHandled()
1109   {
1110     return loadNotifiesHandled;
1111   }
1112
1113   public void notifyFileLoaded(String fullPathName, String fileName2,
1114           String modelName, String errorMsg, int modelParts)
1115   {
1116     if (errorMsg != null)
1117     {
1118       fileLoadingError = errorMsg;
1119       refreshGUI();
1120       return;
1121     }
1122     // TODO: deal sensibly with models loaded inLine:
1123     // modelName will be null, as will fullPathName.
1124
1125     // the rest of this routine ignores the arguments, and simply interrogates
1126     // the Jmol view to find out what structures it contains, and adds them to
1127     // the structure selection manager.
1128     fileLoadingError = null;
1129     String[] oldmodels = modelFileNames;
1130     modelFileNames = null;
1131     chainNames = new ArrayList<String>();
1132     chainFile = new HashMap<String, String>();
1133     boolean notifyLoaded = false;
1134     String[] modelfilenames = getPdbFile();
1135     // first check if we've lost any structures
1136     if (oldmodels != null && oldmodels.length > 0)
1137     {
1138       int oldm = 0;
1139       for (int i = 0; i < oldmodels.length; i++)
1140       {
1141         for (int n = 0; n < modelfilenames.length; n++)
1142         {
1143           if (modelfilenames[n] == oldmodels[i])
1144           {
1145             oldmodels[i] = null;
1146             break;
1147           }
1148         }
1149         if (oldmodels[i] != null)
1150         {
1151           oldm++;
1152         }
1153       }
1154       if (oldm > 0)
1155       {
1156         String[] oldmfn = new String[oldm];
1157         oldm = 0;
1158         for (int i = 0; i < oldmodels.length; i++)
1159         {
1160           if (oldmodels[i] != null)
1161           {
1162             oldmfn[oldm++] = oldmodels[i];
1163           }
1164         }
1165         // deregister the Jmol instance for these structures - we'll add
1166         // ourselves again at the end for the current structure set.
1167         ssm.removeStructureViewerListener(this, oldmfn);
1168       }
1169     }
1170
1171     // register ourselves as a listener and notify the gui that it needs to
1172     // update itself.
1173     ssm.addStructureViewerListener(this);
1174
1175     if (notifyLoaded)
1176     {
1177       FeatureRenderer fr = getFeatureRenderer(null);
1178       if (fr != null)
1179       {
1180         fr.featuresAdded();
1181       }
1182       refreshGUI();
1183       loadNotifiesHandled++;
1184     }
1185     setLoadingFromArchive(false);
1186   }
1187
1188   public void setJalviewColourScheme(ColourSchemeI cs)
1189   {
1190     colourBySequence = false;
1191
1192     if (cs == null)
1193     {
1194       return;
1195     }
1196
1197     String res;
1198     int index;
1199     Color col;
1200     viewerCommandHistory(false);
1201     // TODO: Switch between nucleotide or aa selection expressions
1202     Enumeration en = ResidueProperties.aa3Hash.keys();
1203     StringBuffer command = new StringBuffer("select *;color white;");
1204     while (en.hasMoreElements())
1205     {
1206       res = en.nextElement().toString();
1207       index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
1208       if (index > 20)
1209       {
1210         continue;
1211       }
1212
1213       col = cs.findColour(ResidueProperties.aa[index].charAt(0));
1214       // TODO: need colour string function and res selection here
1215       command.append("select " + res + ";color[" + col.getRed() + ","
1216               + col.getGreen() + "," + col.getBlue() + "];");
1217     }
1218
1219     evalStateCommand(command.toString(),false);
1220     viewerCommandHistory(true);
1221   }
1222
1223   public void showHelp()
1224   {
1225     // chimera help
1226     showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
1227   }
1228
1229   /**
1230    * open the URL somehow
1231    * 
1232    * @param target
1233    */
1234   public abstract void showUrl(String url, String target);
1235
1236   /**
1237    * called when the binding thinks the UI needs to be refreshed after a Jmol
1238    * state change. this could be because structures were loaded, or because an
1239    * error has occured.
1240    */
1241   public abstract void refreshGUI();
1242
1243   public void componentResized(ComponentEvent e)
1244   {
1245
1246   }
1247
1248   public void componentMoved(ComponentEvent e)
1249   {
1250
1251   }
1252
1253   public void componentShown(ComponentEvent e)
1254   {
1255   }
1256
1257   public void componentHidden(ComponentEvent e)
1258   {
1259   }
1260
1261   public void setLoadingFromArchive(boolean loadingFromArchive)
1262   {
1263     this.loadingFromArchive = loadingFromArchive;
1264   }
1265
1266   /**
1267    * 
1268    * @return true if Jmol is still restoring state or loading is still going on
1269    *         (see setFinsihedLoadingFromArchive)
1270    */
1271   public boolean isLoadingFromArchive()
1272   {
1273     return loadingFromArchive && !loadingFinished;
1274   }
1275
1276   /**
1277    * modify flag which controls if sequence colouring events are honoured by the
1278    * binding. Should be true for normal operation
1279    * 
1280    * @param finishedLoading
1281    */
1282   public void setFinishedLoadingFromArchive(boolean finishedLoading)
1283   {
1284     loadingFinished = finishedLoading;
1285   }
1286
1287   public void setBackgroundColour(java.awt.Color col)
1288   {
1289     viewerCommandHistory(false);
1290     // todo set background colour
1291     viewer.sendChimeraCommand(
1292             "background [" + col.getRed() + "," + col.getGreen() + ","
1293                     + col.getBlue() + "];", false);
1294     viewerCommandHistory(true);
1295   }
1296
1297   /**
1298    * add structures and any known sequence associations
1299    * 
1300    * @returns the pdb entries added to the current set.
1301    */
1302   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
1303           SequenceI[][] seq, String[][] chns)
1304   {
1305     List<PDBEntry> v = new ArrayList<PDBEntry>();
1306     List<int[]> rtn = new ArrayList<int[]>();
1307     for (int i = 0; i < pdbentry.length; i++)
1308     {
1309       v.add(pdbentry[i]);
1310     }
1311     for (int i = 0; i < pdbe.length; i++)
1312     {
1313       int r = v.indexOf(pdbe[i]);
1314       if (r == -1 || r >= pdbentry.length)
1315       {
1316         rtn.add(new int[]
1317         { v.size(), i });
1318         v.add(pdbe[i]);
1319       }
1320       else
1321       {
1322         // just make sure the sequence/chain entries are all up to date
1323         addSequenceAndChain(r, seq[i], chns[i]);
1324       }
1325     }
1326     pdbe = v.toArray(new PDBEntry[v.size()]);
1327     pdbentry = pdbe;
1328     if (rtn.size() > 0)
1329     {
1330       // expand the tied sequence[] and string[] arrays
1331       SequenceI[][] sqs = new SequenceI[pdbentry.length][];
1332       String[][] sch = new String[pdbentry.length][];
1333       System.arraycopy(sequence, 0, sqs, 0, sequence.length);
1334       System.arraycopy(chains, 0, sch, 0, this.chains.length);
1335       sequence = sqs;
1336       chains = sch;
1337       pdbe = new PDBEntry[rtn.size()];
1338       for (int r = 0; r < pdbe.length; r++)
1339       {
1340         int[] stri = (rtn.get(r));
1341         // record the pdb file as a new addition
1342         pdbe[r] = pdbentry[stri[0]];
1343         // and add the new sequence/chain entries
1344         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
1345       }
1346     }
1347     else
1348     {
1349       pdbe = null;
1350     }
1351     return pdbe;
1352   }
1353
1354   /**
1355    * Adds sequences to the pe'th pdbentry's sequence set.
1356    * 
1357    * @param pe
1358    * @param seq
1359    */
1360   public void addSequence(int pe, SequenceI[] seq)
1361   {
1362     addSequenceAndChain(pe, seq, null);
1363   }
1364
1365   private void addSequenceAndChain(int pe, SequenceI[] seq, String[] tchain)
1366   {
1367     if (pe < 0 || pe >= pdbentry.length)
1368     {
1369       throw new Error(MessageManager.formatMessage(
1370               "error.implementation_error_no_pdbentry_from_index",
1371               new Object[]
1372               { Integer.valueOf(pe).toString() }));
1373     }
1374     final String nullChain = "TheNullChain";
1375     List<SequenceI> s = new ArrayList<SequenceI>();
1376     List<String> c = new ArrayList<String>();
1377     if (chains == null)
1378     {
1379       chains = new String[pdbentry.length][];
1380     }
1381     if (sequence[pe] != null)
1382     {
1383       for (int i = 0; i < sequence[pe].length; i++)
1384       {
1385         s.add(sequence[pe][i]);
1386         if (chains[pe] != null)
1387         {
1388           if (i < chains[pe].length)
1389           {
1390             c.add(chains[pe][i]);
1391           }
1392           else
1393           {
1394             c.add(nullChain);
1395           }
1396         }
1397         else
1398         {
1399           if (tchain != null && tchain.length > 0)
1400           {
1401             c.add(nullChain);
1402           }
1403         }
1404       }
1405     }
1406     for (int i = 0; i < seq.length; i++)
1407     {
1408       if (!s.contains(seq[i]))
1409       {
1410         s.add(seq[i]);
1411         if (tchain != null && i < tchain.length)
1412         {
1413           c.add(tchain[i] == null ? nullChain : tchain[i]);
1414         }
1415       }
1416     }
1417     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
1418     sequence[pe] = tmp;
1419     if (c.size() > 0)
1420     {
1421       String[] tch = c.toArray(new String[c.size()]);
1422       for (int i = 0; i < tch.length; i++)
1423       {
1424         if (tch[i] == nullChain)
1425         {
1426           tch[i] = null;
1427         }
1428       }
1429       chains[pe] = tch;
1430     }
1431     else
1432     {
1433       chains[pe] = null;
1434     }
1435   }
1436
1437   /**
1438    * 
1439    * @param pdbfile
1440    * @return text report of alignment between pdbfile and any associated
1441    *         alignment sequences
1442    */
1443   public String printMapping(String pdbfile)
1444   {
1445     return ssm.printMapping(pdbfile);
1446   }
1447
1448 }