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