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