Amend features/annotations in applet
[jalview.git] / src / jalview / appletgui / AppletJmol.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19
20 package jalview.appletgui;
21
22 import java.util.*;
23 import java.awt.*;
24 import java.awt.event.*;
25
26 import jalview.datamodel.*;
27 import jalview.structure.*;
28 import jalview.io.*;
29
30 import org.jmol.api.*;
31 import org.jmol.adapter.smarter.SmarterJmolAdapter;
32
33
34 import org.jmol.popup.*;
35 import jalview.schemes.*;
36
37
38 public class AppletJmol extends Frame
39     implements  StructureListener, JmolStatusListener,
40     KeyListener, ActionListener, ItemListener
41
42 {
43   Menu fileMenu = new Menu("File");
44   Menu viewMenu = new Menu("View");
45   Menu coloursMenu = new Menu("Colours");
46   Menu chainMenu = new Menu("Show Chain");
47   Menu helpMenu = new Menu("Help");
48   MenuItem mappingMenuItem = new MenuItem("View Mapping");
49
50   CheckboxMenuItem seqColour = new CheckboxMenuItem("By Sequence", true);
51   MenuItem chain = new MenuItem("By Chain");
52   MenuItem charge = new MenuItem("Charge & Cysteine");
53   MenuItem zappo = new MenuItem("Zappo");
54   MenuItem taylor = new MenuItem("Taylor");
55   MenuItem hydro = new MenuItem("Hydrophobicity");
56   MenuItem helix = new MenuItem("Helix Propensity");
57   MenuItem strand = new MenuItem("Strand Propensity");
58   MenuItem turn = new MenuItem("Turn Propensity");
59   MenuItem buried = new MenuItem("Buried Index");
60   MenuItem user = new MenuItem("User Defined Colours");
61
62   MenuItem jmolHelp = new MenuItem("Jmol Help");
63
64   JmolViewer viewer;
65   JmolPopup jmolpopup;
66
67   Panel scriptWindow;
68   TextField inputLine;
69   TextArea history;
70   SequenceI[] sequence;
71   StructureSelectionManager ssm;
72   RenderPanel renderPanel;
73   AlignmentPanel ap;
74   String fileLoadingError;
75   boolean loadedInline;
76   PDBEntry pdbentry;
77   boolean colourBySequence = true;
78   Vector atomsPicked = new Vector();
79
80   public AppletJmol(PDBEntry pdbentry,
81                     SequenceI[] seq,
82                     AlignmentPanel ap,
83                     String protocol)
84   {
85     this.ap = ap;
86     this.sequence = seq;
87     this.pdbentry = pdbentry;
88
89    String alreadyMapped = StructureSelectionManager
90         .getStructureSelectionManager()
91         .alreadyMappedToFile(pdbentry.getId());
92
93     if (alreadyMapped != null)
94     {
95        StructureSelectionManager.getStructureSelectionManager()
96             .setMapping(seq, pdbentry.getFile(), protocol);
97         return;
98     }
99
100     renderPanel = new RenderPanel();
101
102     this.add(renderPanel, BorderLayout.CENTER);
103
104     viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter());
105
106     viewer.setAppletContext("jalview",
107                        ap.av.applet.getDocumentBase(),
108                             ap.av.applet.getCodeBase(),
109                             null);
110
111     viewer.setJmolStatusListener(this);
112
113     jmolpopup = JmolPopup.newJmolPopup(viewer);
114
115     this.addWindowListener(new WindowAdapter()
116         {
117           public void windowClosing(WindowEvent evt)
118           {
119             closeViewer();
120           }
121         });
122
123     MenuBar menuBar = new MenuBar();
124     menuBar.add(fileMenu);
125     fileMenu.add(mappingMenuItem);
126     menuBar.add(viewMenu);
127     mappingMenuItem.addActionListener(this);
128     viewMenu.add(chainMenu);
129     menuBar.add(coloursMenu);
130     menuBar.add(helpMenu);
131
132     charge.addActionListener(this);
133     hydro.addActionListener(this);
134     chain.addActionListener(this);
135     seqColour.addItemListener(this);
136     zappo.addActionListener(this);
137     taylor.addActionListener(this);
138     helix.addActionListener(this);
139     strand.addActionListener(this);
140     turn.addActionListener(this);
141     buried.addActionListener(this);
142     user.addActionListener(this);
143
144     jmolHelp.addActionListener(this);
145
146     coloursMenu.add(seqColour);
147     coloursMenu.add(chain);
148     coloursMenu.add(charge);
149     coloursMenu.add(zappo);
150     coloursMenu.add(taylor);
151     coloursMenu.add(hydro);
152     coloursMenu.add(helix);
153     coloursMenu.add(strand);
154     coloursMenu.add(turn);
155     coloursMenu.add(buried);
156     coloursMenu.add(user);
157
158     helpMenu.add(jmolHelp);
159
160     this.setMenuBar(menuBar);
161
162     if(pdbentry.getFile()!=null)
163     {
164       if (protocol.equals(AppletFormatAdapter.PASTE))
165         loadInline(pdbentry.getFile());
166       else
167           viewer.openFile(pdbentry.getFile());
168     }
169
170     this.setBounds(400, 400, 400, 400);
171
172     this.setVisible(true);
173   }
174
175   public void loadInline(String string)
176   {
177     loadedInline = true;
178     viewer.openStringInline(string);
179   }
180
181
182   void setChainMenuItems(Vector chains)
183   {
184     chainMenu.removeAll();
185
186     MenuItem menuItem = new MenuItem("All");
187     menuItem.addActionListener(this);
188
189     chainMenu.add(menuItem);
190
191     CheckboxMenuItem menuItemCB;
192     for (int c = 0; c < chains.size(); c++)
193     {
194       menuItemCB = new CheckboxMenuItem(chains.elementAt(c).toString(), true);
195       menuItemCB.addItemListener(this);
196       chainMenu.add(menuItemCB);
197     }
198   }
199
200   boolean allChainsSelected = false;
201   void centerViewer()
202   {
203     StringBuffer cmd = new StringBuffer();
204     for (int i = 0; i < chainMenu.getItemCount(); i++)
205     {
206       if (chainMenu.getItem(i) instanceof CheckboxMenuItem)
207       {
208         CheckboxMenuItem item = (CheckboxMenuItem) chainMenu.getItem(i);
209         if (item.getState())
210           cmd.append(":" + item.getLabel() + " or ");
211       }
212     }
213
214     if (cmd.length() > 0)
215       cmd.setLength(cmd.length() - 4);
216
217     viewer.evalString("select *;restrict "
218                       + cmd + ";cartoon;center " + cmd);
219   }
220
221
222   void closeViewer()
223   {
224     viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
225     viewer.evalStringQuiet("zap");
226     viewer.setJmolStatusListener(null);
227     viewer = null;
228
229     //We'll need to find out what other
230     // listeners need to be shut down in Jmol
231     StructureSelectionManager
232         .getStructureSelectionManager()
233         .removeStructureViewerListener(this, pdbentry.getId());
234
235     this.setVisible(false);
236   }
237
238   public void actionPerformed(ActionEvent evt)
239   {
240     if(evt.getSource()==mappingMenuItem)
241     {
242       jalview.appletgui.CutAndPasteTransfer cap
243           = new jalview.appletgui.CutAndPasteTransfer(false, null);
244       Frame frame = new Frame();
245       frame.add(cap);
246
247       jalview.bin.JalviewLite.addFrame(frame, "PDB - Sequence Mapping", 550,
248                                        600);
249       cap.setText(
250           StructureSelectionManager.getStructureSelectionManager().printMapping(
251               pdbentry.getFile())
252           );
253     }
254     else if (evt.getSource() == charge)
255     {
256       colourBySequence = false;
257       seqColour.setState(false);
258       viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
259                       +"select LYS,ARG;color blue;select CYS;color yellow");
260     }
261
262     else if (evt.getSource() == chain)
263     {
264       colourBySequence = false;
265       seqColour.setState(false);
266       viewer.evalStringQuiet("select *;color chain");
267     }
268     else if (evt.getSource() == zappo)
269     {
270       setJalviewColourScheme(new ZappoColourScheme());
271     }
272     else if (evt.getSource() == taylor)
273     {
274      setJalviewColourScheme(new TaylorColourScheme());
275     }
276     else if (evt.getSource() == hydro)
277     {
278       setJalviewColourScheme(new HydrophobicColourScheme());
279     }
280     else if (evt.getSource() == helix)
281     {
282       setJalviewColourScheme(new HelixColourScheme());
283     }
284     else if (evt.getSource() == strand)
285     {
286       setJalviewColourScheme(new StrandColourScheme());
287     }
288     else if (evt.getSource() == turn)
289     {
290       setJalviewColourScheme(new TurnColourScheme());
291     }
292     else if (evt.getSource() == buried)
293     {
294       setJalviewColourScheme(new BuriedColourScheme());
295     }
296     else if (evt.getSource() == user)
297     {
298       new UserDefinedColours(this);
299     }
300     else if(evt.getSource() == jmolHelp)
301     {
302       try{
303         ap.av.applet.getAppletContext().showDocument(
304             new java.net.URL("http://jmol.sourceforge.net/docs/JmolUserGuide/"),
305             "jmolHelp");
306       }catch(java.net.MalformedURLException ex){}
307     }
308     else
309     {
310       allChainsSelected = true;
311       for (int i = 0; i < chainMenu.getItemCount(); i++)
312       {
313         if (chainMenu.getItem(i) instanceof CheckboxMenuItem)
314           ( (CheckboxMenuItem) chainMenu.getItem(i)).setState(true);
315       }
316       centerViewer();
317       allChainsSelected = false;
318     }
319   }
320
321   public void setJalviewColourScheme(ColourSchemeI cs)
322   {
323     colourBySequence = false;
324     seqColour.setState(false);
325
326     if(cs==null)
327       return;
328
329     String res;
330     int index;
331     Color col;
332
333     Enumeration en = ResidueProperties.aa3Hash.keys();
334     StringBuffer command = new StringBuffer("select *;color white;");
335     while(en.hasMoreElements())
336     {
337       res = en.nextElement().toString();
338       index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
339       if(index>20)
340         continue;
341
342       col = cs.findColour(ResidueProperties.aa[index].charAt(0));
343
344       command.append("select "+res+";color["
345                         + col.getRed() + ","
346                         + col.getGreen() + ","
347                         + col.getBlue() + "];");
348     }
349
350     viewer.evalStringQuiet(command.toString());
351   }
352
353   public void itemStateChanged(ItemEvent evt)
354   {
355     if (evt.getSource() == seqColour)
356     {
357       colourBySequence = seqColour.getState();
358       colourBySequence(ap);
359     }
360     else if (!allChainsSelected)
361       centerViewer();
362   }
363
364   public void keyPressed(KeyEvent evt)
365   {
366     if (evt.getKeyCode() == KeyEvent.VK_ENTER
367         && scriptWindow.isVisible())
368     {
369       viewer.evalString(inputLine.getText());
370       history.append("\n$ "+inputLine.getText());
371       inputLine.setText("");
372     }
373
374   }
375
376   public void keyTyped(KeyEvent evt)
377   {  }
378
379   public void keyReleased(KeyEvent evt){}
380
381   //////////////////////////////////
382   ///StructureListener
383   public String getPdbFile()
384   {
385     return "???";
386   }
387
388
389
390   String lastMessage;
391   public void mouseOverStructure(int atomIndex, String strInfo)
392   {
393       int pdbResNum;
394
395       int chainSeparator = strInfo.indexOf(":");
396
397       if(chainSeparator==-1)
398         chainSeparator = strInfo.indexOf(".");
399
400       pdbResNum = Integer.parseInt(
401           strInfo.substring(strInfo.indexOf("]")+ 1, chainSeparator));
402
403       String chainId;
404
405       if (strInfo.indexOf(":") > -1)
406         chainId = strInfo.substring
407             (strInfo.indexOf(":")+1, strInfo.indexOf("."));
408       else
409       {
410         chainId = " ";
411       }
412
413       if (lastMessage == null || !lastMessage.equals(strInfo))
414         ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile());
415
416       lastMessage = strInfo;
417   }
418
419   StringBuffer resetLastRes = new StringBuffer();
420   StringBuffer eval = new StringBuffer();
421
422   public void highlightAtom(int atomIndex, int pdbResNum, String chain, String pdbfile)
423   {
424     if (!pdbfile.equals(pdbentry.getFile()))
425       return;
426
427     if (resetLastRes.length() > 0)
428     {
429       viewer.evalStringQuiet(resetLastRes.toString());
430     }
431
432     eval.setLength(0);
433     eval.append("select " + pdbResNum);
434
435     resetLastRes.setLength(0);
436     resetLastRes.append("select " + pdbResNum);
437
438     if (!chain.equals(" "))
439     {
440       eval.append(":" + chain);
441       resetLastRes.append(":" + chain);
442     }
443
444     eval.append(";color gold;wireframe 100");
445
446     Color col = new Color(viewer.getAtomArgb(atomIndex));
447
448     resetLastRes.append(";color["
449                         + col.getRed() + ","
450                         + col.getGreen() + ","
451                         + col.getBlue() + "];wireframe 0");
452
453     viewer.evalStringQuiet(eval.toString());
454
455   }
456
457   public void updateColours(Object source)
458   {
459     colourBySequence( (AlignmentPanel) source);
460   }
461
462 //End StructureListener
463 ////////////////////////////
464
465   FeatureRenderer fr;
466   public void colourBySequence(AlignmentPanel ap)
467   {
468     if(!colourBySequence)
469       return;
470
471
472     StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
473
474     if (mapping.length < 1)
475       return;
476
477     SequenceRenderer sr = ap.seqPanel.seqCanvas.getSequenceRenderer();
478
479     boolean showFeatures = false;
480     if (ap.av.showSequenceFeatures)
481     {
482       showFeatures = true;
483       if (fr == null)
484       {
485         fr = new jalview.appletgui.FeatureRenderer(ap.av);
486       }
487
488       fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
489     }
490
491     StringBuffer command = new StringBuffer();
492
493     int lastPos = -1;
494     for (int s = 0; s < sequence.length; s++)
495     {
496       for (int m = 0; m < mapping.length; m++)
497       {
498         if (mapping[m].getSequence() == sequence[s])
499         {
500           for (int r = 0; r < sequence[s].getLength(); r++)
501           {
502             int pos = mapping[m].getPDBResNum(
503                 sequence[s].findPosition(r));
504
505             if (pos < 1 || pos==lastPos)
506               continue;
507
508             lastPos = pos;
509
510             Color col = sr.getResidueBoxColour(sequence[s], r);
511
512             if (showFeatures)
513               col = fr.findFeatureColour(col, sequence[s], r);
514
515             if (command.toString().endsWith(":" + mapping[m].getChain()+
516                                             ";color["
517                                             + col.getRed() + ","
518                                             + col.getGreen() + ","
519                                             + col.getBlue() + "]"))
520             {
521               command = condenseCommand(command.toString(), pos);
522               continue;
523             }
524
525             command.append(";select " + pos);
526
527             if (!mapping[m].getChain().equals(" "))
528             {
529               command.append(":" + mapping[m].getChain());
530             }
531
532             command.append(";color["
533                              + col.getRed() + ","
534                              + col.getGreen() + ","
535                              + col.getBlue() + "]");
536
537           }
538           break;
539         }
540       }
541     }
542
543     viewer.evalStringQuiet(command.toString());
544   }
545
546   StringBuffer condenseCommand(String command, int pos)
547   {
548
549     StringBuffer sb = new StringBuffer(command.substring(0, command.lastIndexOf("select")+7));
550
551     command = command.substring(sb.length());
552
553     String start;
554
555     if (command.indexOf("-") > -1)
556     {
557       start = command.substring(0,command.indexOf("-"));
558     }
559     else
560     {
561       start = command.substring(0, command.indexOf(":"));
562     }
563
564     sb.append(start+"-"+pos+command.substring(command.indexOf(":")));
565
566     return sb;
567   }
568
569   /////////////////////////////////
570   //JmolStatusListener
571
572   public String eval(String strEval)
573   {
574    // System.out.println(strEval);
575    //"# 'eval' is implemented only for the applet.";
576     return null;
577   }
578
579   public void createImage(String file, String type, int quality)
580   {}
581
582   public void setCallbackFunction(String callbackType,
583                                   String callbackFunction)
584   {}
585
586   public void notifyFileLoaded(String fullPathName, String fileName,
587                                String modelName, Object clientFile,
588                                String errorMsg)
589   {
590     if(errorMsg!=null)
591     {
592       fileLoadingError = errorMsg;
593       repaint();
594       return;
595     }
596
597     fileLoadingError = null;
598
599     if (fileName != null)
600     {
601       //FILE LOADED OK
602       jmolpopup.updateComputedMenus();
603             viewer.evalStringQuiet(
604           "select backbone;restrict;cartoon;wireframe off;spacefill off");
605
606       ssm = StructureSelectionManager.getStructureSelectionManager();
607
608       MCview.PDBfile pdb;
609       if (loadedInline)
610       {
611         pdb = ssm.setMapping(sequence,
612                                 pdbentry.getFile(),
613                                 AppletFormatAdapter.PASTE);
614         pdbentry.setFile("INLINE"+pdb.id);
615       }
616       else
617       {
618          pdb = ssm.setMapping(sequence,
619                               pdbentry.getFile(),
620                               AppletFormatAdapter.URL);
621       }
622
623       pdbentry.setId(pdb.id);
624
625       ssm.addStructureViewerListener(this);
626
627       Vector chains = new Vector();
628       for (int i = 0; i < pdb.chains.size(); i++)
629       {
630         chains.addElement( ( (MCview.PDBChain) pdb.chains.elementAt(i)).id);
631       }
632       setChainMenuItems(chains);
633
634       colourBySequence(ap);
635
636       StringBuffer title = new StringBuffer(sequence[0].getName() + ":" +
637                                             pdbentry.getId());
638
639       if (pdbentry.getProperty() != null)
640       {
641         if (pdbentry.getProperty().get("method") != null)
642         {
643           title.append(" Method: ");
644           title.append(pdbentry.getProperty().get("method"));
645         }
646         if (pdbentry.getProperty().get("chains") != null)
647         {
648           title.append(" Chain:");
649           title.append(pdbentry.getProperty().get("chains"));
650         }
651       }
652
653       this.setTitle(title.toString());
654
655     }
656     else
657       return;
658   }
659
660   public void notifyFrameChanged(int frameNo)
661   {
662     boolean isAnimationRunning = (frameNo <= -2);
663   }
664
665   public void notifyScriptStart(String statusMessage, String additionalInfo)
666   {}
667
668   public void sendConsoleEcho(String strEcho)
669   {
670     if (scriptWindow == null)
671       showConsole(true);
672
673     history.append("\n"+strEcho);
674   }
675
676   public void sendConsoleMessage(String strStatus)
677   {
678     if(history!=null && strStatus!=null
679        && !strStatus.equals("Script completed"))
680     {
681       history.append("\n"+strStatus);
682     }
683   }
684
685   public void notifyScriptTermination(String strStatus, int msWalltime)
686   {  }
687
688   public void handlePopupMenu(int x, int y)
689   {
690     jmolpopup.show(x, y);
691   }
692
693   public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
694   {
695     notifyAtomPicked(iatom, strMeasure);
696   }
697
698   public void notifyNewDefaultModeMeasurement(int count, String strInfo)
699   {}
700
701   public void notifyAtomPicked(int atomIndex, String strInfo)
702   {
703
704     int chainSeparator = strInfo.indexOf(":");
705
706     if(chainSeparator==-1)
707       chainSeparator = strInfo.indexOf(".");
708
709     String picked =
710         strInfo.substring(strInfo.indexOf("]")+ 1, chainSeparator);
711
712
713     if (strInfo.indexOf(":") > -1)
714       picked+=strInfo.substring(strInfo.indexOf(":")+1,
715                                strInfo.indexOf("."));
716
717     picked+=".C";
718
719     if (!atomsPicked.contains(picked))
720     {
721       viewer.evalString("select "+picked+";label %n %r:%c");
722       atomsPicked.addElement(picked);
723     }
724     else
725     {
726       viewer.evalString("select "+picked+";label off");
727       atomsPicked.removeElement(picked);
728     }
729   }
730
731   public void notifyAtomHovered(int atomIndex, String strInfo)
732   {
733     mouseOverStructure(atomIndex, strInfo);
734   }
735
736   public void sendSyncScript(String script, String appletName)
737   {}
738
739   public void showUrl(String url)
740   {
741     try{
742       ap.av.applet.getAppletContext().showDocument(new java.net.URL(url),
743           "jmolOutput");
744     }catch(java.net.MalformedURLException ex)
745     {}
746   }
747
748   public void showConsole(boolean showConsole)
749   {
750     if (scriptWindow == null)
751     {
752       scriptWindow = new Panel(new BorderLayout());
753       inputLine = new TextField();
754       history = new TextArea(5, 40);
755       scriptWindow.add(history, BorderLayout.CENTER);
756       scriptWindow.add(inputLine, BorderLayout.SOUTH);
757       add(scriptWindow, BorderLayout.SOUTH);
758       scriptWindow.setVisible(false);
759       history.setEditable(false);
760       inputLine.addKeyListener(this);
761     }
762
763     scriptWindow.setVisible(!scriptWindow.isVisible());
764     validate();
765   }
766
767   public float functionXY(String functionName, int x, int y)
768   {
769     return 0;
770   }
771
772   ///End JmolStatusListener
773   ///////////////////////////////
774
775
776   class RenderPanel
777       extends Panel
778   {
779     Dimension currentSize = new Dimension();
780     Rectangle rectClip = new Rectangle();
781
782     public void update(Graphics g) {
783       paint(g);
784     }
785     public void paint(Graphics g)
786     {
787       currentSize = this.getSize();
788       rectClip = g.getClipBounds();
789
790       if (viewer == null)
791       {
792         g.setColor(Color.black);
793         g.fillRect(0, 0, currentSize.width, currentSize.height);
794         g.setColor(Color.white);
795         g.setFont(new Font("Verdana", Font.BOLD, 14));
796         g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
797       }
798       else
799       {
800         viewer.renderScreenImage(g, currentSize, rectClip);
801       }
802     }
803   }
804
805 }