JAL-845 applet colour by tree; translate as cDNA; pull up history list
[jalview.git] / src / jalview / gui / AlignViewport.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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 /*
22  * Jalview - A Sequence Alignment Editor and Viewer
23  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
24  *
25  * This program is free software; you can redistribute it and/or
26  * modify it under the terms of the GNU General Public License
27  * as published by the Free Software Foundation; either version 2
28  * of the License, or (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program; if not, write to the Free Software
37  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
38  */
39 package jalview.gui;
40
41 import jalview.analysis.AlignmentUtils;
42 import jalview.analysis.AlignmentUtils.MappingResult;
43 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
44 import jalview.analysis.NJTree;
45 import jalview.api.AlignViewportI;
46 import jalview.api.ViewStyleI;
47 import jalview.bin.Cache;
48 import jalview.commands.CommandI;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentI;
51 import jalview.datamodel.ColumnSelection;
52 import jalview.datamodel.PDBEntry;
53 import jalview.datamodel.Sequence;
54 import jalview.datamodel.SequenceGroup;
55 import jalview.datamodel.SequenceI;
56 import jalview.schemes.ColourSchemeProperty;
57 import jalview.schemes.UserColourScheme;
58 import jalview.structure.CommandListener;
59 import jalview.structure.SelectionSource;
60 import jalview.structure.StructureSelectionManager;
61 import jalview.structure.VamsasSource;
62 import jalview.util.MessageManager;
63 import jalview.viewmodel.AlignmentViewport;
64 import jalview.ws.params.AutoCalcSetting;
65
66 import java.awt.Container;
67 import java.awt.Dimension;
68 import java.awt.Font;
69 import java.awt.Rectangle;
70 import java.util.ArrayList;
71 import java.util.Hashtable;
72 import java.util.Set;
73 import java.util.Vector;
74
75 import javax.swing.JInternalFrame;
76 import javax.swing.JOptionPane;
77
78 /**
79  * DOCUMENT ME!
80  * 
81  * @author $author$
82  * @version $Revision: 1.141 $
83  */
84 public class AlignViewport extends AlignmentViewport implements
85         SelectionSource, AlignViewportI, CommandListener
86 {
87   int startRes;
88
89   int endRes;
90
91   int startSeq;
92
93   int endSeq;
94
95
96   SequenceAnnotationOrder sortAnnotationsBy = null;
97
98   Font font;
99
100   NJTree currentTree = null;
101
102   boolean cursorMode = false;
103
104   boolean antiAlias = false;
105
106   private Rectangle explodedGeometry;
107
108   String viewName;
109
110   private boolean gatherViewsHere = false;
111
112   private AnnotationColumnChooser annotationColumnSelectionState;
113   /**
114    * Creates a new AlignViewport object.
115    * 
116    * @param al
117    *          alignment to view
118    */
119   public AlignViewport(AlignmentI al)
120   {
121     setAlignment(al);
122     init();
123   }
124
125   /**
126    * Create a new AlignViewport object with a specific sequence set ID
127    * 
128    * @param al
129    * @param seqsetid
130    *          (may be null - but potential for ambiguous constructor exception)
131    */
132   public AlignViewport(AlignmentI al, String seqsetid)
133   {
134     this(al, seqsetid, null);
135   }
136
137   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
138   {
139     sequenceSetID = seqsetid;
140     viewId = viewid;
141     // TODO remove these once 2.4.VAMSAS release finished
142     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
143     {
144       Cache.log.debug("Setting viewport's sequence set id : "
145               + sequenceSetID);
146     }
147     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
148     {
149       Cache.log.debug("Setting viewport's view id : " + viewId);
150     }
151     setAlignment(al);
152     init();
153   }
154
155   /**
156    * Create a new AlignViewport with hidden regions
157    * 
158    * @param al
159    *          AlignmentI
160    * @param hiddenColumns
161    *          ColumnSelection
162    */
163   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns)
164   {
165     setAlignment(al);
166     if (hiddenColumns != null)
167     {
168       colSel = hiddenColumns;
169     }
170     init();
171   }
172
173   /**
174    * New viewport with hidden columns and an existing sequence set id
175    * 
176    * @param al
177    * @param hiddenColumns
178    * @param seqsetid
179    *          (may be null)
180    */
181   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns,
182           String seqsetid)
183   {
184     this(al, hiddenColumns, seqsetid, null);
185   }
186
187   /**
188    * New viewport with hidden columns and an existing sequence set id and viewid
189    * 
190    * @param al
191    * @param hiddenColumns
192    * @param seqsetid
193    *          (may be null)
194    * @param viewid
195    *          (may be null)
196    */
197   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns,
198           String seqsetid, String viewid)
199   {
200     sequenceSetID = seqsetid;
201     viewId = viewid;
202     // TODO remove these once 2.4.VAMSAS release finished
203     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
204     {
205       Cache.log.debug("Setting viewport's sequence set id : "
206               + sequenceSetID);
207     }
208     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
209     {
210       Cache.log.debug("Setting viewport's view id : " + viewId);
211     }
212     setAlignment(al);
213     if (hiddenColumns != null)
214     {
215       colSel = hiddenColumns;
216     }
217     init();
218   }
219
220   private void applyViewProperties()
221   {
222     antiAlias = Cache.getDefault("ANTI_ALIAS", false);
223
224     viewStyle.setShowJVSuffix(Cache.getDefault("SHOW_JVSUFFIX", true));
225     setShowAnnotation(Cache.getDefault("SHOW_ANNOTATIONS", true));
226
227     setRightAlignIds(Cache.getDefault("RIGHT_ALIGN_IDS", false));
228     setCentreColumnLabels(Cache.getDefault("CENTRE_COLUMN_LABELS", false));
229     autoCalculateConsensus = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
230
231     setPadGaps(Cache.getDefault("PAD_GAPS", true));
232     setShowNPFeats(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
233     setShowDBRefs(Cache.getDefault("SHOW_DBREFS_TOOLTIP", true));
234     viewStyle.setSeqNameItalics(Cache.getDefault("ID_ITALICS", true));
235     viewStyle.setWrapAlignment(Cache.getDefault("WRAP_ALIGNMENT", false));
236     viewStyle.setShowUnconserved(Cache
237             .getDefault("SHOW_UNCONSERVED", false));
238     sortByTree = Cache.getDefault("SORT_BY_TREE", false);
239     followSelection = Cache.getDefault("FOLLOW_SELECTIONS", true);
240     sortAnnotationsBy = SequenceAnnotationOrder.valueOf(Cache.getDefault(
241             Preferences.SORT_ANNOTATIONS,
242             SequenceAnnotationOrder.NONE.name()));
243     showAutocalculatedAbove = Cache.getDefault(
244             Preferences.SHOW_AUTOCALC_ABOVE, false);
245
246   }
247
248   void init()
249   {
250     this.startRes = 0;
251     this.endRes = alignment.getWidth() - 1;
252     this.startSeq = 0;
253     this.endSeq = alignment.getHeight() - 1;
254     applyViewProperties();
255
256     String fontName = Cache.getDefault("FONT_NAME", "SansSerif");
257     String fontStyle = Cache.getDefault("FONT_STYLE", Font.PLAIN + "");
258     String fontSize = Cache.getDefault("FONT_SIZE", "10");
259
260     int style = 0;
261
262     if (fontStyle.equals("bold"))
263     {
264       style = 1;
265     }
266     else if (fontStyle.equals("italic"))
267     {
268       style = 2;
269     }
270
271     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
272
273     alignment
274             .setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
275
276     // We must set conservation and consensus before setting colour,
277     // as Blosum and Clustal require this to be done
278     if (hconsensus == null && !isDataset)
279     {
280       if (!alignment.isNucleotide())
281       {
282         showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
283         showQuality = Cache.getDefault("SHOW_QUALITY", true);
284         showGroupConservation = Cache.getDefault("SHOW_GROUP_CONSERVATION",
285                 false);
286       }
287       showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM",
288               true);
289       showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
290       normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
291               false);
292       showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
293       showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
294     }
295     initAutoAnnotation();
296     if (jalview.bin.Cache.getProperty("DEFAULT_COLOUR") != null)
297     {
298       globalColourScheme = ColourSchemeProperty.getColour(alignment,
299               jalview.bin.Cache.getProperty("DEFAULT_COLOUR"));
300
301       if (globalColourScheme instanceof UserColourScheme)
302       {
303         globalColourScheme = UserDefinedColours.loadDefaultColours();
304         ((UserColourScheme) globalColourScheme).setThreshold(0,
305                 isIgnoreGapsConsensus());
306       }
307
308       if (globalColourScheme != null)
309       {
310         globalColourScheme.setConsensus(hconsensus);
311       }
312     }
313   }
314
315   /**
316    * get the consensus sequence as displayed under the PID consensus annotation
317    * row.
318    * 
319    * @return consensus sequence as a new sequence object
320    */
321   public SequenceI getConsensusSeq()
322   {
323     if (consensus == null)
324     {
325       updateConsensus(null);
326     }
327     if (consensus == null)
328     {
329       return null;
330     }
331     StringBuffer seqs = new StringBuffer();
332     for (int i = 0; i < consensus.annotations.length; i++)
333     {
334       if (consensus.annotations[i] != null)
335       {
336         if (consensus.annotations[i].description.charAt(0) == '[')
337         {
338           seqs.append(consensus.annotations[i].description.charAt(1));
339         }
340         else
341         {
342           seqs.append(consensus.annotations[i].displayCharacter);
343         }
344       }
345     }
346
347     SequenceI sq = new Sequence("Consensus", seqs.toString());
348     sq.setDescription("Percentage Identity Consensus "
349             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
350     return sq;
351   }
352
353   /**
354    * DOCUMENT ME!
355    * 
356    * @return DOCUMENT ME!
357    */
358   public int getStartRes()
359   {
360     return startRes;
361   }
362
363   /**
364    * DOCUMENT ME!
365    * 
366    * @return DOCUMENT ME!
367    */
368   public int getEndRes()
369   {
370     return endRes;
371   }
372
373   /**
374    * DOCUMENT ME!
375    * 
376    * @return DOCUMENT ME!
377    */
378   public int getStartSeq()
379   {
380     return startSeq;
381   }
382
383   /**
384    * DOCUMENT ME!
385    * 
386    * @param res
387    *          DOCUMENT ME!
388    */
389   public void setStartRes(int res)
390   {
391     this.startRes = res;
392   }
393
394   /**
395    * DOCUMENT ME!
396    * 
397    * @param seq
398    *          DOCUMENT ME!
399    */
400   public void setStartSeq(int seq)
401   {
402     this.startSeq = seq;
403   }
404
405   /**
406    * DOCUMENT ME!
407    * 
408    * @param res
409    *          DOCUMENT ME!
410    */
411   public void setEndRes(int res)
412   {
413     if (res > (alignment.getWidth() - 1))
414     {
415       // log.System.out.println(" Corrected res from " + res + " to maximum " +
416       // (alignment.getWidth()-1));
417       res = alignment.getWidth() - 1;
418     }
419
420     if (res < 0)
421     {
422       res = 0;
423     }
424
425     this.endRes = res;
426   }
427
428   /**
429    * DOCUMENT ME!
430    * 
431    * @param seq
432    *          DOCUMENT ME!
433    */
434   public void setEndSeq(int seq)
435   {
436     if (seq > alignment.getHeight())
437     {
438       seq = alignment.getHeight();
439     }
440
441     if (seq < 0)
442     {
443       seq = 0;
444     }
445
446     this.endSeq = seq;
447   }
448
449   /**
450    * DOCUMENT ME!
451    * 
452    * @return DOCUMENT ME!
453    */
454   public int getEndSeq()
455   {
456     return endSeq;
457   }
458
459   boolean validCharWidth;
460
461   /**
462    * update view settings with the given font. You may need to call
463    * alignPanel.fontChanged to update the layout geometry
464    * 
465    * @param setGrid
466    *          when true, charWidth/height is set according to font mentrics
467    */
468   public void setFont(Font f, boolean setGrid)
469   {
470     font = f;
471
472     Container c = new Container();
473
474     java.awt.FontMetrics fm = c.getFontMetrics(font);
475     int w = viewStyle.getCharWidth(), ww = fm.charWidth('M'), h = viewStyle
476             .getCharHeight();
477     if (setGrid)
478     {
479       setCharHeight(fm.getHeight());
480       setCharWidth(ww);
481     }
482     viewStyle.setFontName(font.getName());
483     viewStyle.setFontStyle(font.getStyle());
484     viewStyle.setFontSize(font.getSize());
485
486     validCharWidth = true;
487   }
488
489   @Override
490   public void setViewStyle(ViewStyleI settingsForView)
491   {
492     super.setViewStyle(settingsForView);
493     setFont(new Font(viewStyle.getFontName(), viewStyle.getFontStyle(),
494             viewStyle.getFontSize()), false);
495
496   }
497   /**
498    * DOCUMENT ME!
499    * 
500    * @return DOCUMENT ME!
501    */
502   public Font getFont()
503   {
504     return font;
505   }
506
507   /**
508    * DOCUMENT ME!
509    * 
510    * @param align
511    *          DOCUMENT ME!
512    */
513   public void setAlignment(AlignmentI align)
514   {
515     if (alignment != null && alignment.getCodonFrames() != null)
516     {
517       StructureSelectionManager.getStructureSelectionManager(
518               Desktop.instance).removeMappings(alignment.getCodonFrames());
519     }
520     this.alignment = align;
521     if (alignment != null && alignment.getCodonFrames() != null)
522     {
523       StructureSelectionManager.getStructureSelectionManager(
524               Desktop.instance).addMappings(alignment.getCodonFrames());
525     }
526   }
527
528   /**
529    * DOCUMENT ME!
530    * 
531    * @return DOCUMENT ME!
532    */
533   public char getGapCharacter()
534   {
535     return getAlignment().getGapCharacter();
536   }
537
538   /**
539    * DOCUMENT ME!
540    * 
541    * @param gap
542    *          DOCUMENT ME!
543    */
544   public void setGapCharacter(char gap)
545   {
546     if (getAlignment() != null)
547     {
548       getAlignment().setGapCharacter(gap);
549     }
550   }
551
552   /**
553    * DOCUMENT ME!
554    * 
555    * @return DOCUMENT ME!
556    */
557   public ColumnSelection getColumnSelection()
558   {
559     return colSel;
560   }
561
562   /**
563    * DOCUMENT ME!
564    * 
565    * @param tree
566    *          DOCUMENT ME!
567    */
568   public void setCurrentTree(NJTree tree)
569   {
570     currentTree = tree;
571   }
572
573   /**
574    * DOCUMENT ME!
575    * 
576    * @return DOCUMENT ME!
577    */
578   public NJTree getCurrentTree()
579   {
580     return currentTree;
581   }
582
583   /**
584    * returns the visible column regions of the alignment
585    * 
586    * @param selectedRegionOnly
587    *          true to just return the contigs intersecting with the selected
588    *          area
589    * @return
590    */
591   public int[] getViewAsVisibleContigs(boolean selectedRegionOnly)
592   {
593     int[] viscontigs = null;
594     int start = 0, end = 0;
595     if (selectedRegionOnly && selectionGroup != null)
596     {
597       start = selectionGroup.getStartRes();
598       end = selectionGroup.getEndRes() + 1;
599     }
600     else
601     {
602       end = alignment.getWidth();
603     }
604     viscontigs = colSel.getVisibleContigs(start, end);
605     return viscontigs;
606   }
607
608   /**
609    * get hash of undo and redo list for the alignment
610    * 
611    * @return long[] { historyList.hashCode, redoList.hashCode };
612    */
613   public long[] getUndoRedoHash()
614   {
615     // TODO: JAL-1126
616     if (historyList == null || redoList == null)
617     {
618       return new long[]
619       { -1, -1 };
620     }
621     return new long[]
622     { historyList.hashCode(), this.redoList.hashCode() };
623   }
624
625   /**
626    * test if a particular set of hashcodes are different to the hashcodes for
627    * the undo and redo list.
628    * 
629    * @param undoredo
630    *          the stored set of hashcodes as returned by getUndoRedoHash
631    * @return true if the hashcodes differ (ie the alignment has been edited) or
632    *         the stored hashcode array differs in size
633    */
634   public boolean isUndoRedoHashModified(long[] undoredo)
635   {
636     if (undoredo == null)
637     {
638       return true;
639     }
640     long[] cstate = getUndoRedoHash();
641     if (cstate.length != undoredo.length)
642     {
643       return true;
644     }
645
646     for (int i = 0; i < cstate.length; i++)
647     {
648       if (cstate[i] != undoredo[i])
649       {
650         return true;
651       }
652     }
653     return false;
654   }
655
656   /**
657    * when set, view will scroll to show the highlighted position
658    */
659   public boolean followHighlight = true;
660
661   /**
662    * @return true if view should scroll to show the highlighted region of a
663    *         sequence
664    * @return
665    */
666   public boolean getFollowHighlight()
667   {
668     return followHighlight;
669   }
670
671   public boolean followSelection = true;
672
673   /**
674    * @return true if view selection should always follow the selections
675    *         broadcast by other selection sources
676    */
677   public boolean getFollowSelection()
678   {
679     return followSelection;
680   }
681
682   /**
683    * Send the current selection to be broadcast to any selection listeners.
684    */
685   public void sendSelection()
686   {
687     jalview.structure.StructureSelectionManager
688             .getStructureSelectionManager(Desktop.instance).sendSelection(
689                     new SequenceGroup(getSelectionGroup()),
690                     new ColumnSelection(getColumnSelection()), this);
691   }
692
693   /**
694    * return the alignPanel containing the given viewport. Use this to get the
695    * components currently handling the given viewport.
696    * 
697    * @param av
698    * @return null or an alignPanel guaranteed to have non-null alignFrame
699    *         reference
700    */
701   public AlignmentPanel getAlignPanel()
702   {
703     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(this
704             .getSequenceSetId());
705     for (int p = 0; aps != null && p < aps.length; p++)
706     {
707       if (aps[p].av == this)
708       {
709         return aps[p];
710       }
711     }
712     return null;
713   }
714
715   public boolean getSortByTree()
716   {
717     return sortByTree;
718   }
719
720   public void setSortByTree(boolean sort)
721   {
722     sortByTree = sort;
723   }
724
725   /**
726    * synthesize a column selection if none exists so it covers the given
727    * selection group. if wholewidth is false, no column selection is made if the
728    * selection group covers the whole alignment width.
729    * 
730    * @param sg
731    * @param wholewidth
732    */
733   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
734   {
735     int sgs, sge;
736     if (sg != null
737             && (sgs = sg.getStartRes()) >= 0
738             && sg.getStartRes() <= (sge = sg.getEndRes())
739             && (colSel == null || colSel.getSelected() == null || colSel
740                     .getSelected().size() == 0))
741     {
742       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
743       {
744         // do nothing
745         return;
746       }
747       if (colSel == null)
748       {
749         colSel = new ColumnSelection();
750       }
751       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
752       {
753         colSel.addElement(cspos);
754       }
755     }
756   }
757
758   /**
759    * Returns the (Desktop) instance of the StructureSelectionManager
760    */
761   @Override
762   public StructureSelectionManager getStructureSelectionManager()
763   {
764     return StructureSelectionManager
765             .getStructureSelectionManager(Desktop.instance);
766   }
767
768   /**
769    * 
770    * @param pdbEntries
771    * @return a series of SequenceI arrays, one for each PDBEntry, listing which
772    *         sequence in the alignment holds a reference to it
773    */
774   public SequenceI[][] collateForPDB(PDBEntry[] pdbEntries)
775   {
776     ArrayList<SequenceI[]> seqvectors = new ArrayList<SequenceI[]>();
777     for (PDBEntry pdb : pdbEntries)
778     {
779       ArrayList<SequenceI> seqs = new ArrayList<SequenceI>();
780       for (int i = 0; i < alignment.getHeight(); i++)
781       {
782         Vector pdbs = alignment.getSequenceAt(i).getDatasetSequence()
783                 .getPDBId();
784         if (pdbs == null)
785         {
786           continue;
787         }
788         SequenceI sq;
789         for (int p = 0; p < pdbs.size(); p++)
790         {
791           PDBEntry p1 = (PDBEntry) pdbs.elementAt(p);
792           if (p1.getId().equals(pdb.getId()))
793           {
794             if (!seqs.contains(sq = alignment.getSequenceAt(i)))
795             {
796               seqs.add(sq);
797             }
798
799             continue;
800           }
801         }
802       }
803       seqvectors.add(seqs.toArray(new SequenceI[seqs.size()]));
804     }
805     return seqvectors.toArray(new SequenceI[seqvectors.size()][]);
806   }
807
808   public boolean isNormaliseSequenceLogo()
809   {
810     return normaliseSequenceLogo;
811   }
812
813   public void setNormaliseSequenceLogo(boolean state)
814   {
815     normaliseSequenceLogo = state;
816   }
817
818   /**
819    * 
820    * @return true if alignment characters should be displayed
821    */
822   public boolean isValidCharWidth()
823   {
824     return validCharWidth;
825   }
826
827   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<String, AutoCalcSetting>();
828
829   private boolean showAutocalculatedAbove;
830
831   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
832   {
833     return calcIdParams.get(calcId);
834   }
835
836   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
837           boolean needsUpdate)
838   {
839     calcIdParams.put(calcId, settings);
840     // TODO: create a restart list to trigger any calculations that need to be
841     // restarted after load
842     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
843     if (needsUpdate)
844     {
845       Cache.log.debug("trigger update for " + calcId);
846     }
847   }
848
849   protected SequenceAnnotationOrder getSortAnnotationsBy()
850   {
851     return sortAnnotationsBy;
852   }
853
854   protected void setSortAnnotationsBy(SequenceAnnotationOrder sortAnnotationsBy)
855   {
856     this.sortAnnotationsBy = sortAnnotationsBy;
857   }
858
859   protected boolean isShowAutocalculatedAbove()
860   {
861     return showAutocalculatedAbove;
862   }
863
864   protected void setShowAutocalculatedAbove(boolean showAutocalculatedAbove)
865   {
866     this.showAutocalculatedAbove = showAutocalculatedAbove;
867   }
868
869   /**
870    * Method called when another alignment's edit (or possibly other) command is
871    * broadcast to here.
872    *
873    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
874    * 'unwind' the command on the source sequences (in simulation, not in fact),
875    * and then for each edit in turn:
876    * <ul>
877    * <li>compute the equivalent edit on the mapped sequences</li>
878    * <li>apply the mapped edit</li>
879    * <li>'apply' the source edit to the working copy of the source sequences</li>
880    * </ul>
881    * 
882    * @param command
883    * @param undo
884    * @param ssm
885    */
886   @Override
887   public void mirrorCommand(CommandI command, boolean undo,
888           StructureSelectionManager ssm, VamsasSource source)
889   {
890     /*
891      * Do nothing unless we are a 'complement' of the source. May replace this
892      * with direct calls not via SSM.
893      */
894     if (source instanceof AlignViewportI
895             && ((AlignViewportI) source).getCodingComplement() == this)
896     {
897       // ok to continue;
898     }
899     else
900     {
901       return;
902     }
903
904     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
905             getGapCharacter());
906     if (mappedCommand != null)
907     {
908       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
909       mappedCommand.doCommand(views);
910       getAlignPanel().alignmentChanged();
911     }
912   }
913
914   /**
915    * Add the sequences from the given alignment to this viewport. Optionally,
916    * may give the user the option to open a new frame, or split panel, with cDNA
917    * and protein linked.
918    * 
919    * @param al
920    * @param title
921    */
922   public void addAlignment(AlignmentI al, String title)
923   {
924     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
925
926     // JBPComment: title is a largely redundant parameter at the moment
927     // JBPComment: this really should be an 'insert/pre/append' controller
928     // JBPComment: but the DNA/Protein check makes it a bit more complex
929
930     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
931     // this comment:
932     // TODO: create undo object for this JAL-1101
933
934     /*
935      * If one alignment is protein and one nucleotide, with at least one
936      * sequence name in common, offer to open a linked alignment.
937      */
938     if (getAlignment().isNucleotide() != al.isNucleotide())
939     {
940       // TODO: JAL-845 try a bit harder to link up imported sequences
941       final Set<String> sequenceNames = getAlignment().getSequenceNames();
942       sequenceNames.retainAll(al.getSequenceNames());
943       if (!sequenceNames.isEmpty()) // at least one sequence name in both
944       {
945         if (openLinkedAlignment(al, title))
946         {
947           return;
948         }
949       }
950     }
951     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
952     // provenance) should share the same dataset sequence
953
954     for (int i = 0; i < al.getHeight(); i++)
955     {
956       getAlignment().addSequence(al.getSequenceAt(i));
957     }
958     // TODO this call was done by SequenceFetcher but not FileLoader or
959     // CutAndPasteTransfer. Is it needed?
960     // JBPComment: this repositions the view to show the new sequences
961     // JBPComment: so it is needed for UX
962     setEndSeq(getAlignment().getHeight());
963     firePropertyChange("alignment", null, getAlignment().getSequences());
964   }
965
966   /**
967    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
968    * alignment. Returns true if the new alignment was opened, false if not,
969    * because the user declined the offer.
970    * 
971    * @param title
972    */
973   protected boolean openLinkedAlignment(AlignmentI al, String title)
974   {
975     String[] options = new String[]
976     { MessageManager.getString("action.no"),
977         MessageManager.getString("label.split_window"),
978         MessageManager.getString("label.new_window"), };
979     final String question = JvSwingUtils.wrapTooltip(true,
980             MessageManager.getString("label.open_linked_alignment?"));
981     int response = JOptionPane.showOptionDialog(Desktop.desktop, question,
982             MessageManager.getString("label.open_linked_alignment"),
983             JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
984             options, options[0]);
985
986     if (response != 1 && response != 2)
987     {
988       return false;
989     }
990     final boolean openSplitPane = (response == 1);
991     final boolean openInNewWindow = (response == 2);
992
993     /*
994      * Create the AlignFrame first (which creates the new alignment's datasets),
995      * before attempting sequence mapping.
996      */
997     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
998             AlignFrame.DEFAULT_HEIGHT);
999     newAlignFrame.setTitle(title);
1000
1001     /*
1002      * Identify protein and dna alignments. Make a copy of this one if opening
1003      * in a new split pane.
1004      */
1005     AlignmentI thisAlignment = openSplitPane ? new Alignment(getAlignment())
1006             : getAlignment();
1007     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
1008     final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
1009
1010     newAlignFrame.statusBar.setText(MessageManager.formatMessage(
1011             "label.successfully_loaded_file", new Object[]
1012             { title }));
1013
1014     // TODO if we want this (e.g. to enable reload of the alignment from file),
1015     // we will need to add parameters to the stack.
1016     // if (!protocol.equals(AppletFormatAdapter.PASTE))
1017     // {
1018     // alignFrame.setFileName(file, format);
1019     // }
1020
1021     if (openInNewWindow)
1022     {
1023       Desktop.addInternalFrame(newAlignFrame, title,
1024               AlignFrame.DEFAULT_WIDTH,
1025               AlignFrame.DEFAULT_HEIGHT);
1026     }
1027
1028     /*
1029      * Try to find mappings for at least one sequence. Any mappings made will be
1030      * added to the protein alignment.
1031      */
1032     MappingResult mapped = AlignmentUtils.mapProteinToCdna(protein, cdna);
1033     if (mapped != MappingResult.Mapped)
1034     {
1035       /*
1036        * No mapping possible - warn the user, but leave window open.
1037        */
1038       final String msg = JvSwingUtils.wrapTooltip(true,
1039               MessageManager.getString("label.mapping_failed"));
1040       JOptionPane.showInternalMessageDialog(Desktop.desktop, msg,
1041               MessageManager.getString("label.no_mappings"),
1042               JOptionPane.WARNING_MESSAGE);
1043     }
1044
1045     try
1046     {
1047       newAlignFrame.setMaximum(jalview.bin.Cache.getDefault(
1048               "SHOW_FULLSCREEN",
1049               false));
1050     } catch (java.beans.PropertyVetoException ex)
1051     {
1052     }
1053
1054     if (openSplitPane)
1055     {
1056       protein = openSplitFrame(newAlignFrame, thisAlignment);
1057     }
1058
1059     /*
1060      * Register the mappings (held on the protein alignment) with the
1061      * StructureSelectionManager (for mouseover linking).
1062      */
1063     final StructureSelectionManager ssm = StructureSelectionManager
1064             .getStructureSelectionManager(Desktop.instance);
1065     ssm.addMappings(protein.getCodonFrames());
1066
1067     return true;
1068   }
1069
1070   /**
1071    * Helper method to open a new SplitFrame holding linked dna and protein
1072    * alignments.
1073    * 
1074    * @param newAlignFrame
1075    *          containing a new alignment to be shown
1076    * @param existingAlignment
1077    *          an existing alignment to be copied for display in the split frame
1078    * @return the protein alignment in the split frame
1079    */
1080   protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
1081           AlignmentI existingAlignment)
1082   {
1083     // TODO: move this to a factory/controller method ?
1084     /*
1085      * Open in split pane. DNA sequence above, protein below.
1086      */
1087     AlignFrame copyMe = new AlignFrame(existingAlignment,
1088             AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
1089     copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
1090
1091     AlignmentI al = newAlignFrame.viewport.getAlignment();
1092     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
1093             : newAlignFrame;
1094     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame
1095             : copyMe;
1096     AlignmentI protein = proteinFrame.viewport.getAlignment();
1097
1098     cdnaFrame.setVisible(true);
1099     proteinFrame.setVisible(true);
1100     String linkedTitle = MessageManager
1101             .getString("label.linked_view_title");
1102     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
1103     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
1104
1105     /*
1106      * Set the frames to listen for each other's edit and sort commands.
1107      */
1108     final StructureSelectionManager ssm = StructureSelectionManager
1109             .getStructureSelectionManager(Desktop.instance);
1110     ssm.addCommandListener(cdnaFrame.getViewport());
1111     ssm.addCommandListener(proteinFrame.getViewport());
1112
1113     /*
1114      * 'Coding complement' (dna/protein) views will mirror each others' edits,
1115      * selections, sorting etc as decided from time to time by the relevant
1116      * authorities.
1117      */
1118     proteinFrame.getViewport().setCodingComplement(cdnaFrame.getViewport());
1119     return protein;
1120   }
1121
1122   public AnnotationColumnChooser getAnnotationColumnSelectionState()
1123   {
1124     return annotationColumnSelectionState;
1125   }
1126
1127   public void setAnnotationColumnSelectionState(
1128           AnnotationColumnChooser currentAnnotationColumnSelectionState)
1129   {
1130     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
1131   }
1132
1133   @Override
1134   public void setIdWidth(int i)
1135   {
1136     super.setIdWidth(i);
1137     AlignmentPanel ap = getAlignPanel();
1138     if (ap != null)
1139     {
1140       // modify GUI elements to reflect geometry change
1141       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
1142               .getPreferredSize();
1143       idw.width = i;
1144       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
1145     }
1146   }
1147
1148   public Rectangle getExplodedGeometry()
1149   {
1150     return explodedGeometry;
1151   }
1152
1153   public void setExplodedGeometry(Rectangle explodedPosition)
1154   {
1155     this.explodedGeometry = explodedPosition;
1156   }
1157
1158   public boolean isGatherViewsHere()
1159   {
1160     return gatherViewsHere;
1161   }
1162
1163   public void setGatherViewsHere(boolean gatherViewsHere)
1164   {
1165     this.gatherViewsHere = gatherViewsHere;
1166   }
1167 }