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