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