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