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