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