file format enum wip changes
[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.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   @Override
156   public AlignmentPanel[] getAllAlignmentPanels()
157   {
158     AlignmentPanel[] t, list = new AlignmentPanel[0];
159     for (String setid : _aps)
160     {
161       AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
162       if (panels != null)
163       {
164         t = new AlignmentPanel[list.length + panels.length];
165         System.arraycopy(list, 0, t, 0, list.length);
166         System.arraycopy(panels, 0, t, list.length, panels.length);
167         list = t;
168       }
169     }
170
171     return list;
172   }
173
174   /**
175    * set the primary alignmentPanel reference and add another alignPanel to the
176    * list of ones to use for colouring and aligning
177    * 
178    * @param nap
179    */
180   public void addAlignmentPanel(AlignmentPanel nap)
181   {
182     if (getAlignmentPanel() == null)
183     {
184       setAlignmentPanel(nap);
185     }
186     if (!_aps.contains(nap.av.getSequenceSetId()))
187     {
188       _aps.add(nap.av.getSequenceSetId());
189     }
190   }
191
192   /**
193    * remove any references held to the given alignment panel
194    * 
195    * @param nap
196    */
197   public void removeAlignmentPanel(AlignmentPanel nap)
198   {
199     try
200     {
201       _alignwith.remove(nap);
202       _colourwith.remove(nap);
203       if (getAlignmentPanel() == nap)
204       {
205         setAlignmentPanel(null);
206         for (AlignmentPanel aps : getAllAlignmentPanels())
207         {
208           if (aps != nap)
209           {
210             setAlignmentPanel(aps);
211             break;
212           }
213         }
214       }
215     } catch (Exception ex)
216     {
217     }
218     if (getAlignmentPanel() != null)
219     {
220       buildActionMenu();
221     }
222   }
223
224   public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
225   {
226     addAlignmentPanel(nap);
227     if (!_alignwith.contains(nap))
228     {
229       _alignwith.add(nap);
230     }
231   }
232
233   public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
234   {
235     if (_alignwith.contains(nap))
236     {
237       _alignwith.remove(nap);
238     }
239   }
240
241   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
242           boolean enableColourBySeq)
243   {
244     useAlignmentPanelForColourbyseq(nap);
245     getBinding().setColourBySequence(enableColourBySeq);
246     seqColour.setSelected(enableColourBySeq);
247     viewerColour.setSelected(!enableColourBySeq);
248   }
249
250   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
251   {
252     addAlignmentPanel(nap);
253     if (!_colourwith.contains(nap))
254     {
255       _colourwith.add(nap);
256     }
257   }
258
259   public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
260   {
261     if (_colourwith.contains(nap))
262     {
263       _colourwith.remove(nap);
264     }
265   }
266
267   public abstract ViewerType getViewerType();
268
269   protected abstract AAStructureBindingModel getBindingModel();
270
271   /**
272    * add a new structure (with associated sequences and chains) to this viewer,
273    * retrieving it if necessary first.
274    * 
275    * @param pdbentry
276    * @param seqs
277    * @param chains
278    * @param align
279    *          if true, new structure(s) will be aligned using associated
280    *          alignment
281    * @param alignFrame
282    */
283   protected void addStructure(final PDBEntry pdbentry,
284           final SequenceI[] seqs, final String[] chains,
285           final boolean align, final IProgressIndicator alignFrame)
286   {
287     if (pdbentry.getFile() == null)
288     {
289       if (worker != null && worker.isAlive())
290       {
291         // a retrieval is in progress, wait around and add ourselves to the
292         // queue.
293         new Thread(new Runnable()
294         {
295           @Override
296           public void run()
297           {
298             while (worker != null && worker.isAlive() && _started)
299             {
300               try
301               {
302                 Thread.sleep(100 + ((int) Math.random() * 100));
303
304               } catch (Exception e)
305               {
306               }
307             }
308             // and call ourselves again.
309             addStructure(pdbentry, seqs, chains, align, alignFrame);
310           }
311         }).start();
312         return;
313       }
314     }
315     // otherwise, start adding the structure.
316     getBindingModel().addSequenceAndChain(new PDBEntry[] { pdbentry },
317             new SequenceI[][] { seqs }, new String[][] { chains });
318     addingStructures = true;
319     _started = false;
320     alignAddedStructures = align;
321     worker = new Thread(this);
322     worker.start();
323     return;
324   }
325
326   /**
327    * Presents a dialog with the option to add an align a structure to an
328    * existing structure view
329    * 
330    * @param pdbId
331    * @param view
332    * @return YES, NO or CANCEL JOptionPane code
333    */
334   protected int chooseAlignStructureToViewer(String pdbId,
335           StructureViewerBase view)
336   {
337     int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
338             MessageManager.formatMessage("label.add_pdbentry_to_view",
339                     new Object[] { pdbId, view.getTitle() }),
340             MessageManager
341                     .getString("label.align_to_existing_structure_view"),
342             JOptionPane.YES_NO_CANCEL_OPTION);
343     return option;
344   }
345
346   protected abstract boolean hasPdbId(String pdbId);
347
348   protected abstract List<StructureViewerBase> getViewersFor(
349           AlignmentPanel alp);
350
351   /**
352    * Check for any existing views involving this alignment and give user the
353    * option to add and align this molecule to one of them
354    * 
355    * @param pdbentry
356    * @param seq
357    * @param chains
358    * @param apanel
359    * @param pdbId
360    * @return true if user adds to a view, or cancels entirely, else false
361    */
362   protected boolean addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
363           String[] chains, final AlignmentPanel apanel, String pdbId)
364   {
365     for (StructureViewerBase view : getViewersFor(apanel))
366     {
367       // TODO: highlight the view somehow
368       /*
369        * JAL-1742 exclude view with this structure already mapped (don't offer
370        * to align chain B to chain A of the same structure)
371        */
372       if (view.hasPdbId(pdbId))
373       {
374         continue;
375       }
376       int option = chooseAlignStructureToViewer(pdbId, view);
377       if (option == JOptionPane.CANCEL_OPTION)
378       {
379         return true;
380       }
381       else if (option == JOptionPane.YES_OPTION)
382       {
383         view.useAlignmentPanelForSuperposition(apanel);
384         view.addStructure(pdbentry, seq, chains, true, apanel.alignFrame);
385         return true;
386       }
387       else
388       {
389         // NO_OPTION - offer the next viewer if any
390       }
391     }
392
393     /*
394      * nothing offered and selected
395      */
396     return false;
397   }
398
399   /**
400    * Adds mappings for the given sequences to an already opened PDB structure,
401    * and updates any viewers that have the PDB file
402    * 
403    * @param seq
404    * @param chains
405    * @param apanel
406    * @param pdbFilename
407    */
408   protected void addSequenceMappingsToStructure(SequenceI[] seq,
409           String[] chains, final AlignmentPanel apanel, String pdbFilename)
410   {
411     // TODO : Fix multiple seq to one chain issue here.
412     /*
413      * create the mappings
414      */
415     apanel.getStructureSelectionManager().setMapping(seq, chains,
416             pdbFilename, DataSourceType.FILE);
417
418     /*
419      * alert the FeatureRenderer to show new (PDB RESNUM) features
420      */
421     if (apanel.getSeqPanel().seqCanvas.fr != null)
422     {
423       apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
424       apanel.paintAlignment(true);
425     }
426
427     /*
428      * add the sequences to any other viewers (of the same type) for this pdb
429      * file
430      */
431     // JBPNOTE: this looks like a binding routine, rather than a gui routine
432     for (StructureViewerBase viewer : getViewersFor(null))
433     {
434       AAStructureBindingModel bindingModel = viewer.getBindingModel();
435       for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
436       {
437         if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
438         {
439           bindingModel.addSequence(pe, seq);
440           viewer.addAlignmentPanel(apanel);
441           /*
442            * add it to the set of alignments used for colouring structure by
443            * sequence
444            */
445           viewer.useAlignmentPanelForColourbyseq(apanel);
446           viewer.buildActionMenu();
447           apanel.getStructureSelectionManager().sequenceColoursChanged(
448                   apanel);
449           break;
450         }
451       }
452     }
453   }
454
455   /**
456    * Check if the PDB file is already loaded, if so offer to add it to the
457    * existing viewer
458    * 
459    * @param seq
460    * @param chains
461    * @param apanel
462    * @param pdbId
463    * @return true if the user chooses to add to a viewer, or to cancel entirely
464    */
465   protected boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
466           final AlignmentPanel apanel, String pdbId)
467   {
468     boolean finished = false;
469     String alreadyMapped = apanel.getStructureSelectionManager()
470             .alreadyMappedToFile(pdbId);
471
472     if (alreadyMapped != null)
473     {
474       /*
475        * the PDB file is already loaded
476        */
477       int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
478               MessageManager.formatMessage(
479                       "label.pdb_entry_is_already_displayed",
480                       new Object[] { pdbId }), MessageManager
481                       .formatMessage(
482                               "label.map_sequences_to_visible_window",
483                               new Object[] { pdbId }),
484               JOptionPane.YES_NO_CANCEL_OPTION);
485       if (option == JOptionPane.CANCEL_OPTION)
486       {
487         finished = true;
488       }
489       else if (option == JOptionPane.YES_OPTION)
490       {
491         addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
492         finished = true;
493       }
494     }
495     return finished;
496   }
497 }