JAL-3148 SequenceRenderer, ResidueColourFinder overloads and
[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.AlignmentViewPanel;
24 import jalview.bin.Cache;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.HiddenColumns;
28 import jalview.datamodel.PDBEntry;
29 import jalview.datamodel.SequenceI;
30 import jalview.gui.StructureViewer.ViewerType;
31 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
32 import jalview.io.DataSourceType;
33 import jalview.io.JalviewFileChooser;
34 import jalview.io.JalviewFileView;
35 import jalview.jbgui.GStructureViewer;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.ColourSchemes;
38 import jalview.structure.StructureMapping;
39 import jalview.structures.models.AAStructureBindingModel;
40 import jalview.structures.models.AAStructureBindingModel.ColourBy;
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<AlignmentPanel> _alignwith = new Vector<>();
95
96   /**
97    * list of alignment panels that are used for colouring structures by aligned
98    * sequences
99    */
100   protected Vector<AlignmentPanel> _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   public boolean isUsedForColourBy(Object o)
170   {
171     return (_colourwith != null) && _colourwith.contains(o);
172   }
173
174   /**
175    * 
176    * @return TRUE if the view is NOT being coloured by the alignment colours.
177    */
178   public boolean isColouredByViewer()
179   {
180     return !getBinding().isColourBySequence();
181   }
182
183   public String getViewId()
184   {
185     if (viewId == null)
186     {
187       viewId = System.currentTimeMillis() + "." + this.hashCode();
188     }
189     return viewId;
190   }
191
192   protected void setViewId(String viewId)
193   {
194     this.viewId = viewId;
195   }
196
197   public abstract String getStateInfo();
198
199   protected void buildActionMenu()
200   {
201     if (_alignwith == null)
202     {
203       _alignwith = new Vector<>();
204     }
205     if (_alignwith.size() == 0 && ap != null)
206     {
207       _alignwith.add(ap);
208     }
209     ;
210     for (Component c : viewerActionMenu.getMenuComponents())
211     {
212       if (c != alignStructs)
213       {
214         viewerActionMenu.remove((JMenuItem) c);
215       }
216     }
217   }
218
219   public AlignmentPanel getAlignmentPanel()
220   {
221     return ap;
222   }
223
224   protected void setAlignmentPanel(AlignmentPanel alp)
225   {
226     this.ap = alp;
227   }
228
229   @Override
230   public AlignmentPanel[] getAllAlignmentPanels()
231   {
232     AlignmentPanel[] t, list = new AlignmentPanel[0];
233     for (String setid : _aps)
234     {
235       AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
236       if (panels != null)
237       {
238         t = new AlignmentPanel[list.length + panels.length];
239         System.arraycopy(list, 0, t, 0, list.length);
240         System.arraycopy(panels, 0, t, list.length, panels.length);
241         list = t;
242       }
243     }
244
245     return list;
246   }
247
248   /**
249    * set the primary alignmentPanel reference and add another alignPanel to the
250    * list of ones to use for colouring and aligning
251    * 
252    * @param nap
253    */
254   public void addAlignmentPanel(AlignmentPanel nap)
255   {
256     if (getAlignmentPanel() == null)
257     {
258       setAlignmentPanel(nap);
259     }
260     if (!_aps.contains(nap.av.getSequenceSetId()))
261     {
262       _aps.add(nap.av.getSequenceSetId());
263     }
264   }
265
266   /**
267    * remove any references held to the given alignment panel
268    * 
269    * @param nap
270    */
271   public void removeAlignmentPanel(AlignmentPanel nap)
272   {
273     try
274     {
275       _alignwith.remove(nap);
276       _colourwith.remove(nap);
277       if (getAlignmentPanel() == nap)
278       {
279         setAlignmentPanel(null);
280         for (AlignmentPanel aps : getAllAlignmentPanels())
281         {
282           if (aps != nap)
283           {
284             setAlignmentPanel(aps);
285             break;
286           }
287         }
288       }
289     } catch (Exception ex)
290     {
291     }
292     if (getAlignmentPanel() != null)
293     {
294       buildActionMenu();
295     }
296   }
297
298   public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
299   {
300     addAlignmentPanel(nap);
301     if (!_alignwith.contains(nap))
302     {
303       _alignwith.add(nap);
304     }
305   }
306
307   public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
308   {
309     if (_alignwith.contains(nap))
310     {
311       _alignwith.remove(nap);
312     }
313   }
314
315   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
316           boolean enableColourBySeq)
317   {
318     useAlignmentPanelForColourbyseq(nap);
319     seqColour.setSelected(enableColourBySeq);
320     viewerColour.setSelected(!enableColourBySeq);
321
322     getBinding().setColourBy(enableColourBySeq ? ColourBy.Sequence : ColourBy.Viewer);
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, al, null);
570         getBinding().setJalviewColourScheme(cs, getAlignmentPanel());
571   }
572
573   /**
574    * Builds the colour menu
575    */
576   protected void buildColourMenu()
577   {
578     colourMenu.removeAll();
579     AlignmentI al = getAlignmentPanel().av.getAlignment();
580
581         colourMenu.addSeparator();
582         
583     /*
584      * add colour by sequence, by chain, by charge and cysteine
585      */
586     colourMenu.add(seqColour);
587     colourMenu.add(chainColour);
588     colourMenu.add(chargeColour);
589     chargeColour.setEnabled(!al.isNucleotide());
590
591         /*
592          * add all colour schemes registered to Jalview
593          */
594     ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
595                                 al);
596
597     /*
598      * add 'colour by viewer' (menu item text is set in subclasses)
599      */
600     viewerColour.setSelected(false);
601     viewerColour.addActionListener(new ActionListener()
602     {
603       @Override
604       public void actionPerformed(ActionEvent actionEvent)
605       {
606         viewerColour_actionPerformed(actionEvent);
607       }
608     });
609     colourMenu.add(viewerColour);
610
611     /*
612      * add 'set background colour'
613      */
614     JMenuItem backGround = new JMenuItem();
615     backGround
616             .setText(MessageManager.getString("action.background_colour"));
617     backGround.addActionListener(new ActionListener()
618     {
619       @Override
620       public void actionPerformed(ActionEvent actionEvent)
621       {
622         background_actionPerformed(actionEvent);
623       }
624     });
625     colourMenu.add(backGround);
626
627     /*
628      * add colour buttons to a group so their selection is
629      * mutually exclusive (background colour is a separate option)
630      */
631     itemGroup.add(seqColour);
632     itemGroup.add(chainColour);
633     itemGroup.add(chargeColour);
634     itemGroup.add(viewerColour);
635   }
636
637   /**
638    * Construct menu items
639    */
640   protected void initMenus()
641   {
642     AAStructureBindingModel binding = getBinding();
643
644     seqColour = new JRadioButtonMenuItem();
645     seqColour.setText(MessageManager.getString("action.by_sequence"));
646     seqColour.setName(ViewerColour.BySequence.name());
647     seqColour.setSelected(binding.isColourBySequence());
648     seqColour.addActionListener(new ActionListener()
649     {
650       @Override
651       public void actionPerformed(ActionEvent actionEvent)
652       {
653         seqColour_actionPerformed(actionEvent);
654       }
655     });
656
657     chainColour = new JRadioButtonMenuItem();
658     chainColour.setText(MessageManager.getString("action.by_chain"));
659     chainColour.setName(ViewerColour.ByChain.name());
660     chainColour.addActionListener(new ActionListener()
661     {
662       @Override
663       public void actionPerformed(ActionEvent actionEvent)
664       {
665         chainColour_actionPerformed(actionEvent);
666       }
667     });
668
669     chargeColour = new JRadioButtonMenuItem();
670     chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
671     chargeColour.setName(ViewerColour.ChargeCysteine.name());
672     chargeColour.addActionListener(new ActionListener()
673     {
674       @Override
675       public void actionPerformed(ActionEvent actionEvent)
676       {
677         chargeColour_actionPerformed(actionEvent);
678       }
679     });
680
681     viewerColour = new JRadioButtonMenuItem();
682     // text is set in overrides of this method
683     viewerColour.setName(ViewerColour.ByViewer.name());
684     viewerColour.setSelected(!binding.isColourBySequence());
685
686     if (_colourwith == null)
687     {
688       _colourwith = new Vector<>();
689     }
690     if (_alignwith == null)
691     {
692       _alignwith = new Vector<>();
693     }
694
695     ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
696             MessageManager.getString("label.colour_by"), this, _colourwith,
697             new ItemListener()
698             {
699               @Override
700               public void itemStateChanged(ItemEvent e)
701               {
702                 if (!seqColour.isSelected())
703                 {
704                   seqColour.doClick();
705                 }
706                 else
707                 {
708                   // update the Chimera display now.
709                   seqColour_actionPerformed(null);
710                 }
711               }
712             });
713     viewMenu.add(seqColourBy);
714
715     final ItemListener handler = new ItemListener()
716     {
717       @Override
718       public void itemStateChanged(ItemEvent e)
719       {
720         alignStructs.setEnabled(!_alignwith.isEmpty());
721         alignStructs.setToolTipText(MessageManager.formatMessage(
722                 "label.align_structures_using_linked_alignment_views",
723                 _alignwith.size()));
724       }
725     };
726     viewSelectionMenu = new ViewSelectionMenu(
727             MessageManager.getString("label.superpose_with"), this,
728             _alignwith, handler);
729     handler.itemStateChanged(null);
730     viewerActionMenu.add(viewSelectionMenu, 0);
731     viewerActionMenu.addMenuListener(new MenuListener()
732     {
733       @Override
734       public void menuSelected(MenuEvent e)
735       {
736         handler.itemStateChanged(null);
737       }
738
739       @Override
740       public void menuDeselected(MenuEvent e)
741       {
742       }
743
744       @Override
745       public void menuCanceled(MenuEvent e)
746       {
747       }
748     });
749
750     buildColourMenu();
751   }
752
753   /**
754    * Sends commands to the structure viewer to superimpose structures based on
755    * currently associated alignments. May optionally return an error message for
756    * the operation.
757    */
758   @Override
759   protected String alignStructs_actionPerformed(ActionEvent actionEvent)
760   {
761     return alignStructs_withAllAlignPanels();
762   }
763
764   protected String alignStructs_withAllAlignPanels()
765   {
766     if (getAlignmentPanel() == null)
767     {
768       return null;
769     }
770
771     if (_alignwith.size() == 0)
772     {
773       _alignwith.add(getAlignmentPanel());
774     }
775
776     String reply = null;
777     try
778     {
779       AlignmentI[] als = new Alignment[_alignwith.size()];
780       HiddenColumns[] alc = new HiddenColumns[_alignwith.size()];
781       int[] alm = new int[_alignwith.size()];
782       int a = 0;
783
784       for (AlignmentPanel alignPanel : _alignwith)
785       {
786         als[a] = alignPanel.av.getAlignment();
787         alm[a] = -1;
788         alc[a++] = alignPanel.av.getAlignment().getHiddenColumns();
789       }
790       reply = getBinding().superposeStructures(als, alm, alc);
791       if (reply != null)
792       {
793         String text = MessageManager
794                 .formatMessage("error.superposition_failed", reply);
795         statusBar.setText(text);
796       }
797     } catch (Exception e)
798     {
799       StringBuffer sp = new StringBuffer();
800       for (AlignmentPanel alignPanel : _alignwith)
801       {
802         sp.append("'" + alignPanel.alignFrame.getTitle() + "' ");
803       }
804       Cache.log.info("Couldn't align structures with the " + sp.toString()
805               + "associated alignment panels.", e);
806     }
807     return reply;
808   }
809
810   @Override
811   public void background_actionPerformed(ActionEvent actionEvent)
812   {
813     Color col = JColorChooser.showDialog(this,
814             MessageManager.getString("label.select_background_colour"),
815             null);
816     if (col != null)
817     {
818       getBinding().setBackgroundColour(col);
819     }
820   }
821
822   @Override
823   public void viewerColour_actionPerformed(ActionEvent actionEvent)
824   {
825     if (viewerColour.isSelected())
826     {
827       // disable automatic sequence colouring.
828       getBinding().setColourBy(ColourBy.Viewer);
829     }
830   }
831
832   @Override
833   public void chainColour_actionPerformed(ActionEvent actionEvent)
834   {
835     chainColour.setSelected(true);
836     getBinding().colourByChain();
837   }
838
839   @Override
840   public void chargeColour_actionPerformed(ActionEvent actionEvent)
841   {
842     chargeColour.setSelected(true);
843     getBinding().colourByCharge();
844   }
845
846   @Override
847   public void seqColour_actionPerformed(ActionEvent actionEvent)
848   {
849     AAStructureBindingModel binding = getBinding();
850     boolean colourBySequence = seqColour.isSelected();
851     if (_colourwith == null)
852     {
853       _colourwith = new Vector<>();
854     }
855     if (colourBySequence)
856     {
857       if (!binding.isLoadingFromArchive())
858       {
859         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
860         {
861           // Make the currently displayed alignment panel the associated view
862           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
863         }
864       }
865       // Set the colour using the current view for the associated alignframe
866       for (AlignmentPanel alignPanel : _colourwith)
867       {
868         binding.colourBySequence(alignPanel);
869       }
870       seqColoursApplied = true;
871     }
872   }
873
874   @Override
875   public void pdbFile_actionPerformed(ActionEvent actionEvent)
876   {
877     JalviewFileChooser chooser = new JalviewFileChooser(
878             Cache.getProperty("LAST_DIRECTORY"));
879
880     chooser.setFileView(new JalviewFileView());
881     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
882     chooser.setToolTipText(MessageManager.getString("action.save"));
883
884     int value = chooser.showSaveDialog(this);
885
886     if (value == JalviewFileChooser.APPROVE_OPTION)
887     {
888       BufferedReader in = null;
889       try
890       {
891         // TODO: cope with multiple PDB files in view
892         in = new BufferedReader(
893                 new FileReader(getBinding().getStructureFiles()[0]));
894         File outFile = chooser.getSelectedFile();
895
896         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
897         String data;
898         while ((data = in.readLine()) != null)
899         {
900           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
901           {
902             out.println(data);
903           }
904         }
905         out.close();
906       } catch (Exception ex)
907       {
908         ex.printStackTrace();
909       } finally
910       {
911         if (in != null)
912         {
913           try
914           {
915             in.close();
916           } catch (IOException e)
917           {
918             // ignore
919           }
920         }
921       }
922     }
923   }
924
925   @Override
926   public void viewMapping_actionPerformed(ActionEvent actionEvent)
927   {
928     CutAndPasteTransfer cap = new CutAndPasteTransfer();
929     try
930     {
931       cap.appendText(getBinding().printMappings());
932     } catch (OutOfMemoryError e)
933     {
934       new OOMWarning(
935               "composing sequence-structure alignments for display in text box.",
936               e);
937       cap.dispose();
938       return;
939     }
940     Desktop.addInternalFrame(cap,
941             MessageManager.getString("label.pdb_sequence_mapping"), 550,
942             600);
943   }
944
945   protected abstract String getViewerName();
946
947   /**
948    * Configures the title and menu items of the viewer panel.
949    */
950   @Override
951   public void updateTitleAndMenus()
952   {
953     AAStructureBindingModel binding = getBinding();
954     if (binding.hasFileLoadingError())
955     {
956       repaint();
957       return;
958     }
959     setChainMenuItems(binding.getChainNames());
960
961     this.setTitle(binding.getViewerTitle(getViewerName(), true));
962
963     /*
964      * enable 'Superpose with' if more than one mapped structure
965      */
966     viewSelectionMenu.setEnabled(false);
967     if (getBinding().getStructureFiles().length > 1
968             && getBinding().getSequence().length > 1)
969     {
970       viewSelectionMenu.setEnabled(true);
971     }
972
973     /*
974      * Show action menu if it has any enabled items
975      */
976     viewerActionMenu.setVisible(false);
977     for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
978     {
979       if (viewerActionMenu.getItem(i).isEnabled())
980       {
981         viewerActionMenu.setVisible(true);
982         break;
983       }
984     }
985
986     if (!binding.isLoadingFromArchive())
987     {
988       seqColour_actionPerformed(null);
989     }
990   }
991
992   @Override
993   public String toString()
994   {
995     return getTitle();
996   }
997
998   @Override
999   public boolean hasMapping()
1000   {
1001     if (worker != null && (addingStructures || _started))
1002     {
1003       return false;
1004     }
1005     if (getBinding() == null)
1006     {
1007       if (_aps == null || _aps.size() == 0)
1008       {
1009         // viewer has been closed, but we did at some point run.
1010         return true;
1011       }
1012       return false;
1013     }
1014     String[] pdbids = getBinding().getStructureFiles();
1015     if (pdbids == null)
1016     {
1017       return false;
1018     }
1019     int p=0;
1020     for (String pdbid:pdbids) {
1021       StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1022       if (sm!=null && sm.length>0 && sm[0]!=null) {
1023         p++;
1024       }
1025     }
1026     // only return true if there is a mapping for every structure file we have loaded
1027     if (p == 0 || p != pdbids.length)
1028     {
1029       return false;
1030     }
1031     // and that coloring has been applied
1032     return seqColoursApplied;
1033   }
1034
1035   @Override
1036   public void raiseViewer()
1037   {
1038     toFront();
1039   }
1040
1041 }