cc431acf64a0f6b673e17f1678b9d351283097f7
[jalview.git] / src / jalview / gui / StructureViewerBase.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.bin.Cache;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.StructureViewer.ViewerType;
32 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
33 import jalview.io.DataSourceType;
34 import jalview.io.JalviewFileChooser;
35 import jalview.io.JalviewFileView;
36 import jalview.jbgui.GStructureViewer;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.schemes.ColourSchemes;
39 import jalview.structure.StructureMapping;
40 import jalview.structures.models.AAStructureBindingModel;
41 import jalview.util.MessageManager;
42
43 import java.awt.Color;
44 import java.awt.Component;
45 import java.awt.event.ActionEvent;
46 import java.awt.event.ActionListener;
47 import java.awt.event.ItemEvent;
48 import java.awt.event.ItemListener;
49 import java.io.BufferedReader;
50 import java.io.File;
51 import java.io.FileOutputStream;
52 import java.io.FileReader;
53 import java.io.IOException;
54 import java.io.PrintWriter;
55 import java.util.ArrayList;
56 import java.util.List;
57 import java.util.Vector;
58
59 import javax.swing.ButtonGroup;
60 import javax.swing.JCheckBoxMenuItem;
61 import javax.swing.JColorChooser;
62 import javax.swing.JMenu;
63 import javax.swing.JMenuItem;
64 import javax.swing.JRadioButtonMenuItem;
65 import javax.swing.event.MenuEvent;
66 import javax.swing.event.MenuListener;
67
68 /**
69  * Base class with common functionality for JMol, Chimera or other structure
70  * viewers.
71  * 
72  * @author gmcarstairs
73  *
74  */
75 public abstract class StructureViewerBase extends GStructureViewer
76         implements Runnable, ViewSetProvider
77 {
78   /*
79    * names for colour options (additional to Jalview colour schemes)
80    */
81   enum ViewerColour
82   {
83     BySequence, ByChain, ChargeCysteine, ByViewer
84   }
85
86   /**
87    * list of sequenceSet ids associated with the view
88    */
89   protected List<String> _aps = new ArrayList<>();
90
91   /**
92    * list of alignment panels to use for superposition
93    */
94   protected Vector<AlignmentViewPanel> _alignwith = new Vector<>();
95
96   /**
97    * list of alignment panels that are used for colouring structures by aligned
98    * sequences
99    */
100   protected Vector<AlignmentViewPanel> _colourwith = new Vector<>();
101
102   private String viewId = null;
103
104   private AlignmentPanel ap;
105
106   protected boolean alignAddedStructures = false;
107
108   protected volatile boolean _started = false;
109
110   protected volatile boolean addingStructures = false;
111
112   protected Thread worker = null;
113
114   protected boolean allChainsSelected = false;
115
116   protected JMenu viewSelectionMenu;
117
118   /**
119    * set after sequence colouring has been applied for this structure viewer.
120    * used to determine if the final sequence/structure mapping has been
121    * determined
122    */
123   protected volatile boolean seqColoursApplied = false;
124
125   /**
126    * Default constructor
127    */
128   public StructureViewerBase()
129   {
130     super();
131   }
132
133   /**
134    * @return true if added structures should be aligned to existing one(s)
135    */
136   @Override
137   public boolean isAlignAddedStructures()
138   {
139     return alignAddedStructures;
140   }
141
142   /**
143    * 
144    * @param true
145    *          if added structures should be aligned to existing one(s)
146    */
147   @Override
148   public void setAlignAddedStructures(boolean alignAdded)
149   {
150     alignAddedStructures = alignAdded;
151   }
152
153   /**
154    * 
155    * @param ap2
156    * @return true if this Jmol instance is linked with the given alignPanel
157    */
158   public boolean isLinkedWith(AlignmentPanel ap2)
159   {
160     return _aps.contains(ap2.av.getSequenceSetId());
161   }
162
163   public boolean isUsedforaligment(AlignmentPanel ap2)
164   {
165
166     return (_alignwith != null) && _alignwith.contains(ap2);
167   }
168
169   @Override
170   public boolean isUsedforcolourby(AlignmentViewPanel avp)
171   {
172     return (_colourwith != null) && _colourwith.contains(avp);
173   }
174
175   /**
176    * 
177    * @return TRUE if the view is NOT being coloured by the alignment colours.
178    */
179   public boolean isColouredByViewer()
180   {
181     return !getBinding().isColourBySequence();
182   }
183
184   public String getViewId()
185   {
186     if (viewId == null)
187     {
188       viewId = System.currentTimeMillis() + "." + this.hashCode();
189     }
190     return viewId;
191   }
192
193   protected void setViewId(String viewId)
194   {
195     this.viewId = viewId;
196   }
197
198   public abstract String getStateInfo();
199
200   protected void buildActionMenu()
201   {
202     if (_alignwith == null)
203     {
204       _alignwith = new Vector<>();
205     }
206     if (_alignwith.size() == 0 && ap != null)
207     {
208       _alignwith.add(ap);
209     }
210     ;
211     for (Component c : viewerActionMenu.getMenuComponents())
212     {
213       if (c != alignStructs)
214       {
215         viewerActionMenu.remove((JMenuItem) c);
216       }
217     }
218   }
219
220   public AlignmentPanel getAlignmentPanel()
221   {
222     return ap;
223   }
224
225   protected void setAlignmentPanel(AlignmentPanel alp)
226   {
227     this.ap = alp;
228   }
229
230   @Override
231   public AlignmentPanel[] getAllAlignmentPanels()
232   {
233     AlignmentPanel[] t, list = new AlignmentPanel[0];
234     for (String setid : _aps)
235     {
236       AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
237       if (panels != null)
238       {
239         t = new AlignmentPanel[list.length + panels.length];
240         System.arraycopy(list, 0, t, 0, list.length);
241         System.arraycopy(panels, 0, t, list.length, panels.length);
242         list = t;
243       }
244     }
245
246     return list;
247   }
248
249   /**
250    * set the primary alignmentPanel reference and add another alignPanel to the
251    * list of ones to use for colouring and aligning
252    * 
253    * @param nap
254    */
255   public void addAlignmentPanel(AlignmentPanel nap)
256   {
257     if (getAlignmentPanel() == null)
258     {
259       setAlignmentPanel(nap);
260     }
261     if (!_aps.contains(nap.av.getSequenceSetId()))
262     {
263       _aps.add(nap.av.getSequenceSetId());
264     }
265   }
266
267   /**
268    * remove any references held to the given alignment panel
269    * 
270    * @param nap
271    */
272   public void removeAlignmentPanel(AlignmentPanel nap)
273   {
274     try
275     {
276       _alignwith.remove(nap);
277       _colourwith.remove(nap);
278       if (getAlignmentPanel() == nap)
279       {
280         setAlignmentPanel(null);
281         for (AlignmentPanel aps : getAllAlignmentPanels())
282         {
283           if (aps != nap)
284           {
285             setAlignmentPanel(aps);
286             break;
287           }
288         }
289       }
290     } catch (Exception ex)
291     {
292     }
293     if (getAlignmentPanel() != null)
294     {
295       buildActionMenu();
296     }
297   }
298
299   public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
300   {
301     addAlignmentPanel(nap);
302     if (!_alignwith.contains(nap))
303     {
304       _alignwith.add(nap);
305     }
306   }
307
308   public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
309   {
310     if (_alignwith.contains(nap))
311     {
312       _alignwith.remove(nap);
313     }
314   }
315
316   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
317           boolean enableColourBySeq)
318   {
319     useAlignmentPanelForColourbyseq(nap);
320     getBinding().setColourBySequence(enableColourBySeq);
321     seqColour.setSelected(enableColourBySeq);
322     viewerColour.setSelected(!enableColourBySeq);
323   }
324
325   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
326   {
327     addAlignmentPanel(nap);
328     if (!_colourwith.contains(nap))
329     {
330       _colourwith.add(nap);
331     }
332   }
333
334   public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
335   {
336     if (_colourwith.contains(nap))
337     {
338       _colourwith.remove(nap);
339     }
340   }
341
342   public abstract ViewerType getViewerType();
343
344   protected abstract IProgressIndicator getIProgressIndicator();
345
346   /**
347    * add a new structure (with associated sequences and chains) to this viewer,
348    * retrieving it if necessary first.
349    * 
350    * @param pdbentry
351    * @param seqs
352    * @param chains
353    * @param align
354    *          if true, new structure(s) will be aligned using associated
355    *          alignment
356    * @param alignFrame
357    */
358   protected void addStructure(final PDBEntry pdbentry,
359           final SequenceI[] seqs, final String[] chains,
360           final IProgressIndicator alignFrame)
361   {
362     if (pdbentry.getFile() == null)
363     {
364       if (worker != null && worker.isAlive())
365       {
366         // a retrieval is in progress, wait around and add ourselves to the
367         // queue.
368         new Thread(new Runnable()
369         {
370           @Override
371           public void run()
372           {
373             while (worker != null && worker.isAlive() && _started)
374             {
375               try
376               {
377                 Thread.sleep(100 + ((int) Math.random() * 100));
378
379               } catch (Exception e)
380               {
381               }
382             }
383             // and call ourselves again.
384             addStructure(pdbentry, seqs, chains, alignFrame);
385           }
386         }).start();
387         return;
388       }
389     }
390     // otherwise, start adding the structure.
391     getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
392             new SequenceI[][]
393             { seqs }, new String[][] { chains });
394     addingStructures = true;
395     _started = false;
396     worker = new Thread(this);
397     worker.start();
398     return;
399   }
400
401   protected boolean hasPdbId(String pdbId)
402   {
403     return getBinding().hasPdbId(pdbId);
404   }
405
406   /**
407    * Returns a list of any viewer of the instantiated type. The list is
408    * restricted to those linked to the given alignment panel if it is not null.
409    */
410   protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
411   {
412     return Desktop.instance.getStructureViewers(alp, this.getClass());
413   }
414
415   @Override
416   public void addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
417           String[] chains, final AlignmentViewPanel apanel, String pdbId)
418   {
419     /*
420      * JAL-1742 exclude view with this structure already mapped (don't offer
421      * to align chain B to chain A of the same structure); code may defend
422      * against this possibility before we reach here
423      */
424     if (hasPdbId(pdbId))
425     {
426       return;
427     }
428     AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error if this
429                                                  // cast fails
430     useAlignmentPanelForSuperposition(alignPanel);
431     addStructure(pdbentry, seq, chains, alignPanel.alignFrame);
432   }
433
434   /**
435    * Adds mappings for the given sequences to an already opened PDB structure,
436    * and updates any viewers that have the PDB file
437    * 
438    * @param seq
439    * @param chains
440    * @param apanel
441    * @param pdbFilename
442    */
443   public void addSequenceMappingsToStructure(SequenceI[] seq,
444           String[] chains, final AlignmentViewPanel alpanel,
445           String pdbFilename)
446   {
447     AlignmentPanel apanel = (AlignmentPanel) alpanel;
448
449     // TODO : Fix multiple seq to one chain issue here.
450     /*
451      * create the mappings
452      */
453     apanel.getStructureSelectionManager().setMapping(seq, chains,
454             pdbFilename, DataSourceType.FILE, getIProgressIndicator());
455
456     /*
457      * alert the FeatureRenderer to show new (PDB RESNUM) features
458      */
459     if (apanel.getSeqPanel().seqCanvas.fr != null)
460     {
461       apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
462       // note - we don't do a refresh for structure here because we do it
463       // explicitly for all panels later on
464       apanel.paintAlignment(true, false);
465     }
466
467     /*
468      * add the sequences to any other viewers (of the same type) for this pdb
469      * file
470      */
471     // JBPNOTE: this looks like a binding routine, rather than a gui routine
472     for (StructureViewerBase viewer : getViewersFor(null))
473     {
474       AAStructureBindingModel bindingModel = viewer.getBinding();
475       for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
476       {
477         if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
478         {
479           bindingModel.addSequence(pe, seq);
480           viewer.addAlignmentPanel(apanel);
481           /*
482            * add it to the set of alignments used for colouring structure by
483            * sequence
484            */
485           viewer.useAlignmentPanelForColourbyseq(apanel);
486           viewer.buildActionMenu();
487           apanel.getStructureSelectionManager()
488                   .sequenceColoursChanged(apanel);
489           break;
490         }
491       }
492     }
493   }
494
495   @Override
496   public boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
497           final AlignmentViewPanel apanel, String pdbId)
498   {
499     String alreadyMapped = apanel.getStructureSelectionManager()
500             .alreadyMappedToFile(pdbId);
501
502     if (alreadyMapped == null)
503     {
504       return false;
505     }
506
507     addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
508     return true;
509   }
510
511   void setChainMenuItems(List<String> chainNames)
512   {
513     chainMenu.removeAll();
514     if (chainNames == null || chainNames.isEmpty())
515     {
516       return;
517     }
518     JMenuItem menuItem = new JMenuItem(
519             MessageManager.getString("label.all"));
520     menuItem.addActionListener(new ActionListener()
521     {
522       @Override
523       public void actionPerformed(ActionEvent evt)
524       {
525         allChainsSelected = true;
526         for (int i = 0; i < chainMenu.getItemCount(); i++)
527         {
528           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
529           {
530             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
531           }
532         }
533         showSelectedChains();
534         allChainsSelected = false;
535       }
536     });
537
538     chainMenu.add(menuItem);
539
540     for (String chain : chainNames)
541     {
542       menuItem = new JCheckBoxMenuItem(chain, true);
543       menuItem.addItemListener(new ItemListener()
544       {
545         @Override
546         public void itemStateChanged(ItemEvent evt)
547         {
548           if (!allChainsSelected)
549           {
550             showSelectedChains();
551           }
552         }
553       });
554
555       chainMenu.add(menuItem);
556     }
557   }
558
559   abstract void showSelectedChains();
560
561   /**
562    * Action on selecting one of Jalview's registered colour schemes
563    */
564   @Override
565   public void changeColour_actionPerformed(String colourSchemeName)
566   {
567     AlignmentI al = getAlignmentPanel().av.getAlignment();
568     ColourSchemeI cs = ColourSchemes.getInstance()
569             .getColourScheme(colourSchemeName, getAlignmentPanel().av, al,
570                     null);
571     getBinding().setJalviewColourScheme(cs);
572   }
573
574   /**
575    * Builds the colour menu
576    */
577   protected void buildColourMenu()
578   {
579     colourMenu.removeAll();
580     AlignmentI al = getAlignmentPanel().av.getAlignment();
581
582     /*
583      * add colour by sequence, by chain, by charge and cysteine
584      */
585     colourMenu.add(seqColour);
586     colourMenu.add(chainColour);
587     colourMenu.add(chargeColour);
588     chargeColour.setEnabled(!al.isNucleotide());
589
590     /*
591      * add all 'simple' (per-residue) colour schemes registered to Jalview
592      */
593     ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
594             al, true);
595
596     /*
597      * add 'colour by viewer' (menu item text is set in subclasses)
598      */
599     viewerColour.setSelected(false);
600     viewerColour.addActionListener(new ActionListener()
601     {
602       @Override
603       public void actionPerformed(ActionEvent actionEvent)
604       {
605         viewerColour_actionPerformed(actionEvent);
606       }
607     });
608     colourMenu.add(viewerColour);
609
610     /*
611      * add 'set background colour'
612      */
613     JMenuItem backGround = new JMenuItem();
614     backGround
615             .setText(MessageManager.getString("action.background_colour"));
616     backGround.addActionListener(new ActionListener()
617     {
618       @Override
619       public void actionPerformed(ActionEvent actionEvent)
620       {
621         background_actionPerformed(actionEvent);
622       }
623     });
624     colourMenu.add(backGround);
625
626     /*
627      * add colour buttons to a group so their selection is
628      * mutually exclusive (background colour is a separate option)
629      */
630     itemGroup.add(seqColour);
631     itemGroup.add(chainColour);
632     itemGroup.add(chargeColour);
633     itemGroup.add(viewerColour);
634   }
635
636   /**
637    * Construct menu items
638    */
639   protected void initMenus()
640   {
641     AAStructureBindingModel binding = getBinding();
642
643     seqColour = new JRadioButtonMenuItem();
644     seqColour.setText(MessageManager.getString("action.by_sequence"));
645     seqColour.setName(ViewerColour.BySequence.name());
646     seqColour.setSelected(binding.isColourBySequence());
647     seqColour.addActionListener(new ActionListener()
648     {
649       @Override
650       public void actionPerformed(ActionEvent actionEvent)
651       {
652         seqColour_actionPerformed(actionEvent);
653       }
654     });
655
656     chainColour = new JRadioButtonMenuItem();
657     chainColour.setText(MessageManager.getString("action.by_chain"));
658     chainColour.setName(ViewerColour.ByChain.name());
659     chainColour.addActionListener(new ActionListener()
660     {
661       @Override
662       public void actionPerformed(ActionEvent actionEvent)
663       {
664         chainColour_actionPerformed(actionEvent);
665       }
666     });
667
668     chargeColour = new JRadioButtonMenuItem();
669     chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
670     chargeColour.setName(ViewerColour.ChargeCysteine.name());
671     chargeColour.addActionListener(new ActionListener()
672     {
673       @Override
674       public void actionPerformed(ActionEvent actionEvent)
675       {
676         chargeColour_actionPerformed(actionEvent);
677       }
678     });
679
680     viewerColour = new JRadioButtonMenuItem();
681     // text is set in overrides of this method
682     viewerColour.setName(ViewerColour.ByViewer.name());
683     viewerColour.setSelected(!binding.isColourBySequence());
684
685     if (_colourwith == null)
686     {
687       _colourwith = new Vector<>();
688     }
689     if (_alignwith == null)
690     {
691       _alignwith = new Vector<>();
692     }
693
694     ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
695             MessageManager.getString("label.colour_by"), this, _colourwith,
696             new ItemListener()
697             {
698               @Override
699               public void itemStateChanged(ItemEvent e)
700               {
701                 if (!seqColour.isSelected())
702                 {
703                   seqColour.doClick();
704                 }
705                 else
706                 {
707                   // update the Chimera display now.
708                   seqColour_actionPerformed(null);
709                 }
710               }
711             });
712     viewMenu.add(seqColourBy);
713
714     showAlignmentOnly = new JCheckBoxMenuItem("Visible alignment only");
715     showAlignmentOnly.addActionListener(new ActionListener()
716     {
717       @Override
718       public void actionPerformed(ActionEvent e)
719       {
720         getBinding().setShowAlignmentOnly(showAlignmentOnly.isSelected());
721         getBinding().showStructures(getAlignmentPanel().getAlignViewport(),
722                 true);
723       }
724     });
725     viewMenu.add(showAlignmentOnly);
726
727     final ItemListener handler = new ItemListener()
728     {
729       @Override
730       public void itemStateChanged(ItemEvent e)
731       {
732         alignStructs.setEnabled(!_alignwith.isEmpty());
733         alignStructs.setToolTipText(MessageManager.formatMessage(
734                 "label.align_structures_using_linked_alignment_views",
735                 _alignwith.size()));
736       }
737     };
738     viewSelectionMenu = new ViewSelectionMenu(
739             MessageManager.getString("label.superpose_with"), this,
740             _alignwith, handler);
741     handler.itemStateChanged(null);
742     viewerActionMenu.add(viewSelectionMenu, 0);
743     viewerActionMenu.addMenuListener(new MenuListener()
744     {
745       @Override
746       public void menuSelected(MenuEvent e)
747       {
748         handler.itemStateChanged(null);
749       }
750
751       @Override
752       public void menuDeselected(MenuEvent e)
753       {
754       }
755
756       @Override
757       public void menuCanceled(MenuEvent e)
758       {
759       }
760     });
761
762     buildColourMenu();
763   }
764
765   @Override
766   public void setJalviewColourScheme(ColourSchemeI cs)
767   {
768     getBinding().setJalviewColourScheme(cs);
769   }
770
771   /**
772    * Sends commands to the structure viewer to superimpose structures based on
773    * currently associated alignments. May optionally return an error message for
774    * the operation.
775    */
776   @Override
777   protected String alignStructs_actionPerformed(ActionEvent actionEvent)
778   {
779     return alignStructs_withAllAlignPanels();
780   }
781
782   protected String alignStructs_withAllAlignPanels()
783   {
784     if (getAlignmentPanel() == null)
785     {
786       return null;
787     }
788
789     if (_alignwith.size() == 0)
790     {
791       _alignwith.add(getAlignmentPanel());
792     }
793
794     String reply = null;
795     try
796     {
797       AlignmentI[] als = new Alignment[_alignwith.size()];
798       HiddenColumns[] alc = new HiddenColumns[_alignwith.size()];
799       int[] alm = new int[_alignwith.size()];
800       int a = 0;
801
802       for (AlignmentViewPanel alignPanel : _alignwith)
803       {
804         AlignViewportI av = alignPanel.getAlignViewport();
805         als[a] = av.getAlignment();
806         alm[a] = -1;
807         alc[a++] = av.getAlignment().getHiddenColumns();
808       }
809       reply = getBinding().superposeStructures(als, alm, alc);
810       if (reply != null)
811       {
812         String text = MessageManager
813                 .formatMessage("error.superposition_failed", reply);
814         statusBar.setText(text);
815       }
816     } catch (Exception e)
817     {
818       StringBuffer sp = new StringBuffer();
819       for (AlignmentViewPanel avp : _alignwith)
820       {
821         sp.append(
822                 "'" + ((AlignmentPanel) avp).alignFrame.getTitle() + "' ");
823       }
824       Cache.log.info("Couldn't align structures with the " + sp.toString()
825               + "associated alignment panels.", e);
826     }
827     return reply;
828   }
829
830   @Override
831   public void background_actionPerformed(ActionEvent actionEvent)
832   {
833     Color col = JColorChooser.showDialog(this,
834             MessageManager.getString("label.select_background_colour"),
835             null);
836     if (col != null)
837     {
838       getBinding().setBackgroundColour(col);
839     }
840   }
841
842   @Override
843   public void viewerColour_actionPerformed(ActionEvent actionEvent)
844   {
845     if (viewerColour.isSelected())
846     {
847       // disable automatic sequence colouring.
848       getBinding().setColourBySequence(false);
849     }
850   }
851
852   @Override
853   public void chainColour_actionPerformed(ActionEvent actionEvent)
854   {
855     chainColour.setSelected(true);
856     getBinding().colourByChain();
857   }
858
859   @Override
860   public void chargeColour_actionPerformed(ActionEvent actionEvent)
861   {
862     chargeColour.setSelected(true);
863     getBinding().colourByCharge();
864   }
865
866   @Override
867   public void seqColour_actionPerformed(ActionEvent actionEvent)
868   {
869     AAStructureBindingModel binding = getBinding();
870     binding.setColourBySequence(seqColour.isSelected());
871     if (_colourwith == null)
872     {
873       _colourwith = new Vector<>();
874     }
875     if (binding.isColourBySequence())
876     {
877       if (!binding.isLoadingFromArchive())
878       {
879         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
880         {
881           // Make the currently displayed alignment panel the associated view
882           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
883         }
884       }
885       // Set the colour using the current view for the associated alignframe
886       for (AlignmentViewPanel avp : _colourwith)
887       {
888         binding.colourBySequence(avp);
889       }
890       seqColoursApplied = true;
891     }
892   }
893
894   @Override
895   public void pdbFile_actionPerformed(ActionEvent actionEvent)
896   {
897     JalviewFileChooser chooser = new JalviewFileChooser(
898             Cache.getProperty("LAST_DIRECTORY"));
899
900     chooser.setFileView(new JalviewFileView());
901     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
902     chooser.setToolTipText(MessageManager.getString("action.save"));
903
904     int value = chooser.showSaveDialog(this);
905
906     if (value == JalviewFileChooser.APPROVE_OPTION)
907     {
908       BufferedReader in = null;
909       try
910       {
911         // TODO: cope with multiple PDB files in view
912         in = new BufferedReader(
913                 new FileReader(getBinding().getStructureFiles()[0]));
914         File outFile = chooser.getSelectedFile();
915
916         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
917         String data;
918         while ((data = in.readLine()) != null)
919         {
920           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
921           {
922             out.println(data);
923           }
924         }
925         out.close();
926       } catch (Exception ex)
927       {
928         ex.printStackTrace();
929       } finally
930       {
931         if (in != null)
932         {
933           try
934           {
935             in.close();
936           } catch (IOException e)
937           {
938             // ignore
939           }
940         }
941       }
942     }
943   }
944
945   @Override
946   public void viewMapping_actionPerformed(ActionEvent actionEvent)
947   {
948     CutAndPasteTransfer cap = new CutAndPasteTransfer();
949     try
950     {
951       cap.appendText(getBinding().printMappings());
952     } catch (OutOfMemoryError e)
953     {
954       new OOMWarning(
955               "composing sequence-structure alignments for display in text box.",
956               e);
957       cap.dispose();
958       return;
959     }
960     Desktop.addInternalFrame(cap,
961             MessageManager.getString("label.pdb_sequence_mapping"), 550,
962             600);
963   }
964
965   protected abstract String getViewerName();
966
967   /**
968    * Configures the title and menu items of the viewer panel.
969    */
970   @Override
971   public void updateTitleAndMenus()
972   {
973     AAStructureBindingModel binding = getBinding();
974     if (binding.hasFileLoadingError())
975     {
976       repaint();
977       return;
978     }
979     setChainMenuItems(binding.getChainNames());
980
981     this.setTitle(binding.getViewerTitle(getViewerName(), true));
982
983     /*
984      * enable 'Superpose with' if more than one mapped structure
985      */
986     viewSelectionMenu.setEnabled(false);
987     if (getBinding().getStructureFiles().length > 1
988             && getBinding().getSequence().length > 1)
989     {
990       viewSelectionMenu.setEnabled(true);
991     }
992
993     /*
994      * Show action menu if it has any enabled items
995      */
996     viewerActionMenu.setVisible(false);
997     for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
998     {
999       if (viewerActionMenu.getItem(i).isEnabled())
1000       {
1001         viewerActionMenu.setVisible(true);
1002         break;
1003       }
1004     }
1005
1006     if (!binding.isLoadingFromArchive())
1007     {
1008       seqColour_actionPerformed(null);
1009     }
1010   }
1011
1012   @Override
1013   public String toString()
1014   {
1015     return getTitle();
1016   }
1017
1018   @Override
1019   public boolean hasMapping()
1020   {
1021     if (worker != null && (addingStructures || _started))
1022     {
1023       return false;
1024     }
1025     if (getBinding() == null)
1026     {
1027       if (_aps == null || _aps.size() == 0)
1028       {
1029         // viewer has been closed, but we did at some point run.
1030         return true;
1031       }
1032       return false;
1033     }
1034     String[] pdbids = getBinding().getStructureFiles();
1035     if (pdbids == null)
1036     {
1037       return false;
1038     }
1039     int p=0;
1040     for (String pdbid:pdbids) {
1041       StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1042       if (sm!=null && sm.length>0 && sm[0]!=null) {
1043         p++;
1044       }
1045     }
1046     // only return true if there is a mapping for every structure file we have loaded
1047     if (p == 0 || p != pdbids.length)
1048     {
1049       return false;
1050     }
1051     // and that coloring has been applied
1052     return seqColoursApplied;
1053   }
1054
1055   @Override
1056   public void raiseViewer()
1057   {
1058     toFront();
1059   }
1060
1061 }