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