JAL-1588 refactoring to StructureViewerBase and related
[jalview.git] / src / jalview / gui / AppJmol.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.gui;
22
23 import jalview.bin.Cache;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.ColumnSelection;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.AppletFormatAdapter;
30 import jalview.io.JalviewFileChooser;
31 import jalview.io.JalviewFileView;
32 import jalview.schemes.BuriedColourScheme;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.HelixColourScheme;
35 import jalview.schemes.HydrophobicColourScheme;
36 import jalview.schemes.PurinePyrimidineColourScheme;
37 import jalview.schemes.StrandColourScheme;
38 import jalview.schemes.TaylorColourScheme;
39 import jalview.schemes.TurnColourScheme;
40 import jalview.schemes.ZappoColourScheme;
41 import jalview.structures.models.AAStructureBindingModel;
42 import jalview.util.MessageManager;
43 import jalview.util.Platform;
44
45 import java.awt.BorderLayout;
46 import java.awt.Color;
47 import java.awt.Dimension;
48 import java.awt.Font;
49 import java.awt.Graphics;
50 import java.awt.Rectangle;
51 import java.awt.event.ActionEvent;
52 import java.awt.event.ActionListener;
53 import java.awt.event.ItemEvent;
54 import java.awt.event.ItemListener;
55 import java.io.BufferedReader;
56 import java.io.File;
57 import java.io.FileOutputStream;
58 import java.io.FileReader;
59 import java.io.PrintWriter;
60 import java.util.Enumeration;
61 import java.util.Vector;
62
63 import javax.swing.JCheckBoxMenuItem;
64 import javax.swing.JColorChooser;
65 import javax.swing.JInternalFrame;
66 import javax.swing.JMenu;
67 import javax.swing.JMenuItem;
68 import javax.swing.JOptionPane;
69 import javax.swing.JPanel;
70 import javax.swing.JSplitPane;
71 import javax.swing.event.InternalFrameAdapter;
72 import javax.swing.event.InternalFrameEvent;
73 import javax.swing.event.MenuEvent;
74 import javax.swing.event.MenuListener;
75
76 public class AppJmol extends StructureViewerBase
77 {
78   AppJmolBinding jmb;
79
80   JPanel scriptWindow;
81
82   JSplitPane splitPane;
83
84   RenderPanel renderPanel;
85
86   Vector atomsPicked = new Vector();
87
88   private boolean addingStructures = false;
89
90   /**
91    * 
92    * @param file
93    * @param id
94    * @param seq
95    * @param ap
96    * @param loadStatus
97    * @param bounds
98    * @deprecated defaults to AppJmol(String[] files, ... , viewid);
99    */
100   @Deprecated
101   public AppJmol(String file, String id, SequenceI[] seq,
102           AlignmentPanel ap, String loadStatus, Rectangle bounds)
103   {
104     this(file, id, seq, ap, loadStatus, bounds, null);
105   }
106
107   /**
108    * @deprecated
109    */
110   @Deprecated
111   public AppJmol(String file, String id, SequenceI[] seq,
112           AlignmentPanel ap, String loadStatus, Rectangle bounds,
113           String viewid)
114   {
115     this(new String[]
116     { file }, new String[]
117     { id }, new SequenceI[][]
118     { seq }, ap, true, true, false, loadStatus, bounds, viewid);
119   }
120
121   ViewSelectionMenu seqColourBy;
122
123   /**
124    * 
125    * @param files
126    * @param ids
127    * @param seqs
128    * @param ap
129    * @param usetoColour
130    *          - add the alignment panel to the list used for colouring these
131    *          structures
132    * @param useToAlign
133    *          - add the alignment panel to the list used for aligning these
134    *          structures
135    * @param leaveColouringToJmol
136    *          - do not update the colours from any other source. Jmol is
137    *          handling them
138    * @param loadStatus
139    * @param bounds
140    * @param viewid
141    */
142   public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
143           AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
144           boolean leaveColouringToJmol, String loadStatus,
145           Rectangle bounds, String viewid)
146   {
147     PDBEntry[] pdbentrys = new PDBEntry[files.length];
148     for (int i = 0; i < pdbentrys.length; i++)
149     {
150       PDBEntry pdbentry = new PDBEntry();
151       pdbentry.setFile(files[i]);
152       pdbentry.setId(ids[i]);
153       pdbentrys[i] = pdbentry;
154     }
155     // / TODO: check if protocol is needed to be set, and if chains are
156     // autodiscovered.
157     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
158             pdbentrys, seqs, null, null);
159
160     jmb.setLoadingFromArchive(true);
161     addAlignmentPanel(ap);
162     if (useToAlign)
163     {
164       useAlignmentPanelForSuperposition(ap);
165     }
166     if (leaveColouringToJmol || !usetoColour)
167     {
168       jmb.setColourBySequence(false);
169       seqColour.setSelected(false);
170       viewerColour.setSelected(true);
171     }
172     if (usetoColour)
173     {
174       useAlignmentPanelForColourbyseq(ap);
175       jmb.setColourBySequence(true);
176       seqColour.setSelected(true);
177       viewerColour.setSelected(false);
178     }
179     this.setBounds(bounds);
180     initMenus();
181     setViewId(viewid);
182     // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
183     // bounds.width,bounds.height);
184
185     this.addInternalFrameListener(new InternalFrameAdapter()
186     {
187       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
188       {
189         closeViewer();
190       }
191     });
192     initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
193
194   }
195
196   private void initMenus()
197   {
198     seqColour.setSelected(jmb.isColourBySequence());
199     viewerColour.setSelected(!jmb.isColourBySequence());
200     if (_colourwith == null)
201     {
202       _colourwith = new Vector<AlignmentPanel>();
203     }
204     if (_alignwith == null)
205     {
206       _alignwith = new Vector<AlignmentPanel>();
207     }
208
209     seqColourBy = new ViewSelectionMenu(MessageManager.getString("label.colour_by"), this, _colourwith,
210             new ItemListener()
211             {
212
213               @Override
214               public void itemStateChanged(ItemEvent e)
215               {
216                 if (!seqColour.isSelected())
217                 {
218                   seqColour.doClick();
219                 }
220                 else
221                 {
222                   // update the jmol display now.
223                   seqColour_actionPerformed(null);
224                 }
225               }
226             });
227     viewMenu.add(seqColourBy);
228     final ItemListener handler;
229     JMenu alpanels = new ViewSelectionMenu(MessageManager.getString("label.superpose_with"), this,
230             _alignwith, handler = new ItemListener()
231             {
232
233               @Override
234               public void itemStateChanged(ItemEvent e)
235               {
236                 alignStructs.setEnabled(_alignwith.size() > 0);
237                 alignStructs.setToolTipText(MessageManager
238                         .formatMessage(
239                                 "label.align_structures_using_linked_alignment_views",
240                                 new String[]
241                                 { new Integer(_alignwith.size()).toString() }));
242               }
243             });
244     handler.itemStateChanged(null);
245     viewerActionMenu.add(alpanels);
246     viewerActionMenu.addMenuListener(new MenuListener()
247     {
248
249       @Override
250       public void menuSelected(MenuEvent e)
251       {
252         handler.itemStateChanged(null);
253       }
254
255       @Override
256       public void menuDeselected(MenuEvent e)
257       {
258         // TODO Auto-generated method stub
259
260       }
261
262       @Override
263       public void menuCanceled(MenuEvent e)
264       {
265         // TODO Auto-generated method stub
266
267       }
268     });
269   }
270
271   IProgressIndicator progressBar = null;
272
273   /**
274    * add a single PDB structure to a new or existing Jmol view
275    * 
276    * @param pdbentry
277    * @param seq
278    * @param chains
279    * @param ap
280    */
281   public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
282           final AlignmentPanel ap)
283   {
284     progressBar = ap.alignFrame;
285     // ////////////////////////////////
286     // Is the pdb file already loaded?
287     String alreadyMapped = ap.getStructureSelectionManager()
288             .alreadyMappedToFile(pdbentry.getId());
289
290     if (alreadyMapped != null)
291     {
292       int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
293               MessageManager.formatMessage(
294                       "label.pdb_entry_is_already_displayed", new String[]
295                       { pdbentry.getId() }), MessageManager.formatMessage(
296                       "label.map_sequences_to_visible_window", new String[]
297                       { pdbentry.getId() }),
298               JOptionPane.YES_NO_CANCEL_OPTION);
299
300       if (option == JOptionPane.CANCEL_OPTION)
301       {
302         return;
303       }
304       if (option == JOptionPane.YES_OPTION)
305       {
306         // TODO : Fix multiple seq to one chain issue here.
307         ap.getStructureSelectionManager().setMapping(seq, chains,
308                 alreadyMapped, AppletFormatAdapter.FILE);
309         if (ap.getSeqPanel().seqCanvas.fr != null)
310         {
311           ap.getSeqPanel().seqCanvas.fr.featuresAdded();
312           ap.paintAlignment(true);
313         }
314
315         // Now this AppJmol is mapped to new sequences. We must add them to
316         // the exisiting array
317         JInternalFrame[] frames = Desktop.instance.getAllFrames();
318
319         for (int i = 0; i < frames.length; i++)
320         {
321           if (frames[i] instanceof AppJmol)
322           {
323             final AppJmol topJmol = ((AppJmol) frames[i]);
324             // JBPNOTE: this looks like a binding routine, rather than a gui
325             // routine
326             for (int pe = 0; pe < topJmol.jmb.getPdbCount(); pe++)
327             {
328               if (topJmol.jmb.getPdbEntry(pe).getFile()
329                       .equals(alreadyMapped))
330               {
331                 topJmol.jmb.addSequence(pe, seq);
332                 topJmol.addAlignmentPanel(ap);
333                 // add it to the set used for colouring
334                 topJmol.useAlignmentPanelForColourbyseq(ap);
335                 topJmol.buildActionMenu();
336                 ap.getStructureSelectionManager()
337                         .sequenceColoursChanged(ap);
338                 break;
339               }
340             }
341           }
342         }
343
344         return;
345       }
346     }
347     // /////////////////////////////////
348     // Check if there are other Jmol views involving this alignment
349     // and prompt user about adding this molecule to one of them
350     Vector existingViews = getJmolsFor(ap);
351     if (existingViews.size() > 0)
352     {
353       Enumeration jm = existingViews.elements();
354       while (jm.hasMoreElements())
355       {
356         AppJmol topJmol = (AppJmol) jm.nextElement();
357         // TODO: highlight topJmol in view somehow
358         int option = JOptionPane
359                 .showInternalConfirmDialog(
360                         Desktop.desktop,
361                         MessageManager.formatMessage(
362                                 "label.add_pdbentry_to_view", new String[]
363                                 { pdbentry.getId(), topJmol.getTitle() }),
364                         MessageManager
365                                 .getString("label.align_to_existing_structure_view"),
366                         JOptionPane.YES_NO_CANCEL_OPTION);
367         if (option == JOptionPane.CANCEL_OPTION)
368         {
369           return;
370         }
371         if (option == JOptionPane.YES_OPTION)
372         {
373           topJmol.useAlignmentPanelForSuperposition(ap);
374           topJmol.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
375           return;
376         }
377       }
378     }
379     // /////////////////////////////////
380     openNewJmol(ap, new PDBEntry[]
381     { pdbentry }, new SequenceI[][]
382     { seq });
383   }
384
385   private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys,
386           SequenceI[][] seqs)
387   {
388     progressBar = ap.alignFrame;
389     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
390             pdbentrys, seqs, null, null);
391     addAlignmentPanel(ap);
392     useAlignmentPanelForColourbyseq(ap);
393     if (pdbentrys.length > 1)
394     {
395       alignAddedStructures = true;
396       useAlignmentPanelForSuperposition(ap);
397     }
398     jmb.setColourBySequence(true);
399     setSize(400, 400); // probably should be a configurable/dynamic default here
400     initMenus();
401     worker = null;
402     {
403       addingStructures = false;
404       worker = new Thread(this);
405       worker.start();
406     }
407     this.addInternalFrameListener(new InternalFrameAdapter()
408     {
409       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
410       {
411         closeViewer();
412       }
413     });
414
415   }
416
417   /**
418    * create a new Jmol containing several structures superimposed using the
419    * given alignPanel.
420    * 
421    * @param ap
422    * @param pe
423    * @param seqs
424    */
425   public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
426   {
427     openNewJmol(ap, pe, seqs);
428   }
429
430   public AlignmentPanel[] getAllAlignmentPanels()
431   {
432     AlignmentPanel[] t;
433     AlignmentPanel[] list = new AlignmentPanel[0];
434     for (String setid : _aps)
435     {
436       AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
437       if (panels != null)
438       {
439         t = new AlignmentPanel[list.length + panels.length];
440         System.arraycopy(list, 0, t, 0, list.length);
441         System.arraycopy(panels, 0, t, list.length, panels.length);
442         list = t;
443       }
444     }
445
446     return list;
447   }
448
449   /**
450    * set the primary alignmentPanel reference and add another alignPanel to the
451    * list of ones to use for colouring and aligning
452    * 
453    * @param nap
454    */
455   public void addAlignmentPanel(AlignmentPanel nap)
456   {
457     if (getAlignmentPanel() == null)
458     {
459       setAlignmentPanel(nap);
460     }
461     if (!_aps.contains(nap.av.getSequenceSetId()))
462     {
463       _aps.add(nap.av.getSequenceSetId());
464     }
465   }
466
467   /**
468    * remove any references held to the given alignment panel
469    * 
470    * @param nap
471    */
472   public void removeAlignmentPanel(AlignmentPanel nap)
473   {
474     try
475     {
476       _alignwith.remove(nap);
477       _colourwith.remove(nap);
478       if (getAlignmentPanel() == nap)
479       {
480         setAlignmentPanel(null);
481         for (AlignmentPanel aps : getAllAlignmentPanels())
482         {
483           if (aps != nap)
484           {
485             setAlignmentPanel(aps);
486             break;
487           }
488         }
489       }
490     } catch (Exception ex)
491     {
492     }
493     if (getAlignmentPanel() != null)
494     {
495       buildActionMenu();
496     }
497   }
498
499   public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
500   {
501     addAlignmentPanel(nap);
502     if (!_alignwith.contains(nap))
503     {
504       _alignwith.add(nap);
505     }
506   }
507
508   public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
509   {
510     if (_alignwith.contains(nap))
511     {
512       _alignwith.remove(nap);
513     }
514   }
515
516   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
517           boolean enableColourBySeq)
518   {
519     useAlignmentPanelForColourbyseq(nap);
520     getBinding().setColourBySequence(enableColourBySeq);
521     seqColour.setSelected(enableColourBySeq);
522     viewerColour.setSelected(!enableColourBySeq);
523   }
524
525   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
526   {
527     addAlignmentPanel(nap);
528     if (!_colourwith.contains(nap))
529     {
530       _colourwith.add(nap);
531     }
532   }
533
534   public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
535   {
536     if (_colourwith.contains(nap))
537     {
538       _colourwith.remove(nap);
539     }
540   }
541
542   /**
543    * pdb retrieval thread.
544    */
545   private Thread worker = null;
546
547   /**
548    * add a new structure (with associated sequences and chains) to this viewer,
549    * retrieving it if necessary first.
550    * 
551    * @param pdbentry
552    * @param seq
553    * @param chains
554    * @param alignFrame
555    * @param align
556    *          if true, new structure(s) will be align using associated alignment
557    */
558   private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
559           final String[] chains, final boolean b,
560           final IProgressIndicator alignFrame)
561   {
562     if (pdbentry.getFile() == null)
563     {
564       if (worker != null && worker.isAlive())
565       {
566         // a retrieval is in progress, wait around and add ourselves to the
567         // queue.
568         new Thread(new Runnable()
569         {
570           public void run()
571           {
572             while (worker != null && worker.isAlive() && _started)
573             {
574               try
575               {
576                 Thread.sleep(100 + ((int) Math.random() * 100));
577
578               } catch (Exception e)
579               {
580               }
581
582             }
583             // and call ourselves again.
584             addStructure(pdbentry, seq, chains, b, alignFrame);
585           }
586         }).start();
587         return;
588       }
589     }
590     // otherwise, start adding the structure.
591     jmb.addSequenceAndChain(new PDBEntry[]
592     { pdbentry }, new SequenceI[][]
593     { seq }, new String[][]
594     { chains });
595     addingStructures = true;
596     _started = false;
597     alignAddedStructures = b;
598     progressBar = alignFrame; // visual indication happens on caller frame.
599     (worker = new Thread(this)).start();
600     return;
601   }
602
603   private Vector getJmolsFor(AlignmentPanel apanel)
604   {
605     Vector result = new Vector();
606     JInternalFrame[] frames = Desktop.instance.getAllFrames();
607
608     for (JInternalFrame frame : frames)
609     {
610       if (frame instanceof AppJmol)
611       {
612         if (((StructureViewerBase) frame).isLinkedWith(apanel))
613         {
614           result.addElement(frame);
615         }
616       }
617     }
618     return result;
619   }
620
621   void initJmol(String command)
622   {
623     jmb.setFinishedInit(false);
624     renderPanel = new RenderPanel();
625     // TODO: consider waiting until the structure/view is fully loaded before
626     // displaying
627     this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
628     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
629             getBounds().width, getBounds().height);
630     if (scriptWindow == null)
631     {
632       BorderLayout bl = new BorderLayout();
633       bl.setHgap(0);
634       bl.setVgap(0);
635       scriptWindow = new JPanel(bl);
636       scriptWindow.setVisible(false);
637     }
638     ;
639     jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
640             null);
641     jmb.newJmolPopup(true, "Jmol", true);
642     if (command == null)
643     {
644       command = "";
645     }
646     jmb.evalStateCommand(command);
647     jmb.setFinishedInit(true);
648   }
649
650   void setChainMenuItems(Vector chains)
651   {
652     chainMenu.removeAll();
653     if (chains == null)
654     {
655       return;
656     }
657     JMenuItem menuItem = new JMenuItem(
658             MessageManager.getString("label.all"));
659     menuItem.addActionListener(new ActionListener()
660     {
661       public void actionPerformed(ActionEvent evt)
662       {
663         allChainsSelected = true;
664         for (int i = 0; i < chainMenu.getItemCount(); i++)
665         {
666           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
667           {
668             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
669           }
670         }
671         centerViewer();
672         allChainsSelected = false;
673       }
674     });
675
676     chainMenu.add(menuItem);
677
678     for (int c = 0; c < chains.size(); c++)
679     {
680       menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
681       menuItem.addItemListener(new ItemListener()
682       {
683         public void itemStateChanged(ItemEvent evt)
684         {
685           if (!allChainsSelected)
686           {
687             centerViewer();
688           }
689         }
690       });
691
692       chainMenu.add(menuItem);
693     }
694   }
695
696   boolean allChainsSelected = false;
697
698   private boolean alignAddedStructures = false;
699
700   void centerViewer()
701   {
702     Vector toshow = new Vector();
703     String lbl;
704     int mlength, p, mnum;
705     for (int i = 0; i < chainMenu.getItemCount(); i++)
706     {
707       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
708       {
709         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
710         if (item.isSelected())
711         {
712           toshow.addElement(item.getText());
713         }
714       }
715     }
716     jmb.centerViewer(toshow);
717   }
718
719   public void closeViewer()
720   {
721     jmb.closeViewer();
722     setAlignmentPanel(null);
723     _aps.clear();
724     _alignwith.clear();
725     _colourwith.clear();
726     // TODO: check for memory leaks where instance isn't finalised because jmb
727     // holds a reference to the window
728     jmb = null;
729   }
730
731   /**
732    * state flag for PDB retrieval thread
733    */
734   private boolean _started = false;
735
736   public void run()
737   {
738     _started = true;
739     String pdbid = "";
740     // todo - record which pdbids were successfuly imported.
741     StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
742     try
743     {
744       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
745       // TODO: replace with reference fetching/transfer code (validate PDBentry
746       // as a DBRef?)
747       jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
748       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
749       {
750         String file = jmb.getPdbEntry(pi).getFile();
751         if (file == null)
752         {
753           // retrieve the pdb and store it locally
754           AlignmentI pdbseq = null;
755           pdbid = jmb.getPdbEntry(pi).getId();
756           long hdl = pdbid.hashCode() - System.currentTimeMillis();
757           if (progressBar != null)
758           {
759             progressBar.setProgressBar(MessageManager.formatMessage("status.fetching_pdb", new String[]{pdbid}), hdl);
760           }
761           try
762           {
763             pdbseq = pdbclient.getSequenceRecords(pdbid = jmb.getPdbEntry(
764                     pi)
765                     .getId());
766           } catch (OutOfMemoryError oomerror)
767           {
768             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
769           } catch (Exception ex)
770           {
771             ex.printStackTrace();
772             errormsgs.append("'" + pdbid + "'");
773           }
774           if (progressBar != null)
775           {
776             progressBar.setProgressBar(MessageManager.getString("label.state_completed"), hdl);
777           }
778           if (pdbseq != null)
779           {
780             // just transfer the file name from the first sequence's first
781             // PDBEntry
782             file = new File(((PDBEntry) pdbseq.getSequenceAt(0).getPDBId()
783                     .elementAt(0)).getFile()).getAbsolutePath();
784             jmb.getPdbEntry(pi).setFile(file);
785
786             files.append(" \"" + Platform.escapeString(file) + "\"");
787           }
788           else
789           {
790             errormsgs.append("'" + pdbid + "' ");
791           }
792         }
793         else
794         {
795           if (curfiles != null && curfiles.length > 0)
796           {
797             addingStructures = true; // already files loaded.
798             for (int c = 0; c < curfiles.length; c++)
799             {
800               if (curfiles[c].equals(file))
801               {
802                 file = null;
803                 break;
804               }
805             }
806           }
807           if (file != null)
808           {
809             files.append(" \"" + Platform.escapeString(file) + "\"");
810           }
811         }
812       }
813     } catch (OutOfMemoryError oomerror)
814     {
815       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
816     } catch (Exception ex)
817     {
818       ex.printStackTrace();
819       errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
820               + "'");
821     }
822     if (errormsgs.length() > 0)
823     {
824
825       JOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
826               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
827                       new String[]
828                       { errormsgs.toString() }), MessageManager
829               .getString("label.couldnt_load_file"),
830               JOptionPane.ERROR_MESSAGE);
831
832     }
833     long lastnotify = jmb.getLoadNotifiesHandled();
834     if (files.length() > 0)
835     {
836       if (!addingStructures)
837       {
838
839         try
840         {
841           initJmol("load FILES " + files.toString());
842         } catch (OutOfMemoryError oomerror)
843         {
844           new OOMWarning("When trying to open the Jmol viewer!", oomerror);
845           Cache.log.debug("File locations are " + files);
846         } catch (Exception ex)
847         {
848           Cache.log.error("Couldn't open Jmol viewer!", ex);
849         }
850       }
851       else
852       {
853         StringBuffer cmd = new StringBuffer();
854         cmd.append("loadingJalviewdata=true\nload APPEND ");
855         cmd.append(files.toString());
856         cmd.append("\nloadingJalviewdata=null");
857         final String command = cmd.toString();
858         cmd = null;
859         lastnotify = jmb.getLoadNotifiesHandled();
860
861         try
862         {
863           jmb.evalStateCommand(command);
864         } catch (OutOfMemoryError oomerror)
865         {
866           new OOMWarning(
867                   "When trying to add structures to the Jmol viewer!",
868                   oomerror);
869           Cache.log.debug("File locations are " + files);
870         } catch (Exception ex)
871         {
872           Cache.log.error("Couldn't add files to Jmol viewer!", ex);
873         }
874       }
875
876       // need to wait around until script has finished
877       while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
878               : (jmb.isFinishedInit() && jmb.getPdbFile() != null && jmb
879                       .getPdbFile().length != jmb.getPdbCount()))
880       {
881         try
882         {
883           Cache.log.debug("Waiting around for jmb notify.");
884           Thread.sleep(35);
885         } catch (Exception e)
886         {
887         }
888       }
889       // refresh the sequence colours for the new structure(s)
890       for (AlignmentPanel ap : _colourwith)
891       {
892         jmb.updateColours(ap);
893       }
894       // do superposition if asked to
895       if (alignAddedStructures)
896       {
897         javax.swing.SwingUtilities.invokeLater(new Runnable()
898         {
899           public void run()
900           {
901             alignStructs_withAllAlignPanels();
902             // jmb.superposeStructures(ap.av.getAlignment(), -1, null);
903           }
904         });
905         alignAddedStructures = false;
906       }
907       addingStructures = false;
908
909     }
910     _started = false;
911     worker = null;
912   }
913
914   @Override
915   public void pdbFile_actionPerformed(ActionEvent actionEvent)
916   {
917     JalviewFileChooser chooser = new JalviewFileChooser(
918             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
919
920     chooser.setFileView(new JalviewFileView());
921     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
922     chooser.setToolTipText(MessageManager.getString("action.save"));
923
924     int value = chooser.showSaveDialog(this);
925
926     if (value == JalviewFileChooser.APPROVE_OPTION)
927     {
928       try
929       {
930         // TODO: cope with multiple PDB files in view
931         BufferedReader in = new BufferedReader(new FileReader(
932                 jmb.getPdbFile()[0]));
933         File outFile = chooser.getSelectedFile();
934
935         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
936         String data;
937         while ((data = in.readLine()) != null)
938         {
939           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
940           {
941             out.println(data);
942           }
943         }
944         out.close();
945       } catch (Exception ex)
946       {
947         ex.printStackTrace();
948       }
949     }
950   }
951
952   @Override
953   public void viewMapping_actionPerformed(ActionEvent actionEvent)
954   {
955     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
956     try
957     {
958       for (int pdbe = 0; pdbe < jmb.getPdbCount(); pdbe++)
959       {
960         cap.appendText(jmb.printMapping(jmb.getPdbEntry(pdbe).getFile()));
961         cap.appendText("\n");
962       }
963     } catch (OutOfMemoryError e)
964     {
965       new OOMWarning(
966               "composing sequence-structure alignments for display in text box.",
967               e);
968       cap.dispose();
969       return;
970     }
971     jalview.gui.Desktop.addInternalFrame(cap,
972             MessageManager.getString("label.pdb_sequence_mapping"), 550,
973             600);
974   }
975
976   @Override
977   public void eps_actionPerformed(ActionEvent e)
978   {
979     makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
980   }
981
982   @Override
983   public void png_actionPerformed(ActionEvent e)
984   {
985     makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
986   }
987
988   void makePDBImage(jalview.util.ImageMaker.TYPE type)
989   {
990     int width = getWidth();
991     int height = getHeight();
992
993     jalview.util.ImageMaker im;
994
995     if (type == jalview.util.ImageMaker.TYPE.PNG)
996     {
997       im = new jalview.util.ImageMaker(this,
998               jalview.util.ImageMaker.TYPE.PNG,
999               "Make PNG image from view", width, height, null, null);
1000     }
1001     else if (type == jalview.util.ImageMaker.TYPE.EPS)
1002     {
1003       im = new jalview.util.ImageMaker(this,
1004               jalview.util.ImageMaker.TYPE.EPS,
1005               "Make EPS file from view", width, height, null,
1006               this.getTitle());
1007     }
1008     else
1009     {
1010
1011       im = new jalview.util.ImageMaker(this,
1012               jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
1013               width, height, null, this.getTitle());
1014     }
1015
1016     if (im.getGraphics() != null)
1017     {
1018       Rectangle rect = new Rectangle(width, height);
1019       jmb.viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
1020       im.writeImage();
1021     }
1022   }
1023
1024   @Override
1025   public void viewerColour_actionPerformed(ActionEvent actionEvent)
1026   {
1027     if (viewerColour.isSelected())
1028     {
1029       // disable automatic sequence colouring.
1030       jmb.setColourBySequence(false);
1031     }
1032   }
1033
1034   @Override
1035   public void seqColour_actionPerformed(ActionEvent actionEvent)
1036   {
1037     jmb.setColourBySequence(seqColour.isSelected());
1038     if (_colourwith == null)
1039     {
1040       _colourwith = new Vector<AlignmentPanel>();
1041     }
1042     if (jmb.isColourBySequence())
1043     {
1044       if (!jmb.isLoadingFromArchive())
1045       {
1046         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
1047         {
1048           // Make the currently displayed alignment panel the associated view
1049           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
1050         }
1051       }
1052       // Set the colour using the current view for the associated alignframe
1053       for (AlignmentPanel ap : _colourwith)
1054       {
1055         jmb.colourBySequence(ap.av.showSequenceFeatures, ap);
1056       }
1057     }
1058   }
1059
1060   @Override
1061   public void chainColour_actionPerformed(ActionEvent actionEvent)
1062   {
1063     chainColour.setSelected(true);
1064     jmb.colourByChain();
1065   }
1066
1067   @Override
1068   public void chargeColour_actionPerformed(ActionEvent actionEvent)
1069   {
1070     chargeColour.setSelected(true);
1071     jmb.colourByCharge();
1072   }
1073
1074   @Override
1075   public void zappoColour_actionPerformed(ActionEvent actionEvent)
1076   {
1077     zappoColour.setSelected(true);
1078     jmb.setJalviewColourScheme(new ZappoColourScheme());
1079   }
1080
1081   @Override
1082   public void taylorColour_actionPerformed(ActionEvent actionEvent)
1083   {
1084     taylorColour.setSelected(true);
1085     jmb.setJalviewColourScheme(new TaylorColourScheme());
1086   }
1087
1088   @Override
1089   public void hydroColour_actionPerformed(ActionEvent actionEvent)
1090   {
1091     hydroColour.setSelected(true);
1092     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
1093   }
1094
1095   @Override
1096   public void helixColour_actionPerformed(ActionEvent actionEvent)
1097   {
1098     helixColour.setSelected(true);
1099     jmb.setJalviewColourScheme(new HelixColourScheme());
1100   }
1101
1102   @Override
1103   public void strandColour_actionPerformed(ActionEvent actionEvent)
1104   {
1105     strandColour.setSelected(true);
1106     jmb.setJalviewColourScheme(new StrandColourScheme());
1107   }
1108
1109   @Override
1110   public void turnColour_actionPerformed(ActionEvent actionEvent)
1111   {
1112     turnColour.setSelected(true);
1113     jmb.setJalviewColourScheme(new TurnColourScheme());
1114   }
1115
1116   @Override
1117   public void buriedColour_actionPerformed(ActionEvent actionEvent)
1118   {
1119     buriedColour.setSelected(true);
1120     jmb.setJalviewColourScheme(new BuriedColourScheme());
1121   }
1122
1123   @Override
1124   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
1125   {
1126     setJalviewColourScheme(new PurinePyrimidineColourScheme());
1127   }
1128
1129   @Override
1130   public void userColour_actionPerformed(ActionEvent actionEvent)
1131   {
1132     userColour.setSelected(true);
1133     new UserDefinedColours(this, null);
1134   }
1135
1136   @Override
1137   public void backGround_actionPerformed(ActionEvent actionEvent)
1138   {
1139     java.awt.Color col = JColorChooser.showDialog(this,
1140             MessageManager.getString("label.select_backgroud_colour"), null);
1141     if (col != null)
1142     {
1143       jmb.setBackgroundColour(col);
1144     }
1145   }
1146
1147   @Override
1148   public void showHelp_actionPerformed(ActionEvent actionEvent)
1149   {
1150     try
1151     {
1152       jalview.util.BrowserLauncher
1153               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
1154     } catch (Exception ex)
1155     {
1156     }
1157   }
1158
1159   public void showConsole(boolean showConsole)
1160   {
1161
1162     if (showConsole)
1163     {
1164       if (splitPane == null)
1165       {
1166         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1167         splitPane.setTopComponent(renderPanel);
1168         splitPane.setBottomComponent(scriptWindow);
1169         this.getContentPane().add(splitPane, BorderLayout.CENTER);
1170         splitPane.setDividerLocation(getHeight() - 200);
1171         scriptWindow.setVisible(true);
1172         scriptWindow.validate();
1173         splitPane.validate();
1174       }
1175
1176     }
1177     else
1178     {
1179       if (splitPane != null)
1180       {
1181         splitPane.setVisible(false);
1182       }
1183
1184       splitPane = null;
1185
1186       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1187     }
1188
1189     validate();
1190   }
1191
1192   class RenderPanel extends JPanel
1193   {
1194     final Dimension currentSize = new Dimension();
1195
1196     final Rectangle rectClip = new Rectangle();
1197
1198     public void paintComponent(Graphics g)
1199     {
1200       getSize(currentSize);
1201       g.getClipBounds(rectClip);
1202
1203       if (jmb.fileLoadingError != null)
1204       {
1205         g.setColor(Color.black);
1206         g.fillRect(0, 0, currentSize.width, currentSize.height);
1207         g.setColor(Color.white);
1208         g.setFont(new Font("Verdana", Font.BOLD, 14));
1209         g.drawString(MessageManager.getString("label.error_loading_file")
1210                 + "...", 20, currentSize.height / 2);
1211         StringBuffer sb = new StringBuffer();
1212         int lines = 0;
1213         for (int e = 0; e < jmb.getPdbCount(); e++)
1214         {
1215           sb.append(jmb.getPdbEntry(e).getId());
1216           if (e < jmb.getPdbCount() - 1)
1217           {
1218             sb.append(",");
1219           }
1220
1221           if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
1222           {
1223             lines++;
1224             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1225                     * g.getFontMetrics().getHeight());
1226           }
1227         }
1228       }
1229       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1230       {
1231         g.setColor(Color.black);
1232         g.fillRect(0, 0, currentSize.width, currentSize.height);
1233         g.setColor(Color.white);
1234         g.setFont(new Font("Verdana", Font.BOLD, 14));
1235         g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
1236                 20, currentSize.height / 2);
1237       }
1238       else
1239       {
1240         jmb.viewer.renderScreenImage(g, currentSize, rectClip);
1241       }
1242     }
1243   }
1244
1245   public void updateTitleAndMenus()
1246   {
1247     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1248     {
1249       repaint();
1250       return;
1251     }
1252     setChainMenuItems(jmb.chainNames);
1253
1254     this.setTitle(jmb.getViewerTitle());
1255     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
1256     {
1257       viewerActionMenu.setVisible(true);
1258     }
1259     if (!jmb.isLoadingFromArchive())
1260     {
1261       seqColour_actionPerformed(null);
1262     }
1263   }
1264
1265   /*
1266    * (non-Javadoc)
1267    * 
1268    * @see
1269    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1270    * .ActionEvent)
1271    */
1272   @Override
1273   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1274   {
1275     alignStructs_withAllAlignPanels();
1276   }
1277
1278   private void alignStructs_withAllAlignPanels()
1279   {
1280     if (getAlignmentPanel() == null)
1281     {
1282       return;
1283     }
1284     ;
1285     if (_alignwith.size() == 0)
1286     {
1287       _alignwith.add(getAlignmentPanel());
1288     }
1289     ;
1290     try
1291     {
1292       AlignmentI[] als = new Alignment[_alignwith.size()];
1293       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1294       int[] alm = new int[_alignwith.size()];
1295       int a = 0;
1296
1297       for (AlignmentPanel ap : _alignwith)
1298       {
1299         als[a] = ap.av.getAlignment();
1300         alm[a] = -1;
1301         alc[a++] = ap.av.getColumnSelection();
1302       }
1303       jmb.superposeStructures(als, alm, alc);
1304     } catch (Exception e)
1305     {
1306       StringBuffer sp = new StringBuffer();
1307       for (AlignmentPanel ap : _alignwith)
1308       {
1309         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1310       }
1311       Cache.log.info("Couldn't align structures with the " + sp.toString()
1312               + "associated alignment panels.", e);
1313
1314     }
1315
1316   }
1317
1318   public void setJalviewColourScheme(ColourSchemeI ucs)
1319   {
1320     jmb.setJalviewColourScheme(ucs);
1321
1322   }
1323
1324   /**
1325    * 
1326    * @param alignment
1327    * @return first alignment panel displaying given alignment, or the default
1328    *         alignment panel
1329    */
1330   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1331   {
1332     for (AlignmentPanel ap : getAllAlignmentPanels())
1333     {
1334       if (ap.av.getAlignment() == alignment)
1335       {
1336         return ap;
1337       }
1338     }
1339     return getAlignmentPanel();
1340   }
1341
1342   @Override
1343   public AAStructureBindingModel getBinding()
1344   {
1345     return this.jmb;
1346   }
1347
1348   @Override
1349   public String getStateInfo()
1350   {
1351     return jmb == null ? null : jmb.viewer.getStateInfo();
1352   }
1353
1354 }