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