a89174a4c3c5b4d035f2099abdf9fecaaba14c2b
[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.io.File;
71 import java.util.ArrayDeque;
72 import java.util.ArrayList;
73 import java.util.Deque;
74 import java.util.Hashtable;
75 import java.util.Set;
76 import java.util.Vector;
77
78 import javax.swing.JInternalFrame;
79 import javax.swing.JOptionPane;
80
81 /**
82  * DOCUMENT ME!
83  * 
84  * @author $author$
85  * @version $Revision: 1.141 $
86  */
87 public class AlignViewport extends AlignmentViewport implements
88         SelectionSource, VamsasSource, AlignViewportI, CommandListener
89 {
90   int startRes;
91
92   int endRes;
93
94   int startSeq;
95
96   int endSeq;
97
98
99   SequenceAnnotationOrder sortAnnotationsBy = null;
100
101   Font font;
102
103   NJTree currentTree = null;
104
105   boolean cursorMode = false;
106
107   boolean antiAlias = false;
108
109   Rectangle explodedPosition;
110
111   String viewName;
112
113   boolean gatherViewsHere = false;
114
115   private Deque<CommandI> historyList = new ArrayDeque<CommandI>();
116
117   private Deque<CommandI> redoList = new ArrayDeque<CommandI>();
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)));
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    * DOCUMENT ME!
470    * 
471    * @param f
472    *          DOCUMENT ME!
473    */
474   public void setFont(Font f)
475   {
476     font = f;
477
478     Container c = new Container();
479
480     java.awt.FontMetrics fm = c.getFontMetrics(font);
481     int w = viewStyle.getCharWidth(), ww = fm.charWidth('M'), h = viewStyle
482             .getCharHeight();
483     // only update width/height if the new font won't fit
484     if (h < fm.getHeight())
485     {
486       setCharHeight(fm.getHeight());
487     }
488     if (w < ww)
489     {
490       setCharWidth(ww);
491     }
492     viewStyle.setFontName(font.getName());
493     viewStyle.setFontStyle(font.getStyle());
494     viewStyle.setFontSize(font.getSize());
495
496     validCharWidth = true;
497   }
498
499   @Override
500   public void setViewStyle(ViewStyleI settingsForView)
501   {
502     super.setViewStyle(settingsForView);
503     setFont(new Font(viewStyle.getFontName(), viewStyle.getFontStyle(),
504             viewStyle.getFontSize()));
505
506   }
507   /**
508    * DOCUMENT ME!
509    * 
510    * @return DOCUMENT ME!
511    */
512   public Font getFont()
513   {
514     return font;
515   }
516
517   /**
518    * DOCUMENT ME!
519    * 
520    * @param align
521    *          DOCUMENT ME!
522    */
523   public void setAlignment(AlignmentI align)
524   {
525     if (alignment != null && alignment.getCodonFrames() != null)
526     {
527       StructureSelectionManager.getStructureSelectionManager(
528               Desktop.instance).removeMappings(alignment.getCodonFrames());
529     }
530     this.alignment = align;
531     if (alignment != null && alignment.getCodonFrames() != null)
532     {
533       StructureSelectionManager.getStructureSelectionManager(
534               Desktop.instance).addMappings(alignment.getCodonFrames());
535     }
536   }
537
538   /**
539    * DOCUMENT ME!
540    * 
541    * @return DOCUMENT ME!
542    */
543   public char getGapCharacter()
544   {
545     return getAlignment().getGapCharacter();
546   }
547
548   /**
549    * DOCUMENT ME!
550    * 
551    * @param gap
552    *          DOCUMENT ME!
553    */
554   public void setGapCharacter(char gap)
555   {
556     if (getAlignment() != null)
557     {
558       getAlignment().setGapCharacter(gap);
559     }
560   }
561
562   /**
563    * DOCUMENT ME!
564    * 
565    * @return DOCUMENT ME!
566    */
567   public ColumnSelection getColumnSelection()
568   {
569     return colSel;
570   }
571
572   /**
573    * DOCUMENT ME!
574    * 
575    * @param tree
576    *          DOCUMENT ME!
577    */
578   public void setCurrentTree(NJTree tree)
579   {
580     currentTree = tree;
581   }
582
583   /**
584    * DOCUMENT ME!
585    * 
586    * @return DOCUMENT ME!
587    */
588   public NJTree getCurrentTree()
589   {
590     return currentTree;
591   }
592
593   /**
594    * returns the visible column regions of the alignment
595    * 
596    * @param selectedRegionOnly
597    *          true to just return the contigs intersecting with the selected
598    *          area
599    * @return
600    */
601   public int[] getViewAsVisibleContigs(boolean selectedRegionOnly)
602   {
603     int[] viscontigs = null;
604     int start = 0, end = 0;
605     if (selectedRegionOnly && selectionGroup != null)
606     {
607       start = selectionGroup.getStartRes();
608       end = selectionGroup.getEndRes() + 1;
609     }
610     else
611     {
612       end = alignment.getWidth();
613     }
614     viscontigs = colSel.getVisibleContigs(start, end);
615     return viscontigs;
616   }
617
618   /**
619    * get hash of undo and redo list for the alignment
620    * 
621    * @return long[] { historyList.hashCode, redoList.hashCode };
622    */
623   public long[] getUndoRedoHash()
624   {
625     // TODO: JAL-1126
626     if (historyList == null || redoList == null)
627     {
628       return new long[]
629       { -1, -1 };
630     }
631     return new long[]
632     { historyList.hashCode(), this.redoList.hashCode() };
633   }
634
635   /**
636    * test if a particular set of hashcodes are different to the hashcodes for
637    * the undo and redo list.
638    * 
639    * @param undoredo
640    *          the stored set of hashcodes as returned by getUndoRedoHash
641    * @return true if the hashcodes differ (ie the alignment has been edited) or
642    *         the stored hashcode array differs in size
643    */
644   public boolean isUndoRedoHashModified(long[] undoredo)
645   {
646     if (undoredo == null)
647     {
648       return true;
649     }
650     long[] cstate = getUndoRedoHash();
651     if (cstate.length != undoredo.length)
652     {
653       return true;
654     }
655
656     for (int i = 0; i < cstate.length; i++)
657     {
658       if (cstate[i] != undoredo[i])
659       {
660         return true;
661       }
662     }
663     return false;
664   }
665
666   /**
667    * when set, view will scroll to show the highlighted position
668    */
669   public boolean followHighlight = true;
670
671   /**
672    * @return true if view should scroll to show the highlighted region of a
673    *         sequence
674    * @return
675    */
676   public boolean getFollowHighlight()
677   {
678     return followHighlight;
679   }
680
681   public boolean followSelection = true;
682
683   /**
684    * @return true if view selection should always follow the selections
685    *         broadcast by other selection sources
686    */
687   public boolean getFollowSelection()
688   {
689     return followSelection;
690   }
691
692   /**
693    * Send the current selection to be broadcast to any selection listeners.
694    */
695   public void sendSelection()
696   {
697     jalview.structure.StructureSelectionManager
698             .getStructureSelectionManager(Desktop.instance).sendSelection(
699                     new SequenceGroup(getSelectionGroup()),
700                     new ColumnSelection(getColumnSelection()), this);
701   }
702
703   /**
704    * return the alignPanel containing the given viewport. Use this to get the
705    * components currently handling the given viewport.
706    * 
707    * @param av
708    * @return null or an alignPanel guaranteed to have non-null alignFrame
709    *         reference
710    */
711   public AlignmentPanel getAlignPanel()
712   {
713     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(this
714             .getSequenceSetId());
715     for (int p = 0; aps != null && p < aps.length; p++)
716     {
717       if (aps[p].av == this)
718       {
719         return aps[p];
720       }
721     }
722     return null;
723   }
724
725   public boolean getSortByTree()
726   {
727     return sortByTree;
728   }
729
730   public void setSortByTree(boolean sort)
731   {
732     sortByTree = sort;
733   }
734
735   /**
736    * synthesize a column selection if none exists so it covers the given
737    * selection group. if wholewidth is false, no column selection is made if the
738    * selection group covers the whole alignment width.
739    * 
740    * @param sg
741    * @param wholewidth
742    */
743   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
744   {
745     int sgs, sge;
746     if (sg != null
747             && (sgs = sg.getStartRes()) >= 0
748             && sg.getStartRes() <= (sge = sg.getEndRes())
749             && (colSel == null || colSel.getSelected() == null || colSel
750                     .getSelected().size() == 0))
751     {
752       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
753       {
754         // do nothing
755         return;
756       }
757       if (colSel == null)
758       {
759         colSel = new ColumnSelection();
760       }
761       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
762       {
763         colSel.addElement(cspos);
764       }
765     }
766   }
767
768   public StructureSelectionManager getStructureSelectionManager()
769   {
770     return StructureSelectionManager
771             .getStructureSelectionManager(Desktop.instance);
772   }
773
774   /**
775    * 
776    * @param pdbEntries
777    * @return a series of SequenceI arrays, one for each PDBEntry, listing which
778    *         sequence in the alignment holds a reference to it
779    */
780   public SequenceI[][] collateForPDB(PDBEntry[] pdbEntries)
781   {
782     ArrayList<SequenceI[]> seqvectors = new ArrayList<SequenceI[]>();
783     for (PDBEntry pdb : pdbEntries)
784     {
785       ArrayList<SequenceI> seqs = new ArrayList<SequenceI>();
786       for (int i = 0; i < alignment.getHeight(); i++)
787       {
788         Vector pdbs = alignment.getSequenceAt(i).getDatasetSequence()
789                 .getPDBId();
790         if (pdbs == null)
791         {
792           continue;
793         }
794         SequenceI sq;
795         for (int p = 0; p < pdbs.size(); p++)
796         {
797           PDBEntry p1 = (PDBEntry) pdbs.elementAt(p);
798           if (p1.getId().equals(pdb.getId()))
799           {
800             if (!seqs.contains(sq = alignment.getSequenceAt(i)))
801             {
802               seqs.add(sq);
803             }
804
805             continue;
806           }
807         }
808       }
809       seqvectors.add(seqs.toArray(new SequenceI[seqs.size()]));
810     }
811     return seqvectors.toArray(new SequenceI[seqvectors.size()][]);
812   }
813
814   public boolean isNormaliseSequenceLogo()
815   {
816     return normaliseSequenceLogo;
817   }
818
819   public void setNormaliseSequenceLogo(boolean state)
820   {
821     normaliseSequenceLogo = state;
822   }
823
824   /**
825    * 
826    * @return true if alignment characters should be displayed
827    */
828   public boolean isValidCharWidth()
829   {
830     return validCharWidth;
831   }
832
833   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<String, AutoCalcSetting>();
834
835   private boolean showAutocalculatedAbove;
836
837   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
838   {
839     return calcIdParams.get(calcId);
840   }
841
842   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
843           boolean needsUpdate)
844   {
845     calcIdParams.put(calcId, settings);
846     // TODO: create a restart list to trigger any calculations that need to be
847     // restarted after load
848     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
849     if (needsUpdate)
850     {
851       Cache.log.debug("trigger update for " + calcId);
852     }
853   }
854
855   protected SequenceAnnotationOrder getSortAnnotationsBy()
856   {
857     return sortAnnotationsBy;
858   }
859
860   protected void setSortAnnotationsBy(SequenceAnnotationOrder sortAnnotationsBy)
861   {
862     this.sortAnnotationsBy = sortAnnotationsBy;
863   }
864
865   protected boolean isShowAutocalculatedAbove()
866   {
867     return showAutocalculatedAbove;
868   }
869
870   protected void setShowAutocalculatedAbove(boolean showAutocalculatedAbove)
871   {
872     this.showAutocalculatedAbove = showAutocalculatedAbove;
873   }
874
875   /**
876    * Method called when another alignment's edit (or possibly other) command is
877    * broadcast to here.
878    *
879    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
880    * 'unwind' the command on the source sequences (in simulation, not in fact),
881    * and then for each edit in turn:
882    * <ul>
883    * <li>compute the equivalent edit on the mapped sequences</li>
884    * <li>apply the mapped edit</li>
885    * <li>'apply' the source edit to the working copy of the source sequences</li>
886    * </ul>
887    * 
888    * @param command
889    * @param undo
890    * @param ssm
891    */
892   @Override
893   public void mirrorCommand(CommandI command, boolean undo,
894           StructureSelectionManager ssm, VamsasSource source)
895   {
896     /*
897      * ...work in progress... do nothing unless we are a 'complement' of the
898      * source May replace this with direct calls not via SSM.
899      */
900     if (source instanceof AlignViewportI
901             && ((AlignViewportI) source).getCodingComplement() == this)
902     {
903       // ok to continue;
904     }
905     else
906     {
907       return;
908     }
909
910     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
911             getGapCharacter());
912     if (mappedCommand != null)
913     {
914       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
915       mappedCommand.doCommand(views);
916       getAlignPanel().alignmentChanged();
917     }
918   }
919
920   @Override
921   public VamsasSource getVamsasSource()
922   {
923     return this;
924   }
925
926   /**
927    * Add one command to the command history list.
928    * 
929    * @param command
930    */
931   public void addToHistoryList(CommandI command)
932   {
933     if (this.historyList != null)
934     {
935       this.historyList.push(command);
936       broadcastCommand(command, false);
937     }
938   }
939
940   protected void broadcastCommand(CommandI command, boolean undo)
941   {
942     getStructureSelectionManager().commandPerformed(command, undo, getVamsasSource());
943   }
944
945   /**
946    * Add one command to the command redo list.
947    * 
948    * @param command
949    */
950   public void addToRedoList(CommandI command)
951   {
952     if (this.redoList != null)
953     {
954       this.redoList.push(command);
955     }
956     broadcastCommand(command, true);
957   }
958
959   /**
960    * Clear the command redo list.
961    */
962   public void clearRedoList()
963   {
964     if (this.redoList != null)
965     {
966       this.redoList.clear();
967     }
968   }
969
970   public void setHistoryList(Deque<CommandI> list)
971   {
972     this.historyList = list;
973   }
974
975   public Deque<CommandI> getHistoryList()
976   {
977     return this.historyList;
978   }
979
980   public void setRedoList(Deque<CommandI> list)
981   {
982     this.redoList = list;
983   }
984
985   public Deque<CommandI> getRedoList()
986   {
987     return this.redoList;
988   }
989
990   /**
991    * Add the sequences from the given alignment to this viewport. Optionally,
992    * may give the user the option to open a new frame, or split panel, with cDNA
993    * and protein linked.
994    * 
995    * @param al
996    * @param title
997    */
998   public void addAlignment(AlignmentI al, String title)
999   {
1000     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
1001
1002     // JBPComment: title is a largely redundant parameter at the moment
1003     // JBPComment: this really should be an 'insert/pre/append' controller
1004     // JBPComment: but the DNA/Protein check makes it a bit more complex
1005
1006     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
1007     // this comment:
1008     // TODO: create undo object for this JAL-1101
1009
1010     /*
1011      * If one alignment is protein and one nucleotide, with at least one
1012      * sequence name in common, offer to open a linked alignment.
1013      */
1014     if (getAlignment().isNucleotide() != al.isNucleotide())
1015     {
1016       // TODO: JAL-845 try a bit harder to link up imported sequences
1017       final Set<String> sequenceNames = getAlignment().getSequenceNames();
1018       sequenceNames.retainAll(al.getSequenceNames());
1019       if (!sequenceNames.isEmpty()) // at least one sequence name in both
1020       {
1021         if (openLinkedAlignment(al, title))
1022         {
1023           return;
1024         }
1025       }
1026     }
1027     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
1028     // provenance) should share the same dataset sequence
1029
1030     for (int i = 0; i < al.getHeight(); i++)
1031     {
1032       getAlignment().addSequence(al.getSequenceAt(i));
1033     }
1034     // TODO this call was done by SequenceFetcher but not FileLoader or
1035     // CutAndPasteTransfer. Is it needed?
1036     // JBPComment: this repositions the view to show the new sequences
1037     // JBPComment: so it is needed for UX
1038     setEndSeq(getAlignment().getHeight());
1039     firePropertyChange("alignment", null, getAlignment().getSequences());
1040   }
1041
1042   /**
1043    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
1044    * alignment. Returns true if the new alignment was opened, false if not,
1045    * because the user declined the offer.
1046    * 
1047    * @param title
1048    */
1049   protected boolean openLinkedAlignment(AlignmentI al, String title)
1050   {
1051     String[] options = new String[]
1052     { MessageManager.getString("action.no"),
1053         MessageManager.getString("label.split_window"),
1054         MessageManager.getString("label.new_window"), };
1055     final String question = JvSwingUtils.wrapTooltip(true,
1056             MessageManager.getString("label.open_linked_alignment?"));
1057     int response = JOptionPane.showOptionDialog(Desktop.desktop, question,
1058             MessageManager.getString("label.open_linked_alignment"),
1059             JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
1060             options, options[0]);
1061
1062     if (response != 1 && response != 2)
1063     {
1064       return false;
1065     }
1066     final boolean openSplitPane = (response == 1);
1067     final boolean openInNewWindow = (response == 2);
1068
1069     /*
1070      * Create the AlignFrame first (which creates the new alignment's datasets),
1071      * before attempting sequence mapping.
1072      */
1073     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
1074             AlignFrame.DEFAULT_HEIGHT);
1075     newAlignFrame.setTitle(title);
1076
1077     /*
1078      * Identify protein and dna alignments. Make a copy of this one if opening
1079      * in a new split pane.
1080      */
1081     AlignmentI thisAlignment = openSplitPane ? new Alignment(getAlignment())
1082             : getAlignment();
1083     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
1084     final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
1085
1086     newAlignFrame.statusBar.setText(MessageManager.formatMessage(
1087             "label.successfully_loaded_file", new Object[]
1088             { title }));
1089
1090     // TODO if we want this (e.g. to enable reload of the alignment from file),
1091     // we will need to add parameters to the stack.
1092     // if (!protocol.equals(AppletFormatAdapter.PASTE))
1093     // {
1094     // alignFrame.setFileName(file, format);
1095     // }
1096
1097     if (openInNewWindow)
1098     {
1099       Desktop.addInternalFrame(newAlignFrame, title,
1100               AlignFrame.DEFAULT_WIDTH,
1101               AlignFrame.DEFAULT_HEIGHT);
1102     }
1103
1104     /*
1105      * Try to find mappings for at least one sequence. Any mappings made will be
1106      * added to the protein alignment.
1107      */
1108     MappingResult mapped = AlignmentUtils.mapProteinToCdna(protein, cdna);
1109     final StructureSelectionManager ssm = StructureSelectionManager
1110             .getStructureSelectionManager(Desktop.instance);
1111     if (mapped != MappingResult.Mapped)
1112     {
1113       /*
1114        * No mapping possible - warn the user, but leave window open.
1115        */
1116       final String msg = JvSwingUtils.wrapTooltip(true,
1117               MessageManager.getString("label.mapping_failed"));
1118       JOptionPane.showInternalMessageDialog(Desktop.desktop, msg,
1119               MessageManager.getString("label.no_mappings"),
1120               JOptionPane.WARNING_MESSAGE);
1121     }
1122
1123     try
1124     {
1125       newAlignFrame.setMaximum(jalview.bin.Cache.getDefault(
1126               "SHOW_FULLSCREEN",
1127               false));
1128     } catch (java.beans.PropertyVetoException ex)
1129     {
1130     }
1131
1132     if (openSplitPane)
1133     {
1134       // TODO: move this kind of constructor stuff to a factory/controller
1135       // method ?
1136       /*
1137        * Open in split pane. DNA sequence above, protein below.
1138        */
1139       AlignFrame copyMe = new AlignFrame(thisAlignment,
1140               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
1141       copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
1142       final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
1143               : newAlignFrame;
1144       final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame
1145               : copyMe;
1146       protein = proteinFrame.viewport.getAlignment();
1147
1148       cdnaFrame.setVisible(true);
1149       proteinFrame.setVisible(true);
1150       String sep = String.valueOf(File.separatorChar);
1151       String proteinShortName = proteinFrame.getTitle().substring(
1152               proteinFrame.getTitle().lastIndexOf(sep) + 1);
1153       String dnaShortName = cdnaFrame.getTitle().substring(
1154               cdnaFrame.getTitle().lastIndexOf(sep) + 1);
1155       String linkedTitle = MessageManager.formatMessage(
1156               "label.linked_view_title", dnaShortName, proteinShortName);
1157       JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
1158       Desktop.addInternalFrame(splitFrame, linkedTitle,
1159               AlignFrame.DEFAULT_WIDTH,
1160               AlignFrame.DEFAULT_HEIGHT);
1161
1162       /*
1163        * Set the frames to listen for each other's edit and sort commands.
1164        */
1165       ssm.addCommandListener(cdnaFrame.getViewport());
1166       ssm.addCommandListener(proteinFrame.getViewport());
1167
1168       /*
1169        * 'Coding complement' (dna/protein) views will mirror each others' edits,
1170        * selections, sorting etc as decided from time to time by the relevant
1171        * authorities.
1172        */
1173       proteinFrame.getViewport().setCodingComplement(cdnaFrame.getViewport());
1174     }
1175
1176     /*
1177      * Register the mappings (held on the protein alignment) with the
1178      * StructureSelectionManager (for mouseover linking).
1179      */
1180     ssm.addMappings(protein.getCodonFrames());
1181
1182     return true;
1183   }
1184
1185   public AnnotationColumnChooser getAnnotationColumnSelectionState()
1186   {
1187     return annotationColumnSelectionState;
1188   }
1189
1190   public void setAnnotationColumnSelectionState(
1191           AnnotationColumnChooser currentAnnotationColumnSelectionState)
1192   {
1193     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
1194   }
1195
1196   @Override
1197   public void setIdWidth(int i)
1198   {
1199     super.setIdWidth(i);
1200     AlignmentPanel ap = getAlignPanel();
1201     if (ap != null)
1202     {
1203       // modify GUI elements to reflect geometry change
1204       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
1205               .getPreferredSize();
1206       idw.width = i;
1207       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
1208     }
1209   }
1210 }