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