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