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