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