JAL-2358 ensure mappings removed on close Chimera; pull up method;
[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.datamodel.PDBEntry;
24 import jalview.datamodel.SequenceI;
25 import jalview.gui.StructureViewer.ViewerType;
26 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
27 import jalview.io.DataSourceType;
28 import jalview.jbgui.GStructureViewer;
29 import jalview.structure.StructureSelectionManager;
30 import jalview.structures.models.AAStructureBindingModel;
31 import jalview.util.MessageManager;
32
33 import java.awt.Component;
34 import java.awt.event.ActionEvent;
35 import java.awt.event.ActionListener;
36 import java.awt.event.ItemEvent;
37 import java.awt.event.ItemListener;
38 import java.util.ArrayList;
39 import java.util.List;
40 import java.util.Vector;
41
42 import javax.swing.JCheckBoxMenuItem;
43 import javax.swing.JInternalFrame;
44 import javax.swing.JMenuItem;
45
46 /**
47  * Base class with common functionality for JMol, Chimera or other structure
48  * viewers.
49  * 
50  * @author gmcarstairs
51  *
52  */
53 public abstract class StructureViewerBase extends GStructureViewer
54         implements Runnable, ViewSetProvider
55 {
56
57   /**
58    * list of sequenceSet ids associated with the view
59    */
60   protected List<String> _aps = new ArrayList<String>();
61
62   /**
63    * list of alignment panels to use for superposition
64    */
65   protected Vector<AlignmentPanel> _alignwith = new Vector<AlignmentPanel>();
66
67   /**
68    * list of alignment panels that are used for colouring structures by aligned
69    * sequences
70    */
71   protected Vector<AlignmentPanel> _colourwith = new Vector<AlignmentPanel>();
72
73   private String viewId = null;
74
75   private AlignmentPanel ap;
76
77   protected boolean alignAddedStructures = false;
78
79   protected boolean _started = false;
80
81   protected boolean addingStructures = false;
82
83   protected Thread worker = null;
84
85   protected boolean allChainsSelected = false;
86
87   /**
88    * 
89    * @param ap2
90    * @return true if this Jmol instance is linked with the given alignPanel
91    */
92   public boolean isLinkedWith(AlignmentPanel ap2)
93   {
94     return _aps.contains(ap2.av.getSequenceSetId());
95   }
96
97   public boolean isUsedforaligment(AlignmentPanel ap2)
98   {
99
100     return (_alignwith != null) && _alignwith.contains(ap2);
101   }
102
103   public boolean isUsedforcolourby(AlignmentPanel ap2)
104   {
105     return (_colourwith != null) && _colourwith.contains(ap2);
106   }
107
108   /**
109    * 
110    * @return TRUE if the view is NOT being coloured by the alignment colours.
111    */
112   public boolean isColouredByViewer()
113   {
114     return !getBinding().isColourBySequence();
115   }
116
117   public String getViewId()
118   {
119     if (viewId == null)
120     {
121       viewId = System.currentTimeMillis() + "." + this.hashCode();
122     }
123     return viewId;
124   }
125
126   protected void setViewId(String viewId)
127   {
128     this.viewId = viewId;
129   }
130
131   public abstract String getStateInfo();
132
133   protected void buildActionMenu()
134   {
135     if (_alignwith == null)
136     {
137       _alignwith = new Vector<AlignmentPanel>();
138     }
139     if (_alignwith.size() == 0 && ap != null)
140     {
141       _alignwith.add(ap);
142     }
143     ;
144     for (Component c : viewerActionMenu.getMenuComponents())
145     {
146       if (c != alignStructs)
147       {
148         viewerActionMenu.remove((JMenuItem) c);
149       }
150     }
151   }
152
153   public AlignmentPanel getAlignmentPanel()
154   {
155     return ap;
156   }
157
158   protected void setAlignmentPanel(AlignmentPanel alp)
159   {
160     this.ap = alp;
161   }
162
163   @Override
164   public AlignmentPanel[] getAllAlignmentPanels()
165   {
166     AlignmentPanel[] t, list = new AlignmentPanel[0];
167     for (String setid : _aps)
168     {
169       AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
170       if (panels != null)
171       {
172         t = new AlignmentPanel[list.length + panels.length];
173         System.arraycopy(list, 0, t, 0, list.length);
174         System.arraycopy(panels, 0, t, list.length, panels.length);
175         list = t;
176       }
177     }
178
179     return list;
180   }
181
182   /**
183    * set the primary alignmentPanel reference and add another alignPanel to the
184    * list of ones to use for colouring and aligning
185    * 
186    * @param nap
187    */
188   public void addAlignmentPanel(AlignmentPanel nap)
189   {
190     if (getAlignmentPanel() == null)
191     {
192       setAlignmentPanel(nap);
193     }
194     if (!_aps.contains(nap.av.getSequenceSetId()))
195     {
196       _aps.add(nap.av.getSequenceSetId());
197     }
198   }
199
200   /**
201    * remove any references held to the given alignment panel
202    * 
203    * @param nap
204    */
205   public void removeAlignmentPanel(AlignmentPanel nap)
206   {
207     try
208     {
209       _alignwith.remove(nap);
210       _colourwith.remove(nap);
211       if (getAlignmentPanel() == nap)
212       {
213         setAlignmentPanel(null);
214         for (AlignmentPanel aps : getAllAlignmentPanels())
215         {
216           if (aps != nap)
217           {
218             setAlignmentPanel(aps);
219             break;
220           }
221         }
222       }
223     } catch (Exception ex)
224     {
225     }
226     if (getAlignmentPanel() != null)
227     {
228       buildActionMenu();
229     }
230   }
231
232   public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
233   {
234     addAlignmentPanel(nap);
235     if (!_alignwith.contains(nap))
236     {
237       _alignwith.add(nap);
238     }
239   }
240
241   public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
242   {
243     if (_alignwith.contains(nap))
244     {
245       _alignwith.remove(nap);
246     }
247   }
248
249   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
250           boolean enableColourBySeq)
251   {
252     useAlignmentPanelForColourbyseq(nap);
253     getBinding().setColourBySequence(enableColourBySeq);
254     seqColour.setSelected(enableColourBySeq);
255     viewerColour.setSelected(!enableColourBySeq);
256   }
257
258   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
259   {
260     addAlignmentPanel(nap);
261     if (!_colourwith.contains(nap))
262     {
263       _colourwith.add(nap);
264     }
265   }
266
267   public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
268   {
269     if (_colourwith.contains(nap))
270     {
271       _colourwith.remove(nap);
272     }
273   }
274
275   public abstract ViewerType getViewerType();
276
277   protected abstract AAStructureBindingModel getBindingModel();
278
279   /**
280    * add a new structure (with associated sequences and chains) to this viewer,
281    * retrieving it if necessary first.
282    * 
283    * @param pdbentry
284    * @param seqs
285    * @param chains
286    * @param align
287    *          if true, new structure(s) will be aligned using associated
288    *          alignment
289    * @param alignFrame
290    */
291   protected void addStructure(final PDBEntry pdbentry,
292           final SequenceI[] seqs, final String[] chains,
293           final boolean align, final IProgressIndicator alignFrame)
294   {
295     if (pdbentry.getFile() == null)
296     {
297       if (worker != null && worker.isAlive())
298       {
299         // a retrieval is in progress, wait around and add ourselves to the
300         // queue.
301         new Thread(new Runnable()
302         {
303           @Override
304           public void run()
305           {
306             while (worker != null && worker.isAlive() && _started)
307             {
308               try
309               {
310                 Thread.sleep(100 + ((int) Math.random() * 100));
311
312               } catch (Exception e)
313               {
314               }
315             }
316             // and call ourselves again.
317             addStructure(pdbentry, seqs, chains, align, alignFrame);
318           }
319         }).start();
320         return;
321       }
322     }
323     // otherwise, start adding the structure.
324     getBindingModel().addSequenceAndChain(new PDBEntry[] { pdbentry },
325             new SequenceI[][] { seqs }, new String[][] { chains });
326     addingStructures = true;
327     _started = false;
328     alignAddedStructures = align;
329     worker = new Thread(this);
330     worker.start();
331     return;
332   }
333
334   /**
335    * Presents a dialog with the option to add an align a structure to an
336    * existing structure view
337    * 
338    * @param pdbId
339    * @param view
340    * @return YES, NO or CANCEL JvOptionPane code
341    */
342   protected int chooseAlignStructureToViewer(String pdbId,
343           StructureViewerBase view)
344   {
345     int option = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
346             MessageManager.formatMessage("label.add_pdbentry_to_view",
347                     new Object[] { pdbId, view.getTitle() }),
348             MessageManager
349                     .getString("label.align_to_existing_structure_view"),
350             JvOptionPane.YES_NO_CANCEL_OPTION);
351     return option;
352   }
353
354   protected abstract boolean hasPdbId(String pdbId);
355
356   /**
357    * Returns a list of any structure viewers of the same type. The list is
358    * restricted to those linked to the given alignment panel if it is not null.
359    */
360   protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp){
361
362     List<StructureViewerBase> result = new ArrayList<StructureViewerBase>();
363     JInternalFrame[] frames = Desktop.instance.getAllFrames();
364
365     for (JInternalFrame frame : frames)
366     {
367       if (this.getClass().isAssignableFrom(frame.getClass()))
368       {
369         if (alp == null
370                 || ((StructureViewerBase) frame).isLinkedWith(alp))
371         {
372           result.add((StructureViewerBase) frame);
373         }
374       }
375     }
376     return result;
377   
378   }
379
380   /**
381    * Check for any existing views involving this alignment and give user the
382    * option to add and align this molecule to one of them
383    * 
384    * @param pdbentry
385    * @param seq
386    * @param chains
387    * @param apanel
388    * @param pdbId
389    * @return true if user adds to a view, or cancels entirely, else false
390    */
391   protected boolean addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
392           String[] chains, final AlignmentPanel apanel, String pdbId)
393   {
394     for (StructureViewerBase view : getViewersFor(apanel))
395     {
396       // TODO: highlight the view somehow
397       /*
398        * JAL-1742 exclude view with this structure already mapped (don't offer
399        * to align chain B to chain A of the same structure)
400        */
401       if (view.hasPdbId(pdbId))
402       {
403         continue;
404       }
405       int option = chooseAlignStructureToViewer(pdbId, view);
406       if (option == JvOptionPane.CANCEL_OPTION)
407       {
408         return true;
409       }
410       else if (option == JvOptionPane.YES_OPTION)
411       {
412         view.useAlignmentPanelForSuperposition(apanel);
413         view.addStructure(pdbentry, seq, chains, true, apanel.alignFrame);
414         return true;
415       }
416       else
417       {
418         // NO_OPTION - offer the next viewer if any
419       }
420     }
421
422     /*
423      * nothing offered and selected
424      */
425     return false;
426   }
427
428   /**
429    * Adds mappings for the given sequences to an already opened PDB structure,
430    * and updates any viewers that have the PDB file
431    * 
432    * @param seq
433    * @param chains
434    * @param apanel
435    * @param pdbFilename
436    */
437   protected void addSequenceMappingsToStructure(SequenceI[] seq,
438           String[] chains, final AlignmentPanel apanel, String pdbFilename)
439   {
440     // TODO : Fix multiple seq to one chain issue here.
441     /*
442      * create the mappings
443      */
444     apanel.getStructureSelectionManager().setMapping(seq, chains,
445             pdbFilename, DataSourceType.FILE);
446
447     /*
448      * alert the FeatureRenderer to show new (PDB RESNUM) features
449      */
450     if (apanel.getSeqPanel().seqCanvas.fr != null)
451     {
452       apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
453       apanel.paintAlignment(true);
454     }
455
456     /*
457      * add the sequences to any other viewers (of the same type) for this pdb
458      * file
459      */
460     // JBPNOTE: this looks like a binding routine, rather than a gui routine
461     for (StructureViewerBase viewer : getViewersFor(null))
462     {
463       AAStructureBindingModel bindingModel = viewer.getBindingModel();
464       for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
465       {
466         if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
467         {
468           bindingModel.addSequence(pe, seq);
469           viewer.addAlignmentPanel(apanel);
470           /*
471            * add it to the set of alignments used for colouring structure by
472            * sequence
473            */
474           viewer.useAlignmentPanelForColourbyseq(apanel);
475           viewer.buildActionMenu();
476           apanel.getStructureSelectionManager().sequenceColoursChanged(
477                   apanel);
478           break;
479         }
480       }
481     }
482   }
483
484   /**
485    * Check if the PDB file is already loaded, if so offer to add it to the
486    * existing viewer
487    * 
488    * @param seq
489    * @param chains
490    * @param apanel
491    * @param pdbId
492    * @return true if the user chooses to add to a viewer, or to cancel entirely
493    */
494   protected boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
495           final AlignmentPanel apanel, String pdbId)
496   {
497     boolean finished = false;
498     StructureSelectionManager ssm = apanel.getStructureSelectionManager();
499     String alreadyMapped = ssm.alreadyMappedToFile(pdbId);
500
501     if (alreadyMapped != null)
502     {
503       /*
504        * the PDB file is already loaded
505        */
506       int option = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
507               MessageManager.formatMessage(
508                       "label.pdb_entry_is_already_displayed",
509                       new Object[] { pdbId }), MessageManager
510                       .formatMessage(
511                               "label.map_sequences_to_visible_window",
512                               new Object[] { pdbId }),
513               JvOptionPane.YES_NO_CANCEL_OPTION);
514       if (option == JvOptionPane.CANCEL_OPTION)
515       {
516         finished = true;
517       }
518       else if (option == JvOptionPane.YES_OPTION)
519       {
520         addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
521         finished = true;
522       }
523     }
524     return finished;
525   }
526
527   void setChainMenuItems(List<String> chainNames)
528   {
529     chainMenu.removeAll();
530     if (chainNames == null || chainNames.isEmpty())
531     {
532       return;
533     }
534     JMenuItem menuItem = new JMenuItem(
535             MessageManager.getString("label.all"));
536     menuItem.addActionListener(new ActionListener()
537     {
538       @Override
539       public void actionPerformed(ActionEvent evt)
540       {
541         allChainsSelected = true;
542         for (int i = 0; i < chainMenu.getItemCount(); i++)
543         {
544           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
545           {
546             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
547           }
548         }
549         showSelectedChains();
550         allChainsSelected = false;
551       }
552     });
553
554     chainMenu.add(menuItem);
555
556     for (String chain : chainNames)
557     {
558       menuItem = new JCheckBoxMenuItem(chain, true);
559       menuItem.addItemListener(new ItemListener()
560       {
561         @Override
562         public void itemStateChanged(ItemEvent evt)
563         {
564           if (!allChainsSelected)
565           {
566             showSelectedChains();
567           }
568         }
569       });
570
571       chainMenu.add(menuItem);
572     }
573   }
574
575   abstract void showSelectedChains();
576
577 }