Minor updates
[jalview.git] / src / jalview / gui / AlignFrame.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.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingsI;
31 import jalview.api.AlignFrameI;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignViewportI;
35 import jalview.api.AlignmentViewPanel;
36 //from JalviewLite imports import jalview.api.FeatureRenderer;
37 import jalview.api.FeatureSettingsControllerI;
38 import jalview.api.FeatureSettingsModelI;
39 import jalview.api.SplitContainerI;
40 import jalview.api.ViewStyleI;
41 import jalview.api.analysis.SimilarityParamsI;
42 import jalview.bin.Cache;
43 import jalview.bin.Jalview;
44 import jalview.commands.CommandI;
45 import jalview.commands.EditCommand;
46 import jalview.commands.EditCommand.Action;
47 import jalview.commands.OrderCommand;
48 import jalview.commands.RemoveGapColCommand;
49 import jalview.commands.RemoveGapsCommand;
50 import jalview.commands.SlideSequencesCommand;
51 import jalview.commands.TrimRegionCommand;
52 import jalview.datamodel.AlignExportSettingsAdapter;
53 import jalview.datamodel.AlignedCodonFrame;
54 import jalview.datamodel.Alignment;
55 import jalview.datamodel.AlignmentAnnotation;
56 import jalview.datamodel.AlignmentExportData;
57 import jalview.datamodel.AlignmentI;
58 import jalview.datamodel.AlignmentOrder;
59 import jalview.datamodel.AlignmentView;
60 import jalview.datamodel.ColumnSelection;
61 import jalview.datamodel.HiddenColumns;
62 import jalview.datamodel.PDBEntry;
63 import jalview.datamodel.SeqCigar;
64 import jalview.datamodel.Sequence;
65 import jalview.datamodel.SequenceGroup;
66 import jalview.datamodel.SequenceI;
67 import jalview.gui.ColourMenuHelper.ColourChangeListener;
68 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
69 import jalview.io.AlignmentProperties;
70 import jalview.io.AnnotationFile;
71 import jalview.io.BackupFiles;
72 import jalview.io.BioJsHTMLOutput;
73 import jalview.io.DataSourceType;
74 import jalview.io.FileFormat;
75 import jalview.io.FileFormatI;
76 import jalview.io.FileFormats;
77 import jalview.io.FileLoader;
78 import jalview.io.FileParse;
79 import jalview.io.FormatAdapter;
80 import jalview.io.HtmlSvgOutput;
81 import jalview.io.IdentifyFile;
82 import jalview.io.JPredFile;
83 import jalview.io.JalviewFileChooser;
84 import jalview.io.JalviewFileView;
85 import jalview.io.JnetAnnotationMaker;
86 import jalview.io.NewickFile;
87 import jalview.io.ScoreMatrixFile;
88 import jalview.io.TCoffeeScoreFile;
89 import jalview.io.vcf.VCFLoader;
90 import jalview.jbgui.GAlignFrame;
91 import jalview.project.Jalview2XML;
92 import jalview.schemes.ColourSchemeI;
93 import jalview.schemes.ColourSchemes;
94 import jalview.schemes.ResidueColourScheme;
95 import jalview.schemes.TCoffeeColourScheme;
96 import jalview.util.ImageMaker.TYPE;
97 import jalview.util.MessageManager;
98 import jalview.util.Platform;
99 import jalview.viewmodel.AlignmentViewport;
100 import jalview.viewmodel.ViewportRanges;
101 import jalview.ws.DBRefFetcher;
102 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
103 import jalview.ws.jws1.Discoverer;
104 import jalview.ws.jws2.Jws2Discoverer;
105 import jalview.ws.jws2.jabaws2.Jws2Instance;
106 import jalview.ws.seqfetcher.DbSourceProxy;
107
108 import java.awt.BorderLayout;
109 import java.awt.Color;
110 import java.awt.Component;
111 import java.awt.Dimension;
112 import java.awt.Rectangle;
113 import java.awt.Toolkit;
114 import java.awt.datatransfer.Clipboard;
115 import java.awt.datatransfer.DataFlavor;
116 import java.awt.datatransfer.StringSelection;
117 import java.awt.datatransfer.Transferable;
118 import java.awt.dnd.DnDConstants;
119 import java.awt.dnd.DropTargetDragEvent;
120 import java.awt.dnd.DropTargetDropEvent;
121 import java.awt.dnd.DropTargetEvent;
122 import java.awt.dnd.DropTargetListener;
123 import java.awt.event.ActionEvent;
124 import java.awt.event.ActionListener;
125 import java.awt.event.FocusAdapter;
126 import java.awt.event.FocusEvent;
127 import java.awt.event.ItemEvent;
128 import java.awt.event.ItemListener;
129 import java.awt.event.KeyAdapter;
130 import java.awt.event.KeyEvent;
131 import java.awt.event.MouseEvent;
132 import java.awt.print.PageFormat;
133 import java.awt.print.PrinterJob;
134 import java.beans.PropertyChangeEvent;
135 import java.io.File;
136 import java.io.FileWriter;
137 import java.io.PrintWriter;
138 import java.net.URL;
139 import java.util.ArrayList;
140 import java.util.Arrays;
141 import java.util.Deque;
142 import java.util.Enumeration;
143 import java.util.Hashtable;
144 import java.util.List;
145 import java.util.Vector;
146
147 import javax.swing.ButtonGroup;
148 import javax.swing.JCheckBoxMenuItem;
149 import javax.swing.JComponent;
150 import javax.swing.JEditorPane;
151 import javax.swing.JInternalFrame;
152 import javax.swing.JLabel;
153 import javax.swing.JLayeredPane;
154 import javax.swing.JMenu;
155 import javax.swing.JMenuItem;
156 import javax.swing.JPanel;
157 import javax.swing.JScrollPane;
158 import javax.swing.SwingUtilities;
159
160 import ext.vamsas.ServiceHandle;
161
162 /**
163  * DOCUMENT ME!
164  * 
165  * @author $author$
166  * @version $Revision$
167  */
168 @SuppressWarnings("serial")
169 public class AlignFrame extends GAlignFrame
170         implements AlignFrameI, DropTargetListener, IProgressIndicator,
171         AlignViewControllerGuiI, ColourChangeListener
172 {
173
174   public static final int DEFAULT_WIDTH = 700;
175
176   public static final int DEFAULT_HEIGHT = 500;
177
178   /*
179    * The currently displayed panel (selected tabbed view if more than one)
180    */
181   public AlignmentPanel alignPanel;
182
183   AlignViewport viewport;
184
185   public AlignViewControllerI avc;
186
187   List<AlignmentPanel> alignPanels = new ArrayList<>();
188
189   /**
190    * Last format used to load or save alignments in this window
191    */
192   FileFormatI currentFileFormat = null;
193
194   /**
195    * Current filename for this alignment
196    */
197   String fileName = null;
198
199   File fileObject;
200
201   /**
202    * Creates a new AlignFrame object with specific width and height.
203    * 
204    * @param al
205    * @param width
206    * @param height
207    */
208   public AlignFrame(AlignmentI al, int width, int height)
209   {
210     this(al, null, width, height);
211   }
212
213   /**
214    * Creates a new AlignFrame object with specific width, height and
215    * sequenceSetId
216    * 
217    * @param al
218    * @param width
219    * @param height
220    * @param sequenceSetId
221    */
222   public AlignFrame(AlignmentI al, int width, int height,
223           String sequenceSetId)
224   {
225     this(al, null, width, height, sequenceSetId);
226   }
227
228   /**
229    * Creates a new AlignFrame object with specific width, height and
230    * sequenceSetId
231    * 
232    * @param al
233    * @param width
234    * @param height
235    * @param sequenceSetId
236    * @param viewId
237    */
238   public AlignFrame(AlignmentI al, int width, int height,
239           String sequenceSetId, String viewId)
240   {
241     this(al, null, width, height, sequenceSetId, viewId);
242   }
243
244   /**
245    * new alignment window with hidden columns
246    * 
247    * @param al
248    *          AlignmentI
249    * @param hiddenColumns
250    *          ColumnSelection or null
251    * @param width
252    *          Width of alignment frame
253    * @param height
254    *          height of frame.
255    */
256   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257           int height)
258   {
259     this(al, hiddenColumns, width, height, null);
260   }
261
262   /**
263    * Create alignment frame for al with hiddenColumns, a specific width and
264    * height, and specific sequenceId
265    * 
266    * @param al
267    * @param hiddenColumns
268    * @param width
269    * @param height
270    * @param sequenceSetId
271    *          (may be null)
272    */
273   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
274           int height, String sequenceSetId)
275   {
276     this(al, hiddenColumns, width, height, sequenceSetId, null);
277   }
278
279   /**
280    * Create alignment frame for al with hiddenColumns, a specific width and
281    * height, and specific sequenceId
282    * 
283    * @param al
284    * @param hiddenColumns
285    * @param width
286    * @param height
287    * @param sequenceSetId
288    *          (may be null)
289    * @param viewId
290    *          (may be null)
291    */
292   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
293           int height, String sequenceSetId, String viewId)
294   {
295     setSize(width, height);
296
297     if (al.getDataset() == null)
298     {
299       al.setDataset(null);
300     }
301
302     viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
303
304     init();
305   }
306
307   public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
308           HiddenColumns hiddenColumns, int width, int height)
309   {
310     setSize(width, height);
311
312     if (al.getDataset() == null)
313     {
314       al.setDataset(null);
315     }
316
317     viewport = new AlignViewport(al, hiddenColumns);
318
319     if (hiddenSeqs != null && hiddenSeqs.length > 0)
320     {
321       viewport.hideSequence(hiddenSeqs);
322     }
323     init();
324   }
325
326   /**
327    * Make a new AlignFrame from existing alignmentPanels
328    * 
329    * @param ap
330    *          AlignmentPanel
331    * @param av
332    *          AlignViewport
333    */
334   public AlignFrame(AlignmentPanel ap)
335   {
336     viewport = ap.av;
337     alignPanel = ap;
338     init();
339   }
340
341   /**
342    * initalise the alignframe from the underlying viewport data and the
343    * configurations
344    */
345   void init()
346   {
347     boolean newPanel = (alignPanel == null);
348     viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
349     if (newPanel)
350     {
351       if (Platform.isJS())
352       {
353         // need to set this up front if NOANNOTATION is
354         // used in conjunction with SHOWOVERVIEW.
355
356         // I have not determined if this is appropriate for
357         // Jalview/Java, as it means we are setting this flag
358         // for all subsequent AlignFrames. For now, at least,
359         // I am setting it to be JalviewJS-only.
360
361         boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
362         viewport.setShowAnnotation(showAnnotation);
363       }
364       alignPanel = new AlignmentPanel(this, viewport);
365     }
366     addAlignmentPanel(alignPanel, newPanel);
367
368     // setBackground(Color.white); // BH 2019
369
370     if (!Jalview.isHeadlessMode())
371     {
372       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
373       // JalviewJS options
374       statusPanel.setVisible(Jalview.getInstance().getShowStatus());
375       alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
376     }
377
378     avc = new jalview.controller.AlignViewController(this, viewport,
379             alignPanel);
380     if (viewport.getAlignmentConservationAnnotation() == null)
381     {
382       // BLOSUM62Colour.setEnabled(false);
383       conservationMenuItem.setEnabled(false);
384       modifyConservation.setEnabled(false);
385       // PIDColour.setEnabled(false);
386       // abovePIDThreshold.setEnabled(false);
387       // modifyPID.setEnabled(false);
388     }
389
390     String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
391             "No sort");
392
393     if (sortby.equals("Id"))
394     {
395       sortIDMenuItem_actionPerformed(null);
396     }
397     else if (sortby.equals("Pairwise Identity"))
398     {
399       sortPairwiseMenuItem_actionPerformed(null);
400     }
401
402     setMenusFromViewport(viewport);
403     buildSortByAnnotationScoresMenu();
404     calculateTree.addActionListener(new ActionListener()
405     {
406
407       
408       @Override
409       public void actionPerformed(ActionEvent e)
410       {
411         openTreePcaDialog();
412       }
413     });
414     buildColourMenu();
415
416     if (Desktop.getDesktopPane() != null)
417     {
418       this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
419       if (!Platform.isJS())
420       {
421         addServiceListeners();
422       }
423       setGUINucleotide();
424     }
425
426     if (viewport.getWrapAlignment())
427     {
428       wrapMenuItem_actionPerformed(null);
429     }
430
431     if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
432     {
433       this.overviewMenuItem_actionPerformed(null);
434     }
435
436     addKeyListener();
437
438     final List<AlignmentPanel> selviews = new ArrayList<>();
439     final List<AlignmentPanel> origview = new ArrayList<>();
440     final String menuLabel = MessageManager
441             .getString("label.copy_format_from");
442     ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
443             new ViewSetProvider()
444             {
445
446               
447               @Override
448               public AlignmentPanel[] getAllAlignmentPanels()
449               {
450                 origview.clear();
451                 origview.add(alignPanel);
452                 // make an array of all alignment panels except for this one
453                 List<AlignmentPanel> aps = new ArrayList<>(
454                         Arrays.asList(Desktop.getAlignmentPanels(null)));
455                 aps.remove(AlignFrame.this.alignPanel);
456                 return aps.toArray(new AlignmentPanel[aps.size()]);
457               }
458             }, selviews, new ItemListener()
459             {
460
461               
462               @Override
463               public void itemStateChanged(ItemEvent e)
464               {
465                 if (origview.size() > 0)
466                 {
467                   final AlignmentPanel ap = origview.get(0);
468
469                   /*
470                    * Copy the ViewStyle of the selected panel to 'this one'.
471                    * Don't change value of 'scaleProteinAsCdna' unless copying
472                    * from a SplitFrame.
473                    */
474                   ViewStyleI vs = selviews.get(0).getAlignViewport()
475                           .getViewStyle();
476                   boolean fromSplitFrame = selviews.get(0)
477                           .getAlignViewport().getCodingComplement() != null;
478                   if (!fromSplitFrame)
479                   {
480                     vs.setScaleProteinAsCdna(ap.getAlignViewport()
481                             .getViewStyle().isScaleProteinAsCdna());
482                   }
483                   ap.getAlignViewport().setViewStyle(vs);
484
485                   /*
486                    * Also rescale ViewStyle of SplitFrame complement if there is
487                    * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
488                    * the whole ViewStyle (allow cDNA protein to have different
489                    * fonts)
490                    */
491                   AlignViewportI complement = ap.getAlignViewport()
492                           .getCodingComplement();
493                   if (complement != null && vs.isScaleProteinAsCdna())
494                   {
495                     AlignFrame af = Desktop.getAlignFrameFor(complement);
496                     ((SplitFrame) af.getSplitViewContainer())
497                             .adjustLayout();
498                     af.setMenusForViewport();
499                   }
500
501                   ap.updateLayout();
502                   ap.setSelected(true);
503                   ap.alignFrame.setMenusForViewport();
504
505                 }
506               }
507             });
508     if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
509             .indexOf("devel") > -1
510             || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
511                     .indexOf("test") > -1)
512     {
513       formatMenu.add(vsel);
514     }
515     addFocusListener(new FocusAdapter()
516     {
517       
518       @Override
519       public void focusGained(FocusEvent e)
520       {
521         Jalview.setCurrentAlignFrame(AlignFrame.this);
522       }
523     });
524
525   }
526
527   /**
528    * Change the filename and format for the alignment, and enable the 'reload'
529    * button functionality.
530    * 
531    * @param file
532    *          valid filename
533    * @param format
534    *          format of file
535    */
536   public void setFileName(String file, FileFormatI format)
537   {
538     fileName = file;
539     setFileFormat(format);
540     reload.setEnabled(true);
541   }
542
543   /**
544    * JavaScript will have this, maybe others. More dependable than a file name
545    * and maintains a reference to the actual bytes loaded.
546    * 
547    * @param file
548    */
549   public void setFileObject(File file)
550   {
551     this.fileObject = file;
552   }
553
554   /**
555    * Add a KeyListener with handlers for various KeyPressed and KeyReleased
556    * events
557    */
558   void addKeyListener()
559   {
560     addKeyListener(new KeyAdapter()
561     {
562       
563       @Override
564       public void keyPressed(KeyEvent evt)
565       {
566         if (viewport.cursorMode
567                 && ((evt.getKeyCode() >= KeyEvent.VK_0
568                         && evt.getKeyCode() <= KeyEvent.VK_9)
569                         || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
570                                 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
571                 && Character.isDigit(evt.getKeyChar()))
572         {
573           alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
574         }
575
576         switch (evt.getKeyCode())
577         {
578
579         case KeyEvent.VK_ESCAPE: // escape key
580                                  // alignPanel.deselectAllSequences();
581           alignPanel.deselectAllSequences();
582           break;
583
584         case KeyEvent.VK_DOWN:
585           if (evt.isAltDown() || !viewport.cursorMode)
586           {
587             moveSelectedSequences(false);
588           }
589           if (viewport.cursorMode)
590           {
591             alignPanel.getSeqPanel().moveCursor(0, 1);
592           }
593           break;
594
595         case KeyEvent.VK_UP:
596           if (evt.isAltDown() || !viewport.cursorMode)
597           {
598             moveSelectedSequences(true);
599           }
600           if (viewport.cursorMode)
601           {
602             alignPanel.getSeqPanel().moveCursor(0, -1);
603           }
604
605           break;
606
607         case KeyEvent.VK_LEFT:
608           if (evt.isAltDown() || !viewport.cursorMode)
609           {
610             slideSequences(false,
611                     alignPanel.getSeqPanel().getKeyboardNo1());
612           }
613           else
614           {
615             alignPanel.getSeqPanel().moveCursor(-1, 0);
616           }
617
618           break;
619
620         case KeyEvent.VK_RIGHT:
621           if (evt.isAltDown() || !viewport.cursorMode)
622           {
623             slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
624           }
625           else
626           {
627             alignPanel.getSeqPanel().moveCursor(1, 0);
628           }
629           break;
630
631         case KeyEvent.VK_SPACE:
632           if (viewport.cursorMode)
633           {
634             alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
635                     || evt.isShiftDown() || evt.isAltDown());
636           }
637           break;
638
639         // case KeyEvent.VK_A:
640         // if (viewport.cursorMode)
641         // {
642         // alignPanel.seqPanel.insertNucAtCursor(false,"A");
643         // //System.out.println("A");
644         // }
645         // break;
646         /*
647          * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
648          * System.out.println("closing bracket"); } break;
649          */
650         case KeyEvent.VK_DELETE:
651         case KeyEvent.VK_BACK_SPACE:
652           if (!viewport.cursorMode)
653           {
654             cut_actionPerformed();
655           }
656           else
657           {
658             alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
659                     || evt.isShiftDown() || evt.isAltDown());
660           }
661
662           break;
663
664         case KeyEvent.VK_S:
665           if (viewport.cursorMode)
666           {
667             alignPanel.getSeqPanel().setCursorRow();
668           }
669           break;
670         case KeyEvent.VK_C:
671           if (viewport.cursorMode && !evt.isControlDown())
672           {
673             alignPanel.getSeqPanel().setCursorColumn();
674           }
675           break;
676         case KeyEvent.VK_P:
677           if (viewport.cursorMode)
678           {
679             alignPanel.getSeqPanel().setCursorPosition();
680           }
681           break;
682
683         case KeyEvent.VK_ENTER:
684         case KeyEvent.VK_COMMA:
685           if (viewport.cursorMode)
686           {
687             alignPanel.getSeqPanel().setCursorRowAndColumn();
688           }
689           break;
690
691         case KeyEvent.VK_Q:
692           if (viewport.cursorMode)
693           {
694             alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
695           }
696           break;
697         case KeyEvent.VK_M:
698           if (viewport.cursorMode)
699           {
700             alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
701           }
702           break;
703
704         case KeyEvent.VK_F2:
705           viewport.cursorMode = !viewport.cursorMode;
706           setStatus(MessageManager
707                   .formatMessage("label.keyboard_editing_mode", new String[]
708                   { (viewport.cursorMode ? "on" : "off") }));
709           if (viewport.cursorMode)
710           {
711             ViewportRanges ranges = viewport.getRanges();
712             alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
713                     .getStartRes();
714             alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
715                     .getStartSeq();
716           }
717           alignPanel.getSeqPanel().seqCanvas.repaint();
718           break;
719
720         case KeyEvent.VK_F1:
721           try
722           {
723             Help.showHelpWindow();
724           } catch (Exception ex)
725           {
726             ex.printStackTrace();
727           }
728           break;
729         case KeyEvent.VK_H:
730         {
731           boolean toggleSeqs = !evt.isControlDown();
732           boolean toggleCols = !evt.isShiftDown();
733           toggleHiddenRegions(toggleSeqs, toggleCols);
734           break;
735         }
736         case KeyEvent.VK_B:
737         {
738           boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
739           boolean modifyExisting = true; // always modify, don't clear
740                                          // evt.isShiftDown();
741           boolean invertHighlighted = evt.isAltDown();
742           avc.markHighlightedColumns(invertHighlighted, modifyExisting,
743                   toggleSel);
744           break;
745         }
746         case KeyEvent.VK_PAGE_UP:
747           viewport.getRanges().pageUp();
748           break;
749         case KeyEvent.VK_PAGE_DOWN:
750           viewport.getRanges().pageDown();
751           break;
752         }
753       }
754
755       
756       @Override
757       public void keyReleased(KeyEvent evt)
758       {
759         switch (evt.getKeyCode())
760         {
761         case KeyEvent.VK_LEFT:
762           if (evt.isAltDown() || !viewport.cursorMode)
763           {
764             viewport.firePropertyChange("alignment", null,
765                     viewport.getAlignment().getSequences());
766           }
767           break;
768
769         case KeyEvent.VK_RIGHT:
770           if (evt.isAltDown() || !viewport.cursorMode)
771           {
772             viewport.firePropertyChange("alignment", null,
773                     viewport.getAlignment().getSequences());
774           }
775           break;
776         }
777       }
778     });
779   }
780
781   public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
782   {
783     ap.alignFrame = this;
784     avc = new jalview.controller.AlignViewController(this, viewport,
785             alignPanel);
786
787     alignPanels.add(ap);
788
789     PaintRefresher.Register(ap, ap.av.getSequenceSetId());
790
791     int aSize = alignPanels.size();
792
793     tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
794
795     if (aSize == 1 && ap.av.getViewName() == null)
796     {
797       this.getContentPane().add(ap, BorderLayout.CENTER);
798     }
799     else
800     {
801       if (aSize == 2)
802       {
803         setInitialTabVisible();
804       }
805
806       expandViews.setEnabled(true);
807       gatherViews.setEnabled(true);
808       tabbedPane.addTab(ap.av.getViewName(), ap);
809
810       ap.setVisible(false);
811     }
812
813     if (newPanel)
814     {
815       if (ap.av.isPadGaps())
816       {
817         ap.av.getAlignment().padGaps();
818       }
819       if (Jalview.getInstance().getStartCalculations())
820       {
821         ap.av.updateConservation(ap);
822         ap.av.updateConsensus(ap);
823         ap.av.updateStrucConsensus(ap);
824       }
825     }
826   }
827
828   public void setInitialTabVisible()
829   {
830     expandViews.setEnabled(true);
831     gatherViews.setEnabled(true);
832     tabbedPane.setVisible(true);
833     AlignmentPanel first = alignPanels.get(0);
834     tabbedPane.addTab(first.av.getViewName(), first);
835     this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
836   }
837
838   public AlignViewport getViewport()
839   {
840     return viewport;
841   }
842
843   /* Set up intrinsic listeners for dynamically generated GUI bits. */
844   private void addServiceListeners()
845   {
846     final java.beans.PropertyChangeListener thisListener;
847     Desktop.getInstance().addJalviewPropertyChangeListener("services",
848             thisListener = new java.beans.PropertyChangeListener()
849             {
850               
851               @Override
852               public void propertyChange(PropertyChangeEvent evt)
853               {
854                 // // System.out.println("Discoverer property change.");
855                 // if (evt.getPropertyName().equals("services"))
856                 {
857                   SwingUtilities.invokeLater(new Runnable()
858                   {
859
860                     
861                     @Override
862                     public void run()
863                     {
864                       System.err.println(
865                               "Rebuild WS Menu for service change");
866                       BuildWebServiceMenu();
867                     }
868
869                   });
870                 }
871               }
872             });
873     addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
874     {
875       
876       @Override
877       public void internalFrameClosed(
878               javax.swing.event.InternalFrameEvent evt)
879       {
880         // System.out.println("deregistering discoverer listener");
881         Desktop.getInstance().removeJalviewPropertyChangeListener(
882                 "services", thisListener);
883         closeMenuItem_actionPerformed(true);
884       }
885     });
886     // Finally, build the menu once to get current service state
887     new Thread(new Runnable()
888     {
889       
890       @Override
891       public void run()
892       {
893         BuildWebServiceMenu();
894       }
895     }).start();
896   }
897
898   /**
899    * Configure menu items that vary according to whether the alignment is
900    * nucleotide or protein
901    */
902   public void setGUINucleotide()
903   {
904     AlignmentI al = getViewport().getAlignment();
905     boolean nucleotide = al.isNucleotide();
906
907     loadVcf.setVisible(nucleotide);
908     showTranslation.setVisible(nucleotide);
909     showReverse.setVisible(nucleotide);
910     showReverseComplement.setVisible(nucleotide);
911     conservationMenuItem.setEnabled(!nucleotide);
912     modifyConservation
913             .setEnabled(!nucleotide && conservationMenuItem.isSelected());
914     showGroupConservation.setEnabled(!nucleotide);
915
916     showComplementMenuItem
917             .setText(nucleotide ? MessageManager.getString("label.protein")
918                     : MessageManager.getString("label.nucleotide"));
919   }
920
921   /**
922    * set up menus for the current viewport. This may be called after any
923    * operation that affects the data in the current view (selection changed,
924    * etc) to update the menus to reflect the new state.
925    */
926   
927   @Override
928   public void setMenusForViewport()
929   {
930     setMenusFromViewport(viewport);
931   }
932
933   /**
934    * Need to call this method when tabs are selected for multiple views, or when
935    * loading from Jalview2XML.java
936    * 
937    * @param av
938    *          AlignViewport
939    */
940   public void setMenusFromViewport(AlignViewport av)
941   {
942     padGapsMenuitem.setSelected(av.isPadGaps());
943     colourTextMenuItem.setSelected(av.isShowColourText());
944     abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
945     modifyPID.setEnabled(abovePIDThreshold.isSelected());
946     conservationMenuItem.setSelected(av.getConservationSelected());
947     modifyConservation.setEnabled(conservationMenuItem.isSelected());
948     seqLimits.setSelected(av.getShowJVSuffix());
949     idRightAlign.setSelected(av.isRightAlignIds());
950     centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
951     renderGapsMenuItem.setSelected(av.isRenderGaps());
952     wrapMenuItem.setSelected(av.getWrapAlignment());
953     scaleAbove.setVisible(av.getWrapAlignment());
954     scaleLeft.setVisible(av.getWrapAlignment());
955     scaleRight.setVisible(av.getWrapAlignment());
956     annotationPanelMenuItem.setState(av.isShowAnnotation());
957     // Show/hide annotations only enabled if annotation panel is shown
958     syncAnnotationMenuItems(av.isShowAnnotation());
959     viewBoxesMenuItem.setSelected(av.getShowBoxes());
960     viewTextMenuItem.setSelected(av.getShowText());
961     showNonconservedMenuItem.setSelected(av.getShowUnconserved());
962     showGroupConsensus.setSelected(av.isShowGroupConsensus());
963     showGroupConservation.setSelected(av.isShowGroupConservation());
964     showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
965     showSequenceLogo.setSelected(av.isShowSequenceLogo());
966     normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
967
968     ColourMenuHelper.setColourSelected(colourMenu,
969             av.getGlobalColourScheme());
970
971     showSeqFeatures.setSelected(av.isShowSequenceFeatures());
972     hiddenMarkers.setState(av.getShowHiddenMarkers());
973     applyToAllGroups.setState(av.getColourAppliesToAllGroups());
974     showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
975     showDbRefsMenuitem.setSelected(av.isShowDBRefs());
976     autoCalculate
977             .setSelected(av.getAutoCalculateConsensusAndConservation());
978     sortByTree.setSelected(av.sortByTree);
979     listenToViewSelections.setSelected(av.followSelection);
980
981     showProducts.setEnabled(canShowProducts());
982     setGroovyEnabled(Desktop.getGroovyConsole() != null);
983
984     updateEditMenuBar();
985   }
986
987   /**
988    * Set the enabled state of the 'Run Groovy' option in the Calculate menu
989    * 
990    * @param b
991    */
992   public void setGroovyEnabled(boolean b)
993   {
994     runGroovy.setEnabled(b);
995   }
996
997   private IProgressIndicator progressBar;
998
999   /*
1000    * (non-Javadoc)
1001    * 
1002    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1003    */
1004   
1005   @Override
1006   public void setProgressBar(String message, long id)
1007   {
1008     progressBar.setProgressBar(message, id);
1009   }
1010
1011   
1012   @Override
1013   public void registerHandler(final long id,
1014           final IProgressIndicatorHandler handler)
1015   {
1016     progressBar.registerHandler(id, handler);
1017   }
1018
1019   /**
1020    * 
1021    * @return true if any progress bars are still active
1022    */
1023   
1024   @Override
1025   public boolean operationInProgress()
1026   {
1027     return progressBar.operationInProgress();
1028   }
1029
1030   /**
1031    * Sets the text of the status bar. Note that setting a null or empty value
1032    * will cause the status bar to be hidden, with possibly undesirable flicker
1033    * of the screen layout.
1034    */
1035   
1036   @Override
1037   public void setStatus(String text)
1038   {
1039     statusBar.setText(text == null || text.isEmpty() ? " " : text);
1040   }
1041
1042   /*
1043    * Added so Castor Mapping file can obtain Jalview Version
1044    */
1045   public String getVersion()
1046   {
1047     return jalview.bin.Cache.getProperty("VERSION");
1048   }
1049
1050   public FeatureRenderer getFeatureRenderer()
1051   {
1052     return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1053   }
1054
1055   
1056   @Override
1057   public void fetchSequence_actionPerformed()
1058   {
1059     new SequenceFetcher(this);
1060   }
1061
1062   
1063   @Override
1064   public void addFromFile_actionPerformed(ActionEvent e)
1065   {
1066     Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1067   }
1068
1069   
1070   @Override
1071   public void reload_actionPerformed(ActionEvent e)
1072   {
1073     if (fileName == null)
1074     {
1075       return;
1076     }
1077     // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1078     // originating file's format
1079     // TODO: work out how to recover feature settings for correct view(s) when
1080     // file is reloaded.
1081     if (FileFormat.Jalview.equals(currentFileFormat))
1082     {
1083       JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1084       for (int i = 0; i < frames.length; i++)
1085       {
1086         if (frames[i] instanceof AlignFrame && frames[i] != this
1087                 && ((AlignFrame) frames[i]).fileName != null
1088                 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1089         {
1090           try
1091           {
1092             frames[i].setSelected(true);
1093             Desktop.getInstance().closeAssociatedWindows();
1094           } catch (java.beans.PropertyVetoException ex)
1095           {
1096           }
1097         }
1098
1099       }
1100       Desktop.getInstance().closeAssociatedWindows();
1101
1102       FileLoader loader = new FileLoader();
1103       DataSourceType protocol = fileName.startsWith("http:")
1104               ? DataSourceType.URL
1105               : DataSourceType.FILE;
1106       loader.loadFile(viewport,
1107               (fileObject == null ? fileName : fileObject), protocol,
1108               currentFileFormat);
1109     }
1110     else
1111     {
1112       Rectangle bounds = this.getBounds();
1113
1114       FileLoader loader = new FileLoader();
1115
1116       AlignFrame newframe = null;
1117
1118       if (fileObject == null)
1119       {
1120
1121         DataSourceType protocol = (fileName.startsWith("http:")
1122                 ? DataSourceType.URL
1123                 : DataSourceType.FILE);
1124         newframe = loader.loadFileWaitTillLoaded(fileName, protocol,
1125                 currentFileFormat);
1126       }
1127       else
1128       {
1129         newframe = loader.loadFileWaitTillLoaded(fileObject,
1130                 DataSourceType.FILE, currentFileFormat);
1131       }
1132
1133       newframe.setBounds(bounds);
1134       if (featureSettings != null && featureSettings.isShowing())
1135       {
1136         final Rectangle fspos = featureSettings.frame.getBounds();
1137         // TODO: need a 'show feature settings' function that takes bounds -
1138         // need to refactor Desktop.addFrame
1139         newframe.featureSettings_actionPerformed(null);
1140         final FeatureSettings nfs = newframe.featureSettings;
1141         SwingUtilities.invokeLater(new Runnable()
1142         {
1143           
1144           @Override
1145           public void run()
1146           {
1147             nfs.frame.setBounds(fspos);
1148           }
1149         });
1150         this.featureSettings.close();
1151         this.featureSettings = null;
1152       }
1153       this.closeMenuItem_actionPerformed(true);
1154     }
1155   }
1156
1157   
1158   @Override
1159   public void addFromText_actionPerformed(ActionEvent e)
1160   {
1161     Desktop.getInstance()
1162             .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1163   }
1164
1165   
1166   @Override
1167   public void addFromURL_actionPerformed(ActionEvent e)
1168   {
1169     Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1170   }
1171
1172   
1173   @Override
1174   public void save_actionPerformed(ActionEvent e)
1175   {
1176     if (fileName == null || (currentFileFormat == null)
1177             || fileName.startsWith("http"))
1178     {
1179       saveAs_actionPerformed();
1180     }
1181     else
1182     {
1183       saveAlignment(fileName, currentFileFormat);
1184     }
1185   }
1186
1187   /**
1188    * Saves the alignment to a file with a name chosen by the user, if necessary
1189    * warning if a file would be overwritten
1190    */
1191   
1192   @Override
1193   public void saveAs_actionPerformed()
1194   {
1195     String format = currentFileFormat == null ? null
1196             : currentFileFormat.getName();
1197     JalviewFileChooser chooser = JalviewFileChooser
1198             .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1199
1200     chooser.setFileView(new JalviewFileView());
1201     chooser.setDialogTitle(
1202             MessageManager.getString("label.save_alignment_to_file"));
1203     chooser.setToolTipText(MessageManager.getString("action.save"));
1204
1205     int value = chooser.showSaveDialog(this);
1206
1207     if (value != JalviewFileChooser.APPROVE_OPTION)
1208     {
1209       return;
1210     }
1211     currentFileFormat = chooser.getSelectedFormat();
1212     // todo is this (2005) test now obsolete - value is never null?
1213     while (currentFileFormat == null)
1214     {
1215       JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1216               MessageManager
1217                       .getString("label.select_file_format_before_saving"),
1218               MessageManager.getString("label.file_format_not_specified"),
1219               JvOptionPane.WARNING_MESSAGE);
1220       currentFileFormat = chooser.getSelectedFormat();
1221       value = chooser.showSaveDialog(this);
1222       if (value != JalviewFileChooser.APPROVE_OPTION)
1223       {
1224         return;
1225       }
1226     }
1227
1228     fileName = chooser.getSelectedFile().getPath();
1229
1230     Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1231     Cache.setProperty("LAST_DIRECTORY", fileName);
1232     saveAlignment(fileName, currentFileFormat);
1233   }
1234
1235   boolean lastSaveSuccessful = false;
1236
1237   FileFormatI lastFormatSaved;
1238
1239   String lastFilenameSaved;
1240
1241   /**
1242    * Raise a dialog or status message for the last call to saveAlignment.
1243    *
1244    * @return true if last call to saveAlignment(file, format) was successful.
1245    */
1246   public boolean isSaveAlignmentSuccessful()
1247   {
1248
1249     if (!lastSaveSuccessful)
1250     {
1251       JvOptionPane.showInternalMessageDialog(this, MessageManager
1252               .formatMessage("label.couldnt_save_file", new Object[]
1253               { lastFilenameSaved }),
1254               MessageManager.getString("label.error_saving_file"),
1255               JvOptionPane.WARNING_MESSAGE);
1256     }
1257     else
1258     {
1259
1260       setStatus(MessageManager.formatMessage(
1261               "label.successfully_saved_to_file_in_format", new Object[]
1262               { lastFilenameSaved, lastFormatSaved }));
1263
1264     }
1265     return lastSaveSuccessful;
1266   }
1267
1268   /**
1269    * Saves the alignment to the specified file path, in the specified format,
1270    * which may be an alignment format, or Jalview project format. If the
1271    * alignment has hidden regions, or the format is one capable of including
1272    * non-sequence data (features, annotations, groups), then the user may be
1273    * prompted to specify what to include in the output.
1274    * 
1275    * @param file
1276    * @param format
1277    */
1278   public void saveAlignment(String file, FileFormatI format)
1279   {
1280     lastSaveSuccessful = true;
1281     lastFilenameSaved = file;
1282     lastFormatSaved = format;
1283
1284     if (FileFormat.Jalview.equals(format))
1285     {
1286       String shortName = title;
1287       if (shortName.indexOf(File.separatorChar) > -1)
1288       {
1289         shortName = shortName
1290                 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1291       }
1292       lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1293               shortName);
1294
1295       statusBar.setText(MessageManager.formatMessage(
1296               "label.successfully_saved_to_file_in_format", new Object[]
1297               { fileName, format }));
1298
1299       return;
1300     }
1301
1302     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1303     Runnable cancelAction = new Runnable()
1304     {
1305       
1306       @Override
1307       public void run()
1308       {
1309         lastSaveSuccessful = false;
1310       }
1311     };
1312     Runnable outputAction = new Runnable()
1313     {
1314       
1315       @Override
1316       public void run()
1317       {
1318         // todo defer this to inside formatSequences (or later)
1319         AlignmentExportData exportData = viewport
1320                 .getAlignExportData(options);
1321         String output = new FormatAdapter(alignPanel, options)
1322                 .formatSequences(format, exportData.getAlignment(),
1323                         exportData.getOmitHidden(),
1324                         exportData.getStartEndPostions(),
1325                         viewport.getAlignment().getHiddenColumns());
1326         if (output == null)
1327         {
1328           lastSaveSuccessful = false;
1329         }
1330         else
1331         {
1332           // create backupfiles object and get new temp filename destination
1333           boolean doBackup = BackupFiles.getEnabled();
1334           BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1335           try
1336           {
1337             String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1338                     : file;
1339             PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1340
1341             out.print(output);
1342             out.close();
1343             AlignFrame.this.setTitle(file);
1344             statusBar.setText(MessageManager.formatMessage(
1345                     "label.successfully_saved_to_file_in_format",
1346                     new Object[]
1347                     { fileName, format.getName() }));
1348             lastSaveSuccessful = true;
1349           } catch (Exception ex)
1350           {
1351             lastSaveSuccessful = false;
1352             ex.printStackTrace();
1353           }
1354
1355           if (doBackup)
1356           {
1357             backupfiles.setWriteSuccess(lastSaveSuccessful);
1358             // do the backup file roll and rename the temp file to actual file
1359             lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1360           }
1361         }
1362       }
1363     };
1364
1365     /*
1366      * show dialog with export options if applicable; else just do it
1367      */
1368     if (AlignExportOptions.isNeeded(viewport, format))
1369     {
1370       AlignExportOptions choices = new AlignExportOptions(
1371               alignPanel.getAlignViewport(), format, options);
1372       choices.setResponseAction(0, outputAction);
1373       choices.setResponseAction(1, cancelAction);
1374       choices.showDialog();
1375     }
1376     else
1377     {
1378       outputAction.run();
1379     }
1380   }
1381
1382   /**
1383    * Outputs the alignment to textbox in the requested format, if necessary
1384    * first prompting the user for whether to include hidden regions or
1385    * non-sequence data
1386    * 
1387    * @param fileFormatName
1388    */
1389   
1390   @Override
1391   protected void outputText_actionPerformed(String fileFormatName)
1392   {
1393     FileFormatI fileFormat = FileFormats.getInstance()
1394             .forName(fileFormatName);
1395     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1396     Runnable outputAction = new Runnable()
1397     {
1398       
1399       @Override
1400       public void run()
1401       {
1402         // todo defer this to inside formatSequences (or later)
1403         AlignmentExportData exportData = viewport
1404                 .getAlignExportData(options);
1405         CutAndPasteTransfer cap = new CutAndPasteTransfer();
1406         cap.setForInput(null);
1407         try
1408         {
1409           FileFormatI format = fileFormat;
1410           cap.setText(new FormatAdapter(alignPanel, options)
1411                   .formatSequences(format, exportData.getAlignment(),
1412                           exportData.getOmitHidden(),
1413                           exportData.getStartEndPostions(),
1414                           viewport.getAlignment().getHiddenColumns()));
1415           Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1416                   "label.alignment_output_command", new Object[]
1417                   { fileFormat.getName() }), 600, 500);
1418         } catch (OutOfMemoryError oom)
1419         {
1420           new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1421                   oom);
1422           cap.dispose();
1423         }
1424       }
1425     };
1426
1427     /*
1428      * show dialog with export options if applicable; else just do it
1429      */
1430     if (AlignExportOptions.isNeeded(viewport, fileFormat))
1431     {
1432       AlignExportOptions choices = new AlignExportOptions(
1433               alignPanel.getAlignViewport(), fileFormat, options);
1434       choices.setResponseAction(0, outputAction);
1435       choices.showDialog();
1436     }
1437     else
1438     {
1439       outputAction.run();
1440     }
1441   }
1442
1443   /**
1444    * DOCUMENT ME!
1445    * 
1446    * @param e
1447    *          DOCUMENT ME!
1448    */
1449   
1450   @Override
1451   protected void htmlMenuItem_actionPerformed(ActionEvent e)
1452   {
1453     HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1454     htmlSVG.exportHTML(null);
1455   }
1456
1457   
1458   @Override
1459   public void bioJSMenuItem_actionPerformed(ActionEvent e)
1460   {
1461     BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1462     bjs.exportHTML(null);
1463   }
1464
1465   public void createImageMap(File file, String image)
1466   {
1467     alignPanel.makePNGImageMap(file, image);
1468   }
1469
1470   /**
1471    * Creates a PNG image of the alignment and writes it to the given file. If
1472    * the file is null, the user is prompted to choose a file.
1473    * 
1474    * @param f
1475    */
1476   
1477   @Override
1478   public void createPNG(File f)
1479   {
1480     alignPanel.makeAlignmentImage(TYPE.PNG, f);
1481   }
1482
1483   /**
1484    * Creates an EPS image of the alignment and writes it to the given file. If
1485    * the file is null, the user is prompted to choose a file.
1486    * 
1487    * @param f
1488    */
1489   
1490   @Override
1491   public void createEPS(File f)
1492   {
1493     alignPanel.makeAlignmentImage(TYPE.EPS, f);
1494   }
1495
1496   /**
1497    * Creates an SVG image of the alignment and writes it to the given file. If
1498    * the file is null, the user is prompted to choose a file.
1499    * 
1500    * @param f
1501    */
1502   
1503   @Override
1504   public void createSVG(File f)
1505   {
1506     alignPanel.makeAlignmentImage(TYPE.SVG, f);
1507   }
1508
1509   
1510   @Override
1511   public void pageSetup_actionPerformed(ActionEvent e)
1512   {
1513     PrinterJob printJob = PrinterJob.getPrinterJob();
1514     PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1515   }
1516
1517   /**
1518    * DOCUMENT ME!
1519    * 
1520    * @param e
1521    *          DOCUMENT ME!
1522    */
1523   
1524   @Override
1525   public void printMenuItem_actionPerformed(ActionEvent e)
1526   {
1527     // Putting in a thread avoids Swing painting problems
1528     PrintThread thread = new PrintThread(alignPanel);
1529     thread.start();
1530   }
1531
1532   
1533   @Override
1534   public void exportFeatures_actionPerformed(ActionEvent e)
1535   {
1536     new AnnotationExporter(alignPanel).exportFeatures();
1537   }
1538
1539   
1540   @Override
1541   public void exportAnnotations_actionPerformed(ActionEvent e)
1542   {
1543     new AnnotationExporter(alignPanel).exportAnnotations();
1544   }
1545
1546   
1547   @Override
1548   public void associatedData_actionPerformed(ActionEvent e)
1549   {
1550     final JalviewFileChooser chooser = new JalviewFileChooser(
1551             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1552     chooser.setFileView(new JalviewFileView());
1553     String tooltip = MessageManager
1554             .getString("label.load_jalview_annotations");
1555     chooser.setDialogTitle(tooltip);
1556     chooser.setToolTipText(tooltip);
1557     chooser.setResponseHandler(0, new Runnable()
1558     {
1559       
1560       @Override
1561       public void run()
1562       {
1563         String choice = chooser.getSelectedFile().getPath();
1564         jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1565         loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1566       }
1567     });
1568
1569     chooser.showOpenDialog(this);
1570   }
1571
1572   /**
1573    * Close the current view or all views in the alignment frame. If the frame
1574    * only contains one view then the alignment will be removed from memory.
1575    * 
1576    * @param closeAllTabs
1577    */
1578   
1579   @Override
1580   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1581   {
1582     if (alignPanels != null && alignPanels.size() < 2)
1583     {
1584       closeAllTabs = true;
1585     }
1586
1587     try
1588     {
1589       if (alignPanels != null)
1590       {
1591         if (closeAllTabs)
1592         {
1593           if (this.isClosed())
1594           {
1595             // really close all the windows - otherwise wait till
1596             // setClosed(true) is called
1597             for (int i = 0; i < alignPanels.size(); i++)
1598             {
1599               AlignmentPanel ap = alignPanels.get(i);
1600               ap.closePanel();
1601             }
1602           }
1603         }
1604         else
1605         {
1606           closeView(alignPanel);
1607         }
1608       }
1609
1610       if (closeAllTabs)
1611       {
1612         // JalviewJS-develop only
1613         //
1614         // if (featureSettings != null && featureSettings.isOpen())
1615         // {
1616         // featureSettings.close();
1617         // featureSettings = null;
1618         // }
1619         /*
1620          * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1621          * be called recursively, with the frame now in 'closed' state
1622          */
1623         this.setClosed(true);
1624       }
1625     } catch (Exception ex)
1626     {
1627       ex.printStackTrace();
1628     }
1629   }
1630
1631   /**
1632    * Close the specified panel and close up tabs appropriately.
1633    * 
1634    * @param panelToClose
1635    */
1636   public void closeView(AlignmentPanel panelToClose)
1637   {
1638     int index = tabbedPane.getSelectedIndex();
1639     int closedindex = tabbedPane.indexOfComponent(panelToClose);
1640     alignPanels.remove(panelToClose);
1641     panelToClose.closePanel();
1642     panelToClose = null;
1643
1644     tabbedPane.removeTabAt(closedindex);
1645     tabbedPane.validate();
1646
1647     if (index > closedindex || index == tabbedPane.getTabCount())
1648     {
1649       // modify currently selected tab index if necessary.
1650       index--;
1651     }
1652
1653     this.tabSelectionChanged(index);
1654   }
1655
1656   /**
1657    * DOCUMENT ME!
1658    */
1659   void updateEditMenuBar()
1660   {
1661
1662     if (viewport.getHistoryList().size() > 0)
1663     {
1664       undoMenuItem.setEnabled(true);
1665       CommandI command = viewport.getHistoryList().peek();
1666       undoMenuItem.setText(MessageManager
1667               .formatMessage("label.undo_command", new Object[]
1668               { command.getDescription() }));
1669     }
1670     else
1671     {
1672       undoMenuItem.setEnabled(false);
1673       undoMenuItem.setText(MessageManager.getString("action.undo"));
1674     }
1675
1676     if (viewport.getRedoList().size() > 0)
1677     {
1678       redoMenuItem.setEnabled(true);
1679
1680       CommandI command = viewport.getRedoList().peek();
1681       redoMenuItem.setText(MessageManager
1682               .formatMessage("label.redo_command", new Object[]
1683               { command.getDescription() }));
1684     }
1685     else
1686     {
1687       redoMenuItem.setEnabled(false);
1688       redoMenuItem.setText(MessageManager.getString("action.redo"));
1689     }
1690   }
1691
1692   
1693   @Override
1694   public void addHistoryItem(CommandI command)
1695   {
1696     if (command.getSize() > 0)
1697     {
1698       viewport.addToHistoryList(command);
1699       viewport.clearRedoList();
1700       updateEditMenuBar();
1701       viewport.updateHiddenColumns();
1702       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1703       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1704       // viewport.getColumnSelection()
1705       // .getHiddenColumns().size() > 0);
1706     }
1707   }
1708
1709   /**
1710    * 
1711    * @return alignment objects for all views
1712    */
1713   AlignmentI[] getViewAlignments()
1714   {
1715     if (alignPanels != null)
1716     {
1717       AlignmentI[] als = new AlignmentI[alignPanels.size()];
1718       int i = 0;
1719       for (AlignmentPanel ap : alignPanels)
1720       {
1721         als[i++] = ap.av.getAlignment();
1722       }
1723       return als;
1724     }
1725     if (viewport != null)
1726     {
1727       return new AlignmentI[] { viewport.getAlignment() };
1728     }
1729     return null;
1730   }
1731
1732   /**
1733    * DOCUMENT ME!
1734    * 
1735    * @param e
1736    *          DOCUMENT ME!
1737    */
1738   
1739   @Override
1740   protected void undoMenuItem_actionPerformed(ActionEvent e)
1741   {
1742     if (viewport.getHistoryList().isEmpty())
1743     {
1744       return;
1745     }
1746     CommandI command = viewport.getHistoryList().pop();
1747     viewport.addToRedoList(command);
1748     command.undoCommand(getViewAlignments());
1749
1750     AlignmentViewport originalSource = getOriginatingSource(command);
1751     updateEditMenuBar();
1752
1753     if (originalSource != null)
1754     {
1755       if (originalSource != viewport)
1756       {
1757         Cache.log.warn(
1758                 "Implementation worry: mismatch of viewport origin for undo");
1759       }
1760       originalSource.updateHiddenColumns();
1761       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1762       // null
1763       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1764       // viewport.getColumnSelection()
1765       // .getHiddenColumns().size() > 0);
1766       originalSource.firePropertyChange("alignment", null,
1767               originalSource.getAlignment().getSequences());
1768     }
1769   }
1770
1771   /**
1772    * DOCUMENT ME!
1773    * 
1774    * @param e
1775    *          DOCUMENT ME!
1776    */
1777   
1778   @Override
1779   protected void redoMenuItem_actionPerformed(ActionEvent e)
1780   {
1781     if (viewport.getRedoList().size() < 1)
1782     {
1783       return;
1784     }
1785
1786     CommandI command = viewport.getRedoList().pop();
1787     viewport.addToHistoryList(command);
1788     command.doCommand(getViewAlignments());
1789
1790     AlignmentViewport originalSource = getOriginatingSource(command);
1791     updateEditMenuBar();
1792
1793     if (originalSource != null)
1794     {
1795
1796       if (originalSource != viewport)
1797       {
1798         Cache.log.warn(
1799                 "Implementation worry: mismatch of viewport origin for redo");
1800       }
1801       originalSource.updateHiddenColumns();
1802       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1803       // null
1804       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1805       // viewport.getColumnSelection()
1806       // .getHiddenColumns().size() > 0);
1807       originalSource.firePropertyChange("alignment", null,
1808               originalSource.getAlignment().getSequences());
1809     }
1810   }
1811
1812   AlignmentViewport getOriginatingSource(CommandI command)
1813   {
1814     AlignmentViewport originalSource = null;
1815     // For sequence removal and addition, we need to fire
1816     // the property change event FROM the viewport where the
1817     // original alignment was altered
1818     AlignmentI al = null;
1819     if (command instanceof EditCommand)
1820     {
1821       EditCommand editCommand = (EditCommand) command;
1822       al = editCommand.getAlignment();
1823       List<Component> comps = PaintRefresher.components
1824               .get(viewport.getSequenceSetId());
1825
1826       for (Component comp : comps)
1827       {
1828         if (comp instanceof AlignmentPanel)
1829         {
1830           if (al == ((AlignmentPanel) comp).av.getAlignment())
1831           {
1832             originalSource = ((AlignmentPanel) comp).av;
1833             break;
1834           }
1835         }
1836       }
1837     }
1838
1839     if (originalSource == null)
1840     {
1841       // The original view is closed, we must validate
1842       // the current view against the closed view first
1843       if (al != null)
1844       {
1845         PaintRefresher.validateSequences(al, viewport.getAlignment());
1846       }
1847
1848       originalSource = viewport;
1849     }
1850
1851     return originalSource;
1852   }
1853
1854   /**
1855    * DOCUMENT ME!
1856    * 
1857    * @param up
1858    *          DOCUMENT ME!
1859    */
1860   public void moveSelectedSequences(boolean up)
1861   {
1862     SequenceGroup sg = viewport.getSelectionGroup();
1863
1864     if (sg == null)
1865     {
1866       return;
1867     }
1868     viewport.getAlignment().moveSelectedSequencesByOne(sg,
1869             viewport.getHiddenRepSequences(), up);
1870     alignPanel.paintAlignment(true, false);
1871   }
1872
1873   synchronized void slideSequences(boolean right, int size)
1874   {
1875     List<SequenceI> sg = new ArrayList<>();
1876     if (viewport.cursorMode)
1877     {
1878       sg.add(viewport.getAlignment()
1879               .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1880     }
1881     else if (viewport.getSelectionGroup() != null
1882             && viewport.getSelectionGroup().getSize() != viewport
1883                     .getAlignment().getHeight())
1884     {
1885       sg = viewport.getSelectionGroup()
1886               .getSequences(viewport.getHiddenRepSequences());
1887     }
1888
1889     if (sg.size() < 1)
1890     {
1891       return;
1892     }
1893
1894     List<SequenceI> invertGroup = new ArrayList<>();
1895
1896     for (SequenceI seq : viewport.getAlignment().getSequences())
1897     {
1898       if (!sg.contains(seq))
1899       {
1900         invertGroup.add(seq);
1901       }
1902     }
1903
1904     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1905
1906     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1907     for (int i = 0; i < invertGroup.size(); i++)
1908     {
1909       seqs2[i] = invertGroup.get(i);
1910     }
1911
1912     SlideSequencesCommand ssc;
1913     if (right)
1914     {
1915       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1916               viewport.getGapCharacter());
1917     }
1918     else
1919     {
1920       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1921               viewport.getGapCharacter());
1922     }
1923
1924     int groupAdjustment = 0;
1925     if (ssc.getGapsInsertedBegin() && right)
1926     {
1927       if (viewport.cursorMode)
1928       {
1929         alignPanel.getSeqPanel().moveCursor(size, 0);
1930       }
1931       else
1932       {
1933         groupAdjustment = size;
1934       }
1935     }
1936     else if (!ssc.getGapsInsertedBegin() && !right)
1937     {
1938       if (viewport.cursorMode)
1939       {
1940         alignPanel.getSeqPanel().moveCursor(-size, 0);
1941       }
1942       else
1943       {
1944         groupAdjustment = -size;
1945       }
1946     }
1947
1948     if (groupAdjustment != 0)
1949     {
1950       viewport.getSelectionGroup().setStartRes(
1951               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1952       viewport.getSelectionGroup().setEndRes(
1953               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1954     }
1955
1956     /*
1957      * just extend the last slide command if compatible; but not if in
1958      * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1959      */
1960     boolean appendHistoryItem = false;
1961     Deque<CommandI> historyList = viewport.getHistoryList();
1962     boolean inSplitFrame = getSplitViewContainer() != null;
1963     if (!inSplitFrame && historyList != null && historyList.size() > 0
1964             && historyList.peek() instanceof SlideSequencesCommand)
1965     {
1966       appendHistoryItem = ssc.appendSlideCommand(
1967               (SlideSequencesCommand) historyList.peek());
1968     }
1969
1970     if (!appendHistoryItem)
1971     {
1972       addHistoryItem(ssc);
1973     }
1974
1975     repaint();
1976   }
1977
1978   /**
1979    * DOCUMENT ME!
1980    * 
1981    * @param e
1982    *          DOCUMENT ME!
1983    */
1984   
1985   @Override
1986   protected void copy_actionPerformed()
1987   {
1988     if (viewport.getSelectionGroup() == null)
1989     {
1990       return;
1991     }
1992     // TODO: preserve the ordering of displayed alignment annotation in any
1993     // internal paste (particularly sequence associated annotation)
1994     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1995     String[] omitHidden = null;
1996
1997     if (viewport.hasHiddenColumns())
1998     {
1999       omitHidden = viewport.getViewAsString(true);
2000     }
2001
2002     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2003             seqs, omitHidden, null);
2004
2005     StringSelection ss = new StringSelection(output);
2006
2007     Desktop d = Desktop.getInstance();
2008     try
2009     {
2010       d.internalCopy = true;
2011       // Its really worth setting the clipboard contents
2012       // to empty before setting the large StringSelection!!
2013       Toolkit.getDefaultToolkit().getSystemClipboard()
2014               .setContents(new StringSelection(""), null);
2015
2016       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2017               Desktop.getInstance());
2018     } catch (OutOfMemoryError er)
2019     {
2020       new OOMWarning("copying region", er);
2021       return;
2022     }
2023
2024     HiddenColumns hiddenColumns = null;
2025     if (viewport.hasHiddenColumns())
2026     {
2027       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2028       int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2029
2030       // create new HiddenColumns object with copy of hidden regions
2031       // between startRes and endRes, offset by startRes
2032       hiddenColumns = new HiddenColumns(
2033               viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2034               hiddenCutoff, hiddenOffset);
2035     }
2036
2037     d.jalviewClipboard = new Object[] { seqs,
2038         viewport.getAlignment().getDataset(), hiddenColumns };
2039     setStatus(MessageManager.formatMessage(
2040             "label.copied_sequences_to_clipboard", new Object[]
2041             { Integer.valueOf(seqs.length).toString() }));
2042   }
2043
2044   /**
2045    * DOCUMENT ME!
2046    * 
2047    * @param e
2048    *          DOCUMENT ME!
2049    */
2050   
2051   @Override
2052   protected void pasteNew_actionPerformed(ActionEvent e)
2053   {
2054     paste(true);
2055   }
2056
2057   /**
2058    * DOCUMENT ME!
2059    * 
2060    * @param e
2061    *          DOCUMENT ME!
2062    */
2063   
2064   @Override
2065   protected void pasteThis_actionPerformed(ActionEvent e)
2066   {
2067     paste(false);
2068   }
2069
2070   /**
2071    * Paste contents of Jalview clipboard
2072    * 
2073    * @param newAlignment
2074    *          true to paste to a new alignment, otherwise add to this.
2075    */
2076   void paste(boolean newAlignment)
2077   {
2078     boolean externalPaste = true;
2079     try
2080     {
2081       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2082       Transferable contents = c.getContents(this);
2083
2084       if (contents == null)
2085       {
2086         return;
2087       }
2088
2089       String str;
2090       FileFormatI format;
2091       try
2092       {
2093         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2094         if (str.length() < 1)
2095         {
2096           return;
2097         }
2098
2099         format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2100
2101       } catch (OutOfMemoryError er)
2102       {
2103         new OOMWarning("Out of memory pasting sequences!!", er);
2104         return;
2105       }
2106
2107       SequenceI[] sequences;
2108       boolean annotationAdded = false;
2109       AlignmentI alignment = null;
2110
2111       Desktop d = Desktop.getInstance();
2112
2113       if (d.jalviewClipboard != null)
2114       {
2115         // The clipboard was filled from within Jalview, we must use the
2116         // sequences
2117         // And dataset from the copied alignment
2118         SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2119         // be doubly sure that we create *new* sequence objects.
2120         sequences = new SequenceI[newseq.length];
2121         for (int i = 0; i < newseq.length; i++)
2122         {
2123           sequences[i] = new Sequence(newseq[i]);
2124         }
2125         alignment = new Alignment(sequences);
2126         externalPaste = false;
2127       }
2128       else
2129       {
2130         // parse the clipboard as an alignment.
2131         alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2132                 format);
2133         sequences = alignment.getSequencesArray();
2134       }
2135
2136       int alwidth = 0;
2137       ArrayList<Integer> newGraphGroups = new ArrayList<>();
2138       int fgroup = -1;
2139
2140       if (newAlignment)
2141       {
2142
2143         if (d.jalviewClipboard != null)
2144         {
2145           // dataset is inherited
2146           alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2147         }
2148         else
2149         {
2150           // new dataset is constructed
2151           alignment.setDataset(null);
2152         }
2153         alwidth = alignment.getWidth() + 1;
2154       }
2155       else
2156       {
2157         AlignmentI pastedal = alignment; // preserve pasted alignment object
2158         // Add pasted sequences and dataset into existing alignment.
2159         alignment = viewport.getAlignment();
2160         alwidth = alignment.getWidth() + 1;
2161         // decide if we need to import sequences from an existing dataset
2162         boolean importDs = d.jalviewClipboard != null
2163                 && d.jalviewClipboard[1] != alignment.getDataset();
2164         // importDs==true instructs us to copy over new dataset sequences from
2165         // an existing alignment
2166         Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2167                                                                       // create
2168         // minimum dataset set
2169
2170         for (int i = 0; i < sequences.length; i++)
2171         {
2172           if (importDs)
2173           {
2174             newDs.addElement(null);
2175           }
2176           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2177           // paste
2178           if (importDs && ds != null)
2179           {
2180             if (!newDs.contains(ds))
2181             {
2182               newDs.setElementAt(ds, i);
2183               ds = new Sequence(ds);
2184               // update with new dataset sequence
2185               sequences[i].setDatasetSequence(ds);
2186             }
2187             else
2188             {
2189               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2190             }
2191           }
2192           else
2193           {
2194             // copy and derive new dataset sequence
2195             sequences[i] = sequences[i].deriveSequence();
2196             alignment.getDataset()
2197                     .addSequence(sequences[i].getDatasetSequence());
2198             // TODO: avoid creation of duplicate dataset sequences with a
2199             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2200           }
2201           alignment.addSequence(sequences[i]); // merges dataset
2202         }
2203         if (newDs != null)
2204         {
2205           newDs.clear(); // tidy up
2206         }
2207         if (alignment.getAlignmentAnnotation() != null)
2208         {
2209           for (AlignmentAnnotation alan : alignment
2210                   .getAlignmentAnnotation())
2211           {
2212             if (alan.graphGroup > fgroup)
2213             {
2214               fgroup = alan.graphGroup;
2215             }
2216           }
2217         }
2218         if (pastedal.getAlignmentAnnotation() != null)
2219         {
2220           // Add any annotation attached to alignment.
2221           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2222           for (int i = 0; i < alann.length; i++)
2223           {
2224             annotationAdded = true;
2225             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2226             {
2227               AlignmentAnnotation newann = new AlignmentAnnotation(
2228                       alann[i]);
2229               if (newann.graphGroup > -1)
2230               {
2231                 if (newGraphGroups.size() <= newann.graphGroup
2232                         || newGraphGroups.get(newann.graphGroup) == null)
2233                 {
2234                   for (int q = newGraphGroups
2235                           .size(); q <= newann.graphGroup; q++)
2236                   {
2237                     newGraphGroups.add(q, null);
2238                   }
2239                   newGraphGroups.set(newann.graphGroup,
2240                           Integer.valueOf(++fgroup));
2241                 }
2242                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2243                         .intValue();
2244               }
2245
2246               newann.padAnnotation(alwidth);
2247               alignment.addAnnotation(newann);
2248             }
2249           }
2250         }
2251       }
2252       if (!newAlignment)
2253       {
2254         // /////
2255         // ADD HISTORY ITEM
2256         //
2257         addHistoryItem(new EditCommand(
2258                 MessageManager.getString("label.add_sequences"),
2259                 Action.PASTE, sequences, 0, alignment.getWidth(),
2260                 alignment));
2261       }
2262       // Add any annotations attached to sequences
2263       for (int i = 0; i < sequences.length; i++)
2264       {
2265         if (sequences[i].getAnnotation() != null)
2266         {
2267           AlignmentAnnotation newann;
2268           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2269           {
2270             annotationAdded = true;
2271             newann = sequences[i].getAnnotation()[a];
2272             newann.adjustForAlignment();
2273             newann.padAnnotation(alwidth);
2274             if (newann.graphGroup > -1)
2275             {
2276               if (newann.graphGroup > -1)
2277               {
2278                 if (newGraphGroups.size() <= newann.graphGroup
2279                         || newGraphGroups.get(newann.graphGroup) == null)
2280                 {
2281                   for (int q = newGraphGroups
2282                           .size(); q <= newann.graphGroup; q++)
2283                   {
2284                     newGraphGroups.add(q, null);
2285                   }
2286                   newGraphGroups.set(newann.graphGroup,
2287                           Integer.valueOf(++fgroup));
2288                 }
2289                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2290                         .intValue();
2291               }
2292             }
2293             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2294             // was
2295             // duplicated
2296             // earlier
2297             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2298                     a);
2299           }
2300         }
2301       }
2302       if (!newAlignment)
2303       {
2304
2305         // propagate alignment changed.
2306         viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2307         if (annotationAdded)
2308         {
2309           // Duplicate sequence annotation in all views.
2310           AlignmentI[] alview = this.getViewAlignments();
2311           for (int i = 0; i < sequences.length; i++)
2312           {
2313             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2314             if (sann == null)
2315             {
2316               continue;
2317             }
2318             for (int avnum = 0; avnum < alview.length; avnum++)
2319             {
2320               if (alview[avnum] != alignment)
2321               {
2322                 // duplicate in a view other than the one with input focus
2323                 int avwidth = alview[avnum].getWidth() + 1;
2324                 // this relies on sann being preserved after we
2325                 // modify the sequence's annotation array for each duplication
2326                 for (int a = 0; a < sann.length; a++)
2327                 {
2328                   AlignmentAnnotation newann = new AlignmentAnnotation(
2329                           sann[a]);
2330                   sequences[i].addAlignmentAnnotation(newann);
2331                   newann.padAnnotation(avwidth);
2332                   alview[avnum].addAnnotation(newann); // annotation was
2333                   // duplicated earlier
2334                   // TODO JAL-1145 graphGroups are not updated for sequence
2335                   // annotation added to several views. This may cause
2336                   // strangeness
2337                   alview[avnum].setAnnotationIndex(newann, a);
2338                 }
2339               }
2340             }
2341           }
2342           buildSortByAnnotationScoresMenu();
2343         }
2344         viewport.firePropertyChange("alignment", null,
2345                 alignment.getSequences());
2346         if (alignPanels != null)
2347         {
2348           for (AlignmentPanel ap : alignPanels)
2349           {
2350             ap.validateAnnotationDimensions(false);
2351           }
2352         }
2353         else
2354         {
2355           alignPanel.validateAnnotationDimensions(false);
2356         }
2357
2358       }
2359       else
2360       {
2361         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2362                 DEFAULT_HEIGHT);
2363         String newtitle = new String("Copied sequences");
2364
2365         if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2366         {
2367           HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2368           af.viewport.setHiddenColumns(hc);
2369         }
2370
2371         // >>>This is a fix for the moment, until a better solution is
2372         // found!!<<<
2373         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2374                 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2375                         .getFeatureRenderer());
2376
2377         // TODO: maintain provenance of an alignment, rather than just make the
2378         // title a concatenation of operations.
2379         if (!externalPaste)
2380         {
2381           if (title.startsWith("Copied sequences"))
2382           {
2383             newtitle = title;
2384           }
2385           else
2386           {
2387             newtitle = newtitle.concat("- from " + title);
2388           }
2389         }
2390         else
2391         {
2392           newtitle = new String("Pasted sequences");
2393         }
2394
2395         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2396                 DEFAULT_HEIGHT);
2397
2398       }
2399
2400     } catch (Exception ex)
2401     {
2402       ex.printStackTrace();
2403       System.out.println("Exception whilst pasting: " + ex);
2404       // could be anything being pasted in here
2405     }
2406
2407   }
2408
2409   
2410   @Override
2411   protected void expand_newalign(ActionEvent e)
2412   {
2413     try
2414     {
2415       AlignmentI alignment = AlignmentUtils
2416               .expandContext(getViewport().getAlignment(), -1);
2417       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2418               DEFAULT_HEIGHT);
2419       String newtitle = new String("Flanking alignment");
2420
2421       Desktop d = Desktop.getInstance();
2422
2423       if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2424       {
2425         HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2426         af.viewport.setHiddenColumns(hc);
2427       }
2428
2429       // >>>This is a fix for the moment, until a better solution is
2430       // found!!<<<
2431       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2432               .transferSettings(alignPanel.getSeqPanel().seqCanvas
2433                       .getFeatureRenderer());
2434
2435       // TODO: maintain provenance of an alignment, rather than just make the
2436       // title a concatenation of operations.
2437       {
2438         if (title.startsWith("Copied sequences"))
2439         {
2440           newtitle = title;
2441         }
2442         else
2443         {
2444           newtitle = newtitle.concat("- from " + title);
2445         }
2446       }
2447
2448       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2449
2450     } catch (Exception ex)
2451     {
2452       ex.printStackTrace();
2453       System.out.println("Exception whilst pasting: " + ex);
2454       // could be anything being pasted in here
2455     } catch (OutOfMemoryError oom)
2456     {
2457       new OOMWarning("Viewing flanking region of alignment", oom);
2458     }
2459   }
2460
2461   /**
2462    * Action Cut (delete and copy) the selected region
2463    */
2464   
2465   @Override
2466   protected void cut_actionPerformed()
2467   {
2468     copy_actionPerformed();
2469     delete_actionPerformed();
2470   }
2471
2472   /**
2473    * Performs menu option to Delete the currently selected region
2474    */
2475   
2476   @Override
2477   protected void delete_actionPerformed()
2478   {
2479
2480     SequenceGroup sg = viewport.getSelectionGroup();
2481     if (sg == null)
2482     {
2483       return;
2484     }
2485
2486     Runnable okAction = new Runnable()
2487     {
2488       
2489       @Override
2490       public void run()
2491       {
2492         SequenceI[] cut = sg.getSequences()
2493                 .toArray(new SequenceI[sg.getSize()]);
2494
2495         addHistoryItem(new EditCommand(
2496                 MessageManager.getString("label.cut_sequences"), Action.CUT,
2497                 cut, sg.getStartRes(),
2498                 sg.getEndRes() - sg.getStartRes() + 1,
2499                 viewport.getAlignment()));
2500
2501         viewport.setSelectionGroup(null);
2502         viewport.sendSelection();
2503         viewport.getAlignment().deleteGroup(sg);
2504
2505         viewport.firePropertyChange("alignment", null,
2506                 viewport.getAlignment().getSequences());
2507         if (viewport.getAlignment().getHeight() < 1)
2508         {
2509           try
2510           {
2511             AlignFrame.this.setClosed(true);
2512           } catch (Exception ex)
2513           {
2514           }
2515         }
2516       }
2517     };
2518
2519     /*
2520      * If the cut affects all sequences, prompt for confirmation
2521      */
2522     boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2523             .getHeight();
2524     boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2525             + 1) == viewport.getAlignment().getWidth()) ? true : false;
2526     if (wholeHeight && wholeWidth)
2527     {
2528       JvOptionPane dialog = JvOptionPane
2529               .newOptionDialog(Desktop.getDesktopPane());
2530       dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2531       Object[] options = new Object[] {
2532           MessageManager.getString("action.ok"),
2533           MessageManager.getString("action.cancel") };
2534       dialog.showDialog(MessageManager.getString("warn.delete_all"),
2535               MessageManager.getString("label.delete_all"),
2536               JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2537               options, options[0]);
2538     }
2539     else
2540     {
2541       okAction.run();
2542     }
2543   }
2544
2545   /**
2546    * DOCUMENT ME!
2547    * 
2548    * @param e
2549    *          DOCUMENT ME!
2550    */
2551   
2552   @Override
2553   protected void deleteGroups_actionPerformed(ActionEvent e)
2554   {
2555     if (avc.deleteGroups())
2556     {
2557       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2558       alignPanel.updateAnnotation();
2559       alignPanel.paintAlignment(true, true);
2560     }
2561   }
2562
2563   /**
2564    * DOCUMENT ME!
2565    * 
2566    * @param e
2567    *          DOCUMENT ME!
2568    */
2569   
2570   @Override
2571   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2572   {
2573     // SequenceGroup sg = new SequenceGroup(
2574     // viewport.getAlignment().getSequences());
2575     //
2576     // sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2577     // viewport.setSelectionGroup(sg);
2578     // viewport.isSelectionGroupChanged(true);
2579     // viewport.sendSelection();
2580     // // JAL-2034 - should delegate to
2581     // // alignPanel to decide if overview needs
2582     // // updating.
2583     // alignPanel.paintAlignment(false, false);
2584     // PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2585     alignPanel.selectAllSequences();
2586   }
2587
2588   /**
2589    * DOCUMENT ME!
2590    * 
2591    * @param e
2592    *          DOCUMENT ME!
2593    */
2594   
2595   @Override
2596   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2597   {
2598     alignPanel.deselectAllSequences();
2599     // if (viewport.cursorMode)
2600     // {
2601     // alignPanel.getSeqPanel().keyboardNo1 = null;
2602     // alignPanel.getSeqPanel().keyboardNo2 = null;
2603     // }
2604     // viewport.setSelectionGroup(null);
2605     // viewport.getColumnSelection().clear();
2606     // viewport.setSelectionGroup(null);
2607     // alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2608     // // JAL-2034 - should delegate to
2609     // // alignPanel to decide if overview needs
2610     // // updating.
2611     // alignPanel.paintAlignment(false, false);
2612     // PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2613     // viewport.sendSelection();
2614   }
2615
2616   /**
2617    * DOCUMENT ME!
2618    * 
2619    * @param e
2620    *          DOCUMENT ME!
2621    */
2622   
2623   @Override
2624   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2625   {
2626     SequenceGroup sg = viewport.getSelectionGroup();
2627
2628     if (sg == null)
2629     {
2630       alignPanel.selectAllSequences();
2631
2632       return;
2633     }
2634
2635     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2636     {
2637       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2638     }
2639     // JAL-2034 - should delegate to
2640     // alignPanel to decide if overview needs
2641     // updating.
2642
2643     alignPanel.paintAlignment(true, false);
2644     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2645     viewport.sendSelection();
2646   }
2647
2648   
2649   @Override
2650   public void invertColSel_actionPerformed(ActionEvent e)
2651   {
2652     viewport.invertColumnSelection();
2653     alignPanel.paintAlignment(true, false);
2654     viewport.sendSelection();
2655   }
2656
2657   /**
2658    * DOCUMENT ME!
2659    * 
2660    * @param e
2661    *          DOCUMENT ME!
2662    */
2663   
2664   @Override
2665   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2666   {
2667     trimAlignment(true);
2668   }
2669
2670   /**
2671    * DOCUMENT ME!
2672    * 
2673    * @param e
2674    *          DOCUMENT ME!
2675    */
2676   
2677   @Override
2678   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2679   {
2680     trimAlignment(false);
2681   }
2682
2683   void trimAlignment(boolean trimLeft)
2684   {
2685     ColumnSelection colSel = viewport.getColumnSelection();
2686     int column;
2687
2688     if (!colSel.isEmpty())
2689     {
2690       if (trimLeft)
2691       {
2692         column = colSel.getMin();
2693       }
2694       else
2695       {
2696         column = colSel.getMax();
2697       }
2698
2699       SequenceI[] seqs;
2700       if (viewport.getSelectionGroup() != null)
2701       {
2702         seqs = viewport.getSelectionGroup()
2703                 .getSequencesAsArray(viewport.getHiddenRepSequences());
2704       }
2705       else
2706       {
2707         seqs = viewport.getAlignment().getSequencesArray();
2708       }
2709
2710       TrimRegionCommand trimRegion;
2711       if (trimLeft)
2712       {
2713         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2714                 column, viewport.getAlignment());
2715         viewport.getRanges().setStartRes(0);
2716       }
2717       else
2718       {
2719         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2720                 column, viewport.getAlignment());
2721       }
2722
2723       setStatus(MessageManager.formatMessage("label.removed_columns",
2724               new String[]
2725               { Integer.valueOf(trimRegion.getSize()).toString() }));
2726
2727       addHistoryItem(trimRegion);
2728
2729       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2730       {
2731         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2732                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2733         {
2734           viewport.getAlignment().deleteGroup(sg);
2735         }
2736       }
2737
2738       viewport.firePropertyChange("alignment", null,
2739               viewport.getAlignment().getSequences());
2740     }
2741   }
2742
2743   /**
2744    * DOCUMENT ME!
2745    * 
2746    * @param e
2747    *          DOCUMENT ME!
2748    */
2749   
2750   @Override
2751   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2752   {
2753     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2754
2755     SequenceI[] seqs;
2756     if (viewport.getSelectionGroup() != null)
2757     {
2758       seqs = viewport.getSelectionGroup()
2759               .getSequencesAsArray(viewport.getHiddenRepSequences());
2760       start = viewport.getSelectionGroup().getStartRes();
2761       end = viewport.getSelectionGroup().getEndRes();
2762     }
2763     else
2764     {
2765       seqs = viewport.getAlignment().getSequencesArray();
2766     }
2767
2768     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2769             "Remove Gapped Columns", seqs, start, end,
2770             viewport.getAlignment());
2771
2772     addHistoryItem(removeGapCols);
2773
2774     setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2775             new Object[]
2776             { Integer.valueOf(removeGapCols.getSize()).toString() }));
2777
2778     // This is to maintain viewport position on first residue
2779     // of first sequence
2780     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2781     ViewportRanges ranges = viewport.getRanges();
2782     int startRes = seq.findPosition(ranges.getStartRes());
2783     // ShiftList shifts;
2784     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2785     // edit.alColumnChanges=shifts.getInverse();
2786     // if (viewport.hasHiddenColumns)
2787     // viewport.getColumnSelection().compensateForEdits(shifts);
2788     ranges.setStartRes(seq.findIndex(startRes) - 1);
2789     viewport.firePropertyChange("alignment", null,
2790             viewport.getAlignment().getSequences());
2791
2792   }
2793
2794   /**
2795    * DOCUMENT ME!
2796    * 
2797    * @param e
2798    *          DOCUMENT ME!
2799    */
2800   
2801   @Override
2802   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2803   {
2804     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2805
2806     SequenceI[] seqs;
2807     if (viewport.getSelectionGroup() != null)
2808     {
2809       seqs = viewport.getSelectionGroup()
2810               .getSequencesAsArray(viewport.getHiddenRepSequences());
2811       start = viewport.getSelectionGroup().getStartRes();
2812       end = viewport.getSelectionGroup().getEndRes();
2813     }
2814     else
2815     {
2816       seqs = viewport.getAlignment().getSequencesArray();
2817     }
2818
2819     // This is to maintain viewport position on first residue
2820     // of first sequence
2821     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2822     int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2823
2824     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2825             viewport.getAlignment()));
2826
2827     viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2828
2829     viewport.firePropertyChange("alignment", null,
2830             viewport.getAlignment().getSequences());
2831
2832   }
2833
2834   /**
2835    * DOCUMENT ME!
2836    * 
2837    * @param e
2838    *          DOCUMENT ME!
2839    */
2840   
2841   @Override
2842   public void padGapsMenuitem_actionPerformed(ActionEvent e)
2843   {
2844     viewport.setPadGaps(padGapsMenuitem.isSelected());
2845     viewport.firePropertyChange("alignment", null,
2846             viewport.getAlignment().getSequences());
2847   }
2848
2849   /**
2850    * DOCUMENT ME!
2851    * 
2852    * @param e
2853    *          DOCUMENT ME!
2854    */
2855   
2856   @Override
2857   public void findMenuItem_actionPerformed(ActionEvent e)
2858   {
2859     new Finder();
2860   }
2861
2862   /**
2863    * Create a new view of the current alignment.
2864    */
2865   
2866   @Override
2867   public void newView_actionPerformed(ActionEvent e)
2868   {
2869     newView(null, true);
2870   }
2871
2872   /**
2873    * Creates and shows a new view of the current alignment.
2874    * 
2875    * @param viewTitle
2876    *          title of newly created view; if null, one will be generated
2877    * @param copyAnnotation
2878    *          if true then duplicate all annnotation, groups and settings
2879    * @return new alignment panel, already displayed.
2880    */
2881   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2882   {
2883     /*
2884      * Create a new AlignmentPanel (with its own, new Viewport)
2885      */
2886     AlignmentPanel newap = new jalview.project.Jalview2XML()
2887             .copyAlignPanel(alignPanel);
2888     if (!copyAnnotation)
2889     {
2890       /*
2891        * remove all groups and annotation except for the automatic stuff
2892        */
2893       newap.av.getAlignment().deleteAllGroups();
2894       newap.av.getAlignment().deleteAllAnnotations(false);
2895     }
2896
2897     newap.av.setGatherViewsHere(false);
2898
2899     if (viewport.getViewName() == null)
2900     {
2901       viewport.setViewName(
2902               MessageManager.getString("label.view_name_original"));
2903     }
2904
2905     /*
2906      * Views share the same edits undo and redo stacks
2907      */
2908     newap.av.setHistoryList(viewport.getHistoryList());
2909     newap.av.setRedoList(viewport.getRedoList());
2910
2911     /*
2912      * copy any visualisation settings that are not saved in the project
2913      */
2914     newap.av.setColourAppliesToAllGroups(
2915             viewport.getColourAppliesToAllGroups());
2916
2917     /*
2918      * Views share the same mappings; need to deregister any new mappings
2919      * created by copyAlignPanel, and register the new reference to the shared
2920      * mappings
2921      */
2922     newap.av.replaceMappings(viewport.getAlignment());
2923
2924     /*
2925      * start up cDNA consensus (if applicable) now mappings are in place
2926      */
2927     if (newap.av.initComplementConsensus())
2928     {
2929       newap.refresh(true); // adjust layout of annotations
2930     }
2931
2932     newap.av.setViewName(getNewViewName(viewTitle));
2933
2934     addAlignmentPanel(newap, true);
2935     newap.alignmentChanged();
2936
2937     if (alignPanels.size() == 2)
2938     {
2939       viewport.setGatherViewsHere(true);
2940     }
2941     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2942     return newap;
2943   }
2944
2945   /**
2946    * Make a new name for the view, ensuring it is unique within the current
2947    * sequenceSetId. (This used to be essential for Jalview Project archives, but
2948    * these now use viewId. Unique view names are still desirable for usability.)
2949    * 
2950    * @param viewTitle
2951    * @return
2952    */
2953   protected String getNewViewName(String viewTitle)
2954   {
2955     int index = Desktop.getViewCount(viewport.getSequenceSetId());
2956     boolean addFirstIndex = false;
2957     if (viewTitle == null || viewTitle.trim().length() == 0)
2958     {
2959       viewTitle = MessageManager.getString("action.view");
2960       addFirstIndex = true;
2961     }
2962     else
2963     {
2964       index = 1;// we count from 1 if given a specific name
2965     }
2966     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2967
2968     List<Component> comps = PaintRefresher.components
2969             .get(viewport.getSequenceSetId());
2970
2971     List<String> existingNames = getExistingViewNames(comps);
2972
2973     while (existingNames.contains(newViewName))
2974     {
2975       newViewName = viewTitle + " " + (++index);
2976     }
2977     return newViewName;
2978   }
2979
2980   /**
2981    * Returns a list of distinct view names found in the given list of
2982    * components. View names are held on the viewport of an AlignmentPanel.
2983    * 
2984    * @param comps
2985    * @return
2986    */
2987   protected List<String> getExistingViewNames(List<Component> comps)
2988   {
2989     List<String> existingNames = new ArrayList<>();
2990     for (Component comp : comps)
2991     {
2992       if (comp instanceof AlignmentPanel)
2993       {
2994         AlignmentPanel ap = (AlignmentPanel) comp;
2995         if (!existingNames.contains(ap.av.getViewName()))
2996         {
2997           existingNames.add(ap.av.getViewName());
2998         }
2999       }
3000     }
3001     return existingNames;
3002   }
3003
3004   /**
3005    * Explode tabbed views into separate windows.
3006    */
3007   
3008   @Override
3009   public void expandViews_actionPerformed(ActionEvent e)
3010   {
3011     Desktop.explodeViews(this);
3012   }
3013
3014   /**
3015    * Gather views in separate windows back into a tabbed presentation.
3016    */
3017   
3018   @Override
3019   public void gatherViews_actionPerformed(ActionEvent e)
3020   {
3021     Desktop.getInstance().gatherViews(this);
3022   }
3023
3024   /**
3025    * DOCUMENT ME!
3026    * 
3027    * @param e
3028    *          DOCUMENT ME!
3029    */
3030   
3031   @Override
3032   public void font_actionPerformed(ActionEvent e)
3033   {
3034     new FontChooser(alignPanel);
3035   }
3036
3037   /**
3038    * DOCUMENT ME!
3039    * 
3040    * @param e
3041    *          DOCUMENT ME!
3042    */
3043   
3044   @Override
3045   protected void seqLimit_actionPerformed(ActionEvent e)
3046   {
3047     viewport.setShowJVSuffix(seqLimits.isSelected());
3048
3049     alignPanel.getIdPanel().getIdCanvas()
3050             .setPreferredSize(alignPanel.calculateIdWidth());
3051     alignPanel.paintAlignment(true, false);
3052   }
3053
3054   
3055   @Override
3056   public void idRightAlign_actionPerformed(ActionEvent e)
3057   {
3058     viewport.setRightAlignIds(idRightAlign.isSelected());
3059     alignPanel.paintAlignment(false, false);
3060   }
3061
3062   
3063   @Override
3064   public void centreColumnLabels_actionPerformed(ActionEvent e)
3065   {
3066     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3067     alignPanel.paintAlignment(false, false);
3068   }
3069
3070   /*
3071    * (non-Javadoc)
3072    * 
3073    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3074    */
3075   
3076   @Override
3077   protected void followHighlight_actionPerformed()
3078   {
3079     /*
3080      * Set the 'follow' flag on the Viewport (and scroll to position if now
3081      * true).
3082      */
3083     final boolean state = this.followHighlightMenuItem.getState();
3084     viewport.setFollowHighlight(state);
3085     if (state)
3086     {
3087       alignPanel.scrollToPosition(viewport.getSearchResults());
3088     }
3089   }
3090
3091   /**
3092    * DOCUMENT ME!
3093    * 
3094    * @param e
3095    *          DOCUMENT ME!
3096    */
3097   
3098   @Override
3099   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3100   {
3101     viewport.setColourText(colourTextMenuItem.isSelected());
3102     alignPanel.paintAlignment(false, false);
3103   }
3104
3105   /**
3106    * DOCUMENT ME!
3107    * 
3108    * @param e
3109    *          DOCUMENT ME!
3110    */
3111   
3112   @Override
3113   public void wrapMenuItem_actionPerformed(ActionEvent e)
3114   {
3115     scaleAbove.setVisible(wrapMenuItem.isSelected());
3116     scaleLeft.setVisible(wrapMenuItem.isSelected());
3117     scaleRight.setVisible(wrapMenuItem.isSelected());
3118     viewport.setWrapAlignment(wrapMenuItem.isSelected());
3119     alignPanel.updateLayout();
3120   }
3121
3122   
3123   @Override
3124   public void showAllSeqs_actionPerformed(ActionEvent e)
3125   {
3126     viewport.showAllHiddenSeqs();
3127   }
3128
3129   
3130   @Override
3131   public void showAllColumns_actionPerformed(ActionEvent e)
3132   {
3133     viewport.showAllHiddenColumns();
3134     alignPanel.paintAlignment(true, true);
3135     viewport.sendSelection();
3136   }
3137
3138   
3139   @Override
3140   public void hideSelSequences_actionPerformed(ActionEvent e)
3141   {
3142     viewport.hideAllSelectedSeqs();
3143   }
3144
3145   /**
3146    * called by key handler and the hide all/show all menu items
3147    * 
3148    * @param toggleSeqs
3149    * @param toggleCols
3150    */
3151   protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3152   {
3153
3154     boolean hide = false;
3155     SequenceGroup sg = viewport.getSelectionGroup();
3156     if (!toggleSeqs && !toggleCols)
3157     {
3158       // Hide everything by the current selection - this is a hack - we do the
3159       // invert and then hide
3160       // first check that there will be visible columns after the invert.
3161       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3162               && sg.getStartRes() <= sg.getEndRes()))
3163       {
3164         // now invert the sequence set, if required - empty selection implies
3165         // that no hiding is required.
3166         if (sg != null)
3167         {
3168           invertSequenceMenuItem_actionPerformed(null);
3169           sg = viewport.getSelectionGroup();
3170           toggleSeqs = true;
3171
3172         }
3173         viewport.expandColSelection(sg, true);
3174         // finally invert the column selection and get the new sequence
3175         // selection.
3176         invertColSel_actionPerformed(null);
3177         toggleCols = true;
3178       }
3179     }
3180
3181     if (toggleSeqs)
3182     {
3183       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3184       {
3185         hideSelSequences_actionPerformed(null);
3186         hide = true;
3187       }
3188       else if (!(toggleCols && viewport.hasSelectedColumns()))
3189       {
3190         showAllSeqs_actionPerformed(null);
3191       }
3192     }
3193
3194     if (toggleCols)
3195     {
3196       if (viewport.hasSelectedColumns())
3197       {
3198         hideSelColumns_actionPerformed(null);
3199         if (!toggleSeqs)
3200         {
3201           viewport.setSelectionGroup(sg);
3202         }
3203       }
3204       else if (!hide)
3205       {
3206         showAllColumns_actionPerformed(null);
3207       }
3208     }
3209   }
3210
3211   /*
3212    * (non-Javadoc)
3213    * 
3214    * @see
3215    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3216    * event.ActionEvent)
3217    */
3218   
3219   @Override
3220   public void hideAllButSelection_actionPerformed(ActionEvent e)
3221   {
3222     toggleHiddenRegions(false, false);
3223     viewport.sendSelection();
3224   }
3225
3226   /*
3227    * (non-Javadoc)
3228    * 
3229    * @see
3230    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3231    * .ActionEvent)
3232    */
3233   
3234   @Override
3235   public void hideAllSelection_actionPerformed(ActionEvent e)
3236   {
3237     SequenceGroup sg = viewport.getSelectionGroup();
3238     viewport.expandColSelection(sg, false);
3239     viewport.hideAllSelectedSeqs();
3240     viewport.hideSelectedColumns();
3241     alignPanel.updateLayout();
3242     alignPanel.paintAlignment(true, true);
3243     viewport.sendSelection();
3244   }
3245
3246   /*
3247    * (non-Javadoc)
3248    * 
3249    * @see
3250    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3251    * ActionEvent)
3252    */
3253   
3254   @Override
3255   public void showAllhidden_actionPerformed(ActionEvent e)
3256   {
3257     viewport.showAllHiddenColumns();
3258     viewport.showAllHiddenSeqs();
3259     alignPanel.paintAlignment(true, true);
3260     viewport.sendSelection();
3261   }
3262
3263   
3264   @Override
3265   public void hideSelColumns_actionPerformed(ActionEvent e)
3266   {
3267     viewport.hideSelectedColumns();
3268     alignPanel.updateLayout();
3269     alignPanel.paintAlignment(true, true);
3270     viewport.sendSelection();
3271   }
3272
3273   
3274   @Override
3275   public void hiddenMarkers_actionPerformed(ActionEvent e)
3276   {
3277     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3278     repaint();
3279   }
3280
3281   /**
3282    * DOCUMENT ME!
3283    * 
3284    * @param e
3285    *          DOCUMENT ME!
3286    */
3287   
3288   @Override
3289   protected void scaleAbove_actionPerformed(ActionEvent e)
3290   {
3291     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3292     alignPanel.updateLayout();
3293     alignPanel.paintAlignment(true, false);
3294   }
3295
3296   /**
3297    * DOCUMENT ME!
3298    * 
3299    * @param e
3300    *          DOCUMENT ME!
3301    */
3302   
3303   @Override
3304   protected void scaleLeft_actionPerformed(ActionEvent e)
3305   {
3306     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3307     alignPanel.updateLayout();
3308     alignPanel.paintAlignment(true, false);
3309   }
3310
3311   /**
3312    * DOCUMENT ME!
3313    * 
3314    * @param e
3315    *          DOCUMENT ME!
3316    */
3317   
3318   @Override
3319   protected void scaleRight_actionPerformed(ActionEvent e)
3320   {
3321     viewport.setScaleRightWrapped(scaleRight.isSelected());
3322     alignPanel.updateLayout();
3323     alignPanel.paintAlignment(true, false);
3324   }
3325
3326   /**
3327    * DOCUMENT ME!
3328    * 
3329    * @param e
3330    *          DOCUMENT ME!
3331    */
3332   
3333   @Override
3334   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3335   {
3336     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3337     alignPanel.paintAlignment(false, false);
3338   }
3339
3340   /**
3341    * DOCUMENT ME!
3342    * 
3343    * @param e
3344    *          DOCUMENT ME!
3345    */
3346   
3347   @Override
3348   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3349   {
3350     viewport.setShowText(viewTextMenuItem.isSelected());
3351     alignPanel.paintAlignment(false, false);
3352   }
3353
3354   /**
3355    * DOCUMENT ME!
3356    * 
3357    * @param e
3358    *          DOCUMENT ME!
3359    */
3360   
3361   @Override
3362   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3363   {
3364     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3365     alignPanel.paintAlignment(false, false);
3366   }
3367
3368   public FeatureSettings featureSettings;
3369
3370   
3371   @Override
3372   public FeatureSettingsControllerI getFeatureSettingsUI()
3373   {
3374     return featureSettings;
3375   }
3376
3377   
3378   @Override
3379   public void featureSettings_actionPerformed(ActionEvent e)
3380   {
3381     showFeatureSettingsUI();
3382   }
3383
3384   
3385   public FeatureSettingsControllerI showFeatureSettingsUI()
3386   {
3387     if (featureSettings != null)
3388     {
3389       // featureSettings.closeOldSettings();
3390       featureSettings = null;
3391     }
3392     if (!showSeqFeatures.isSelected())
3393     {
3394       // make sure features are actually displayed
3395       showSeqFeatures.setSelected(true);
3396       showSeqFeatures_actionPerformed(null);
3397     }
3398     featureSettings = new FeatureSettings(this);
3399     return featureSettings;
3400   }
3401
3402   /**
3403    * Set or clear 'Show Sequence Features'
3404    * 
3405    * @param evt
3406    *          DOCUMENT ME!
3407    */
3408   
3409   @Override
3410   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3411   {
3412     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3413     alignPanel.paintAlignment(true, true);
3414   }
3415
3416   /**
3417    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3418    * the annotations panel as a whole.
3419    * 
3420    * The options to show/hide all annotations should be enabled when the panel
3421    * is shown, and disabled when the panel is hidden.
3422    * 
3423    * @param e
3424    */
3425   
3426   @Override
3427   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3428   {
3429     final boolean setVisible = annotationPanelMenuItem.isSelected();
3430     viewport.setShowAnnotation(setVisible);
3431     syncAnnotationMenuItems(setVisible);
3432     alignPanel.updateLayout();
3433   }
3434
3435   private void syncAnnotationMenuItems(boolean setVisible)
3436   {
3437     showAllSeqAnnotations.setEnabled(setVisible);
3438     hideAllSeqAnnotations.setEnabled(setVisible);
3439     showAllAlAnnotations.setEnabled(setVisible);
3440     hideAllAlAnnotations.setEnabled(setVisible);
3441   }
3442
3443   
3444   @Override
3445   public void alignmentProperties()
3446   {
3447     JComponent pane;
3448     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3449
3450             .formatAsHtml();
3451     String content = MessageManager.formatMessage("label.html_content",
3452             new Object[]
3453             { contents.toString() });
3454     contents = null;
3455
3456     if (Platform.isJS())
3457     {
3458       JLabel textLabel = new JLabel();
3459       textLabel.setText(content);
3460       textLabel.setBackground(Color.WHITE);
3461
3462       pane = new JPanel(new BorderLayout());
3463       ((JPanel) pane).setOpaque(true);
3464       pane.setBackground(Color.WHITE);
3465       ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3466     }
3467     else
3468     /**
3469      * Java only
3470      * 
3471      * @j2sIgnore
3472      */
3473     {
3474       JEditorPane editPane = new JEditorPane("text/html", "");
3475       editPane.setEditable(false);
3476       editPane.setText(content);
3477       pane = editPane;
3478     }
3479
3480     JInternalFrame frame = new JInternalFrame();
3481
3482     frame.getContentPane().add(new JScrollPane(pane));
3483
3484     Desktop.addInternalFrame(frame, MessageManager
3485             .formatMessage("label.alignment_properties", new Object[]
3486             { getTitle() }), 500, 400);
3487   }
3488
3489   /**
3490    * DOCUMENT ME!
3491    * 
3492    * @param e
3493    *          DOCUMENT ME!
3494    */
3495   
3496   @Override
3497   public void overviewMenuItem_actionPerformed(ActionEvent e)
3498   {
3499     if (alignPanel.overviewPanel != null)
3500     {
3501       return;
3502     }
3503
3504     JInternalFrame frame = new JInternalFrame();
3505
3506     // BH 2019.07.26 we allow for an embedded
3507     // undecorated overview with defined size
3508     frame.setName(Jalview.getAppID("overview"));
3509     //
3510     Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3511     if (dim != null && dim.width == 0)
3512     {
3513       dim = null; // hidden, not embedded
3514     }
3515     OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3516
3517     frame.setContentPane(overview);
3518     if (dim == null)
3519     {
3520       dim = new Dimension();
3521       // was frame.getSize(), but that is 0,0 at this point;
3522     }
3523     else
3524     {
3525       // we are imbedding, and so we have an undecorated frame
3526       // and we can set the the frame dimensions accordingly.
3527     }
3528     // allowing for unresizable option using, style="resize:none"
3529     boolean resizable = (Platform.getEmbeddedAttribute(frame,
3530             "resize") != "none");
3531     Desktop.addInternalFrame(frame, MessageManager
3532             .formatMessage("label.overview_params", new Object[]
3533             { this.getTitle() }), true, dim.width, dim.height, resizable,
3534             true);
3535     frame.pack();
3536     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3537     frame.addInternalFrameListener(
3538             new javax.swing.event.InternalFrameAdapter()
3539             {
3540               
3541               @Override
3542               public void internalFrameClosed(
3543                       javax.swing.event.InternalFrameEvent evt)
3544               {
3545                 overview.dispose();
3546                 alignPanel.setOverviewPanel(null);
3547               }
3548             });
3549     if (getKeyListeners().length > 0)
3550     {
3551       frame.addKeyListener(getKeyListeners()[0]);
3552     }
3553
3554     alignPanel.setOverviewPanel(overview);
3555   }
3556
3557   
3558   @Override
3559   public void textColour_actionPerformed()
3560   {
3561     new TextColourChooser().chooseColour(alignPanel, null);
3562   }
3563
3564   /*
3565    * public void covariationColour_actionPerformed() {
3566    * changeColour(new
3567    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3568    * ()[0])); }
3569    */
3570   
3571   @Override
3572   public void annotationColour_actionPerformed()
3573   {
3574     new AnnotationColourChooser(viewport, alignPanel);
3575   }
3576
3577   
3578   @Override
3579   public void annotationColumn_actionPerformed(ActionEvent e)
3580   {
3581     new AnnotationColumnChooser(viewport, alignPanel);
3582   }
3583
3584   /**
3585    * Action on the user checking or unchecking the option to apply the selected
3586    * colour scheme to all groups. If unchecked, groups may have their own
3587    * independent colour schemes.
3588    * 
3589    * @param selected
3590    */
3591   
3592   @Override
3593   public void applyToAllGroups_actionPerformed(boolean selected)
3594   {
3595     viewport.setColourAppliesToAllGroups(selected);
3596   }
3597
3598   /**
3599    * Action on user selecting a colour from the colour menu
3600    * 
3601    * @param name
3602    *          the name (not the menu item label!) of the colour scheme
3603    */
3604   
3605   @Override
3606   public void changeColour_actionPerformed(String name)
3607   {
3608     /*
3609      * 'User Defined' opens a panel to configure or load a
3610      * user-defined colour scheme
3611      */
3612     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3613     {
3614       new UserDefinedColours(alignPanel);
3615       return;
3616     }
3617
3618     /*
3619      * otherwise set the chosen colour scheme (or null for 'None')
3620      */
3621     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3622             viewport, viewport.getAlignment(),
3623             viewport.getHiddenRepSequences());
3624     changeColour(cs);
3625   }
3626
3627   /**
3628    * Actions on setting or changing the alignment colour scheme
3629    * 
3630    * @param cs
3631    */
3632   
3633   @Override
3634   public void changeColour(ColourSchemeI cs)
3635   {
3636     // TODO: pull up to controller method
3637     ColourMenuHelper.setColourSelected(colourMenu, cs);
3638
3639     viewport.setGlobalColourScheme(cs);
3640
3641     alignPanel.paintAlignment(true, true);
3642   }
3643
3644   /**
3645    * Show the PID threshold slider panel
3646    */
3647   
3648   @Override
3649   protected void modifyPID_actionPerformed()
3650   {
3651     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3652             alignPanel.getViewName());
3653     SliderPanel.showPIDSlider();
3654   }
3655
3656   /**
3657    * Show the Conservation slider panel
3658    */
3659   
3660   @Override
3661   protected void modifyConservation_actionPerformed()
3662   {
3663     SliderPanel.setConservationSlider(alignPanel,
3664             viewport.getResidueShading(), alignPanel.getViewName());
3665     SliderPanel.showConservationSlider();
3666   }
3667
3668   /**
3669    * Action on selecting or deselecting (Colour) By Conservation
3670    */
3671   
3672   @Override
3673   public void conservationMenuItem_actionPerformed(boolean selected)
3674   {
3675     modifyConservation.setEnabled(selected);
3676     viewport.setConservationSelected(selected);
3677     viewport.getResidueShading().setConservationApplied(selected);
3678
3679     changeColour(viewport.getGlobalColourScheme());
3680     if (selected)
3681     {
3682       modifyConservation_actionPerformed();
3683     }
3684     else
3685     {
3686       SliderPanel.hideConservationSlider();
3687     }
3688   }
3689
3690   /**
3691    * Action on selecting or deselecting (Colour) Above PID Threshold
3692    */
3693   
3694   @Override
3695   public void abovePIDThreshold_actionPerformed(boolean selected)
3696   {
3697     modifyPID.setEnabled(selected);
3698     viewport.setAbovePIDThreshold(selected);
3699     if (!selected)
3700     {
3701       viewport.getResidueShading().setThreshold(0,
3702               viewport.isIgnoreGapsConsensus());
3703     }
3704
3705     changeColour(viewport.getGlobalColourScheme());
3706     if (selected)
3707     {
3708       modifyPID_actionPerformed();
3709     }
3710     else
3711     {
3712       SliderPanel.hidePIDSlider();
3713     }
3714   }
3715
3716   /**
3717    * DOCUMENT ME!
3718    * 
3719    * @param e
3720    *          DOCUMENT ME!
3721    */
3722   
3723   @Override
3724   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3725   {
3726     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3727     AlignmentSorter.sortByPID(viewport.getAlignment(),
3728             viewport.getAlignment().getSequenceAt(0));
3729     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3730             viewport.getAlignment()));
3731     alignPanel.paintAlignment(true, false);
3732   }
3733
3734   /**
3735    * DOCUMENT ME!
3736    * 
3737    * @param e
3738    *          DOCUMENT ME!
3739    */
3740   
3741   @Override
3742   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3743   {
3744     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3745     AlignmentSorter.sortByID(viewport.getAlignment());
3746     addHistoryItem(
3747             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3748     alignPanel.paintAlignment(true, false);
3749   }
3750
3751   /**
3752    * DOCUMENT ME!
3753    * 
3754    * @param e
3755    *          DOCUMENT ME!
3756    */
3757   
3758   @Override
3759   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3760   {
3761     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3762     AlignmentSorter.sortByLength(viewport.getAlignment());
3763     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3764             viewport.getAlignment()));
3765     alignPanel.paintAlignment(true, false);
3766   }
3767
3768   /**
3769    * DOCUMENT ME!
3770    * 
3771    * @param e
3772    *          DOCUMENT ME!
3773    */
3774   
3775   @Override
3776   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3777   {
3778     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3779     AlignmentSorter.sortByGroup(viewport.getAlignment());
3780     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3781             viewport.getAlignment()));
3782
3783     alignPanel.paintAlignment(true, false);
3784   }
3785
3786   /**
3787    * DOCUMENT ME!
3788    * 
3789    * @param e
3790    *          DOCUMENT ME!
3791    */
3792   
3793   @Override
3794   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3795   {
3796     new RedundancyPanel(alignPanel, this);
3797   }
3798
3799   /**
3800    * DOCUMENT ME!
3801    * 
3802    * @param e
3803    *          DOCUMENT ME!
3804    */
3805   
3806   @Override
3807   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3808   {
3809     if ((viewport.getSelectionGroup() == null)
3810             || (viewport.getSelectionGroup().getSize() < 2))
3811     {
3812       JvOptionPane.showInternalMessageDialog(this,
3813               MessageManager.getString(
3814                       "label.you_must_select_least_two_sequences"),
3815               MessageManager.getString("label.invalid_selection"),
3816               JvOptionPane.WARNING_MESSAGE);
3817     }
3818     else
3819     {
3820       JInternalFrame frame = new JInternalFrame();
3821       frame.setContentPane(new PairwiseAlignPanel(viewport));
3822       Desktop.addInternalFrame(frame,
3823               MessageManager.getString("action.pairwise_alignment"), 600,
3824               500);
3825     }
3826   }
3827
3828   
3829   @Override
3830   public void autoCalculate_actionPerformed(ActionEvent e)
3831   {
3832     viewport.setAutoCalculateConsensusAndConservation(
3833             autoCalculate.isSelected());
3834     if (viewport.getAutoCalculateConsensusAndConservation())
3835     {
3836       viewport.firePropertyChange("alignment", null,
3837               viewport.getAlignment().getSequences());
3838     }
3839   }
3840
3841   
3842   @Override
3843   public void sortByTreeOption_actionPerformed(ActionEvent e)
3844   {
3845     viewport.sortByTree = sortByTree.isSelected();
3846   }
3847
3848   
3849   @Override
3850   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3851   {
3852     viewport.followSelection = listenToViewSelections.isSelected();
3853   }
3854
3855   /**
3856    * Constructs a tree panel and adds it to the desktop
3857    * 
3858    * @param type
3859    *          tree type (NJ or AV)
3860    * @param modelName
3861    *          name of score model used to compute the tree
3862    * @param options
3863    *          parameters for the distance or similarity calculation
3864    */
3865   void newTreePanel(String type, String modelName,
3866           SimilarityParamsI options)
3867   {
3868     String frameTitle = "";
3869     TreePanel tp;
3870
3871     boolean onSelection = false;
3872     if (viewport.getSelectionGroup() != null
3873             && viewport.getSelectionGroup().getSize() > 0)
3874     {
3875       SequenceGroup sg = viewport.getSelectionGroup();
3876
3877       /* Decide if the selection is a column region */
3878       for (SequenceI _s : sg.getSequences())
3879       {
3880         if (_s.getLength() < sg.getEndRes())
3881         {
3882           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3883                   MessageManager.getString(
3884                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3885                   MessageManager.getString(
3886                           "label.sequences_selection_not_aligned"),
3887                   JvOptionPane.WARNING_MESSAGE);
3888
3889           return;
3890         }
3891       }
3892       onSelection = true;
3893     }
3894     else
3895     {
3896       if (viewport.getAlignment().getHeight() < 2)
3897       {
3898         return;
3899       }
3900     }
3901
3902     tp = new TreePanel(alignPanel, type, modelName, options);
3903     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3904
3905     frameTitle += " from ";
3906
3907     if (viewport.getViewName() != null)
3908     {
3909       frameTitle += viewport.getViewName() + " of ";
3910     }
3911
3912     frameTitle += this.title;
3913
3914     Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
3915     Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
3916   }
3917
3918   /**
3919    * DOCUMENT ME!
3920    * 
3921    * @param title
3922    *          DOCUMENT ME!
3923    * @param order
3924    *          DOCUMENT ME!
3925    */
3926   public void addSortByOrderMenuItem(String title,
3927           final AlignmentOrder order)
3928   {
3929     final JMenuItem item = new JMenuItem(MessageManager
3930             .formatMessage("action.by_title_param", new Object[]
3931             { title }));
3932     sort.add(item);
3933     item.addActionListener(new java.awt.event.ActionListener()
3934     {
3935       
3936       @Override
3937       public void actionPerformed(ActionEvent e)
3938       {
3939         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3940
3941         // TODO: JBPNote - have to map order entries to curent SequenceI
3942         // pointers
3943         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3944
3945         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3946                 viewport.getAlignment()));
3947
3948         alignPanel.paintAlignment(true, false);
3949       }
3950     });
3951   }
3952
3953   /**
3954    * Add a new sort by annotation score menu item
3955    * 
3956    * @param sort
3957    *          the menu to add the option to
3958    * @param scoreLabel
3959    *          the label used to retrieve scores for each sequence on the
3960    *          alignment
3961    */
3962   public void addSortByAnnotScoreMenuItem(JMenu sort,
3963           final String scoreLabel)
3964   {
3965     final JMenuItem item = new JMenuItem(scoreLabel);
3966     sort.add(item);
3967     item.addActionListener(new java.awt.event.ActionListener()
3968     {
3969       
3970       @Override
3971       public void actionPerformed(ActionEvent e)
3972       {
3973         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3974         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3975                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3976         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3977                 viewport.getAlignment()));
3978         alignPanel.paintAlignment(true, false);
3979       }
3980     });
3981   }
3982
3983   /**
3984    * last hash for alignment's annotation array - used to minimise cost of
3985    * rebuild.
3986    */
3987   protected int _annotationScoreVectorHash;
3988
3989   /**
3990    * search the alignment and rebuild the sort by annotation score submenu the
3991    * last alignment annotation vector hash is stored to minimize cost of
3992    * rebuilding in subsequence calls.
3993    * 
3994    */
3995   
3996   @Override
3997   public void buildSortByAnnotationScoresMenu()
3998   {
3999     if (viewport.getAlignment().getAlignmentAnnotation() == null)
4000     {
4001       return;
4002     }
4003
4004     if (viewport.getAlignment().getAlignmentAnnotation()
4005             .hashCode() != _annotationScoreVectorHash)
4006     {
4007       sortByAnnotScore.removeAll();
4008       // almost certainly a quicker way to do this - but we keep it simple
4009       Hashtable<String, String> scoreSorts = new Hashtable<>();
4010       AlignmentAnnotation aann[];
4011       for (SequenceI sqa : viewport.getAlignment().getSequences())
4012       {
4013         aann = sqa.getAnnotation();
4014         for (int i = 0; aann != null && i < aann.length; i++)
4015         {
4016           if (aann[i].hasScore() && aann[i].sequenceRef != null)
4017           {
4018             scoreSorts.put(aann[i].label, aann[i].label);
4019           }
4020         }
4021       }
4022       Enumeration<String> labels = scoreSorts.keys();
4023       while (labels.hasMoreElements())
4024       {
4025         addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
4026       }
4027       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4028       scoreSorts.clear();
4029
4030       _annotationScoreVectorHash = viewport.getAlignment()
4031               .getAlignmentAnnotation().hashCode();
4032     }
4033   }
4034
4035   /**
4036    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4037    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4038    * call. Listeners are added to remove the menu item when the treePanel is
4039    * closed, and adjust the tree leaf to sequence mapping when the alignment is
4040    * modified.
4041    */
4042   
4043   @Override
4044   public void buildTreeSortMenu()
4045   {
4046     sortByTreeMenu.removeAll();
4047
4048     List<Component> comps = PaintRefresher.components
4049             .get(viewport.getSequenceSetId());
4050     List<TreePanel> treePanels = new ArrayList<>();
4051     for (Component comp : comps)
4052     {
4053       if (comp instanceof TreePanel)
4054       {
4055         treePanels.add((TreePanel) comp);
4056       }
4057     }
4058
4059     if (treePanels.size() < 1)
4060     {
4061       sortByTreeMenu.setVisible(false);
4062       return;
4063     }
4064
4065     sortByTreeMenu.setVisible(true);
4066
4067     for (final TreePanel tp : treePanels)
4068     {
4069       final JMenuItem item = new JMenuItem(tp.getTitle());
4070       item.addActionListener(new java.awt.event.ActionListener()
4071       {
4072         
4073         @Override
4074         public void actionPerformed(ActionEvent e)
4075         {
4076           tp.sortByTree_actionPerformed();
4077           addHistoryItem(tp.sortAlignmentIn(alignPanel));
4078
4079         }
4080       });
4081
4082       sortByTreeMenu.add(item);
4083     }
4084   }
4085
4086   public boolean sortBy(AlignmentOrder alorder, String undoname)
4087   {
4088     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4089     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4090     if (undoname != null)
4091     {
4092       addHistoryItem(new OrderCommand(undoname, oldOrder,
4093               viewport.getAlignment()));
4094     }
4095     alignPanel.paintAlignment(true, false);
4096     return true;
4097   }
4098
4099   /**
4100    * Work out whether the whole set of sequences or just the selected set will
4101    * be submitted for multiple alignment.
4102    * 
4103    */
4104   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4105   {
4106     // Now, check we have enough sequences
4107     AlignmentView msa = null;
4108
4109     if ((viewport.getSelectionGroup() != null)
4110             && (viewport.getSelectionGroup().getSize() > 1))
4111     {
4112       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4113       // some common interface!
4114       /*
4115        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4116        * SequenceI[sz = seqs.getSize(false)];
4117        * 
4118        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4119        * seqs.getSequenceAt(i); }
4120        */
4121       msa = viewport.getAlignmentView(true);
4122     }
4123     else if (viewport.getSelectionGroup() != null
4124             && viewport.getSelectionGroup().getSize() == 1)
4125     {
4126       int option = JvOptionPane.showConfirmDialog(this,
4127               MessageManager.getString("warn.oneseq_msainput_selection"),
4128               MessageManager.getString("label.invalid_selection"),
4129               JvOptionPane.OK_CANCEL_OPTION);
4130       if (option == JvOptionPane.OK_OPTION)
4131       {
4132         msa = viewport.getAlignmentView(false);
4133       }
4134     }
4135     else
4136     {
4137       msa = viewport.getAlignmentView(false);
4138     }
4139     return msa;
4140   }
4141
4142   /**
4143    * Decides what is submitted to a secondary structure prediction service: the
4144    * first sequence in the alignment, or in the current selection, or, if the
4145    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4146    * region or the whole alignment. (where the first sequence in the set is the
4147    * one that the prediction will be for).
4148    */
4149   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4150   {
4151     AlignmentView seqs = null;
4152
4153     if ((viewport.getSelectionGroup() != null)
4154             && (viewport.getSelectionGroup().getSize() > 0))
4155     {
4156       seqs = viewport.getAlignmentView(true);
4157     }
4158     else
4159     {
4160       seqs = viewport.getAlignmentView(false);
4161     }
4162     // limit sequences - JBPNote in future - could spawn multiple prediction
4163     // jobs
4164     // TODO: viewport.getAlignment().isAligned is a global state - the local
4165     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4166     if (!viewport.getAlignment().isAligned(false))
4167     {
4168       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4169       // TODO: if seqs.getSequences().length>1 then should really have warned
4170       // user!
4171
4172     }
4173     return seqs;
4174   }
4175
4176   /**
4177    * DOCUMENT ME!
4178    * 
4179    * @param e
4180    *          DOCUMENT ME!
4181    */
4182   
4183   @Override
4184   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4185   {
4186     // Pick the tree file
4187     JalviewFileChooser chooser = new JalviewFileChooser(
4188             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4189     chooser.setFileView(new JalviewFileView());
4190     chooser.setDialogTitle(
4191             MessageManager.getString("label.select_newick_like_tree_file"));
4192     chooser.setToolTipText(
4193             MessageManager.getString("label.load_tree_file"));
4194
4195     chooser.setResponseHandler(0, new Runnable()
4196     {
4197       
4198       @Override
4199       public void run()
4200       {
4201         String filePath = chooser.getSelectedFile().getPath();
4202         Cache.setProperty("LAST_DIRECTORY", filePath);
4203         NewickFile fin = null;
4204         try
4205         {
4206           fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4207                   DataSourceType.FILE));
4208           viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4209         } catch (Exception ex)
4210         {
4211           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4212                   ex.getMessage(),
4213                   MessageManager
4214                           .getString("label.problem_reading_tree_file"),
4215                   JvOptionPane.WARNING_MESSAGE);
4216           ex.printStackTrace();
4217         }
4218         if (fin != null && fin.hasWarningMessage())
4219         {
4220           JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4221                   fin.getWarningMessage(),
4222                   MessageManager.getString(
4223                           "label.possible_problem_with_tree_file"),
4224                   JvOptionPane.WARNING_MESSAGE);
4225         }
4226       }
4227     });
4228     chooser.showOpenDialog(this);
4229   }
4230
4231   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4232   {
4233     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4234   }
4235
4236   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4237           int h, int x, int y)
4238   {
4239     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4240   }
4241
4242   /**
4243    * Add a treeviewer for the tree extracted from a Newick file object to the
4244    * current alignment view
4245    * 
4246    * @param nf
4247    *          the tree
4248    * @param title
4249    *          tree viewer title
4250    * @param input
4251    *          Associated alignment input data (or null)
4252    * @param w
4253    *          width
4254    * @param h
4255    *          height
4256    * @param x
4257    *          position
4258    * @param y
4259    *          position
4260    * @return TreePanel handle
4261    */
4262   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4263           AlignmentView input, int w, int h, int x, int y)
4264   {
4265     TreePanel tp = null;
4266
4267     try
4268     {
4269       nf.parse();
4270
4271       if (nf.getTree() != null)
4272       {
4273         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4274         Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4275         if (dim == null)
4276         {
4277           dim = new Dimension(w, h);
4278         }
4279         else
4280         {
4281           // no offset, either
4282           x = 0;
4283         }
4284         tp.setSize(dim.width, dim.height);
4285
4286         if (x > 0 && y > 0)
4287         {
4288           tp.setLocation(x, y);
4289         }
4290
4291         Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4292       }
4293     } catch (Exception ex)
4294     {
4295       ex.printStackTrace();
4296     }
4297
4298     return tp;
4299   }
4300
4301   private boolean buildingMenu = false;
4302
4303   /**
4304    * Generates menu items and listener event actions for web service clients
4305    * 
4306    */
4307   public void BuildWebServiceMenu()
4308   {
4309     while (buildingMenu)
4310     {
4311       try
4312       {
4313         System.err.println("Waiting for building menu to finish.");
4314         Thread.sleep(10);
4315       } catch (Exception e)
4316       {
4317       }
4318     }
4319     final AlignFrame me = this;
4320     buildingMenu = true;
4321     new Thread(new Runnable()
4322     {
4323       
4324       @Override
4325       public void run()
4326       {
4327         final List<JMenuItem> legacyItems = new ArrayList<>();
4328         try
4329         {
4330           // System.err.println("Building ws menu again "
4331           // + Thread.currentThread());
4332           // TODO: add support for context dependent disabling of services based
4333           // on
4334           // alignment and current selection
4335           // TODO: add additional serviceHandle parameter to specify abstract
4336           // handler
4337           // class independently of AbstractName
4338           // TODO: add in rediscovery GUI function to restart discoverer
4339           // TODO: group services by location as well as function and/or
4340           // introduce
4341           // object broker mechanism.
4342           final Vector<JMenu> wsmenu = new Vector<>();
4343           final IProgressIndicator af = me;
4344
4345           /*
4346            * do not i18n these strings - they are hard-coded in class
4347            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4348            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4349            */
4350           final JMenu msawsmenu = new JMenu("Alignment");
4351           final JMenu secstrmenu = new JMenu(
4352                   "Secondary Structure Prediction");
4353           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4354           final JMenu analymenu = new JMenu("Analysis");
4355           final JMenu dismenu = new JMenu("Protein Disorder");
4356           // JAL-940 - only show secondary structure prediction services from
4357           // the legacy server
4358           Hashtable<String, Vector<ServiceHandle>> ds = Discoverer
4359                   .getInstance().getServices();
4360           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4361           // &&
4362           ds != null && (ds.size() > 0))
4363           {
4364             // TODO: refactor to allow list of AbstractName/Handler bindings to
4365             // be
4366             // stored or retrieved from elsewhere
4367             // No MSAWS used any more:
4368             // Vector msaws = null; // (Vector)
4369             // Discoverer.services.get("MsaWS");
4370             Vector<ServiceHandle> secstrpr = ds.get("SecStrPred");
4371             if (secstrpr != null)
4372             {
4373               // Add any secondary structure prediction services
4374               for (int i = 0, j = secstrpr.size(); i < j; i++)
4375               {
4376                 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4377                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4378                         .getServiceClient(sh);
4379                 int p = secstrmenu.getItemCount();
4380                 impl.attachWSMenuEntry(secstrmenu, me);
4381                 int q = secstrmenu.getItemCount();
4382                 for (int litm = p; litm < q; litm++)
4383                 {
4384                   legacyItems.add(secstrmenu.getItem(litm));
4385                 }
4386               }
4387             }
4388           }
4389
4390           // Add all submenus in the order they should appear on the web
4391           // services menu
4392           wsmenu.add(msawsmenu);
4393           wsmenu.add(secstrmenu);
4394           wsmenu.add(dismenu);
4395           wsmenu.add(analymenu);
4396           // No search services yet
4397           // wsmenu.add(seqsrchmenu);
4398
4399           javax.swing.SwingUtilities.invokeLater(new Runnable()
4400           {
4401             
4402             @Override
4403             public void run()
4404             {
4405               try
4406               {
4407                 webService.removeAll();
4408                 // first, add discovered services onto the webservices menu
4409                 if (wsmenu.size() > 0)
4410                 {
4411                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4412                   {
4413                     webService.add(wsmenu.get(i));
4414                   }
4415                 }
4416                 else
4417                 {
4418                   webService.add(me.webServiceNoServices);
4419                 }
4420                 // TODO: move into separate menu builder class.
4421                 // boolean new_sspred = false;
4422                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4423                 {
4424                   Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4425                   if (jws2servs != null)
4426                   {
4427                     if (jws2servs.hasServices())
4428                     {
4429                       jws2servs.attachWSMenuEntry(webService, me);
4430                       for (Jws2Instance sv : jws2servs.getServices())
4431                       {
4432                         if (sv.description.toLowerCase().contains("jpred"))
4433                         {
4434                           for (JMenuItem jmi : legacyItems)
4435                           {
4436                             jmi.setVisible(false);
4437                           }
4438                         }
4439                       }
4440
4441                     }
4442                     if (jws2servs.isRunning())
4443                     {
4444                       JMenuItem tm = new JMenuItem(
4445                               "Still discovering JABA Services");
4446                       tm.setEnabled(false);
4447                       webService.add(tm);
4448                     }
4449                   }
4450                 }
4451                 build_urlServiceMenu(me.webService);
4452                 build_fetchdbmenu(webService);
4453                 for (JMenu item : wsmenu)
4454                 {
4455                   if (item.getItemCount() == 0)
4456                   {
4457                     item.setEnabled(false);
4458                   }
4459                   else
4460                   {
4461                     item.setEnabled(true);
4462                   }
4463                 }
4464               } catch (Exception e)
4465               {
4466                 Cache.log.debug(
4467                         "Exception during web service menu building process.",
4468                         e);
4469               }
4470             }
4471           });
4472         } catch (Exception e)
4473         {
4474         }
4475         buildingMenu = false;
4476       }
4477     }).start();
4478
4479   }
4480
4481   /**
4482    * construct any groupURL type service menu entries.
4483    * 
4484    * @param webService
4485    */
4486   protected void build_urlServiceMenu(JMenu webService)
4487   {
4488     // TODO: remove this code when 2.7 is released
4489     // DEBUG - alignmentView
4490     /*
4491      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4492      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4493      * 
4494      *  public void actionPerformed(ActionEvent e) {
4495      * jalview.datamodel.AlignmentView
4496      * .testSelectionViews(af.viewport.getAlignment(),
4497      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4498      * 
4499      * }); webService.add(testAlView);
4500      */
4501     // TODO: refactor to RestClient discoverer and merge menu entries for
4502     // rest-style services with other types of analysis/calculation service
4503     // SHmmr test client - still being implemented.
4504     // DEBUG - alignmentView
4505
4506     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4507             .getRestClients())
4508     {
4509       client.attachWSMenuEntry(
4510               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4511               this);
4512     }
4513   }
4514
4515   /**
4516    * Searches the alignment sequences for xRefs and builds the Show
4517    * Cross-References menu (formerly called Show Products), with database
4518    * sources for which cross-references are found (protein sources for a
4519    * nucleotide alignment and vice versa)
4520    * 
4521    * @return true if Show Cross-references menu should be enabled
4522    */
4523   public boolean canShowProducts()
4524   {
4525     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4526     AlignmentI dataset = viewport.getAlignment().getDataset();
4527
4528     showProducts.removeAll();
4529     final boolean dna = viewport.getAlignment().isNucleotide();
4530
4531     if (seqs == null || seqs.length == 0)
4532     {
4533       // nothing to see here.
4534       return false;
4535     }
4536
4537     boolean showp = false;
4538     try
4539     {
4540       List<String> ptypes = new CrossRef(seqs, dataset)
4541               .findXrefSourcesForSequences(dna);
4542
4543       for (final String source : ptypes)
4544       {
4545         showp = true;
4546         final AlignFrame af = this;
4547         JMenuItem xtype = new JMenuItem(source);
4548         xtype.addActionListener(new ActionListener()
4549         {
4550           
4551           @Override
4552           public void actionPerformed(ActionEvent e)
4553           {
4554             showProductsFor(af.viewport.getSequenceSelection(), dna,
4555                     source);
4556           }
4557         });
4558         showProducts.add(xtype);
4559       }
4560       showProducts.setVisible(showp);
4561       showProducts.setEnabled(showp);
4562     } catch (Exception e)
4563     {
4564       Cache.log.warn(
4565               "canShowProducts threw an exception - please report to help@jalview.org",
4566               e);
4567       return false;
4568     }
4569     return showp;
4570   }
4571
4572   /**
4573    * Finds and displays cross-references for the selected sequences (protein
4574    * products for nucleotide sequences, dna coding sequences for peptides).
4575    * 
4576    * @param sel
4577    *          the sequences to show cross-references for
4578    * @param dna
4579    *          true if from a nucleotide alignment (so showing proteins)
4580    * @param source
4581    *          the database to show cross-references for
4582    */
4583   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4584           final String source)
4585   {
4586     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4587             .start();
4588   }
4589
4590   /**
4591    * Construct and display a new frame containing the translation of this
4592    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4593    */
4594   
4595   @Override
4596   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4597   {
4598     AlignmentI al = null;
4599     try
4600     {
4601       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4602
4603       al = dna.translateCdna(codeTable);
4604     } catch (Exception ex)
4605     {
4606       jalview.bin.Cache.log.error(
4607               "Exception during translation. Please report this !", ex);
4608       final String msg = MessageManager.getString(
4609               "label.error_when_translating_sequences_submit_bug_report");
4610       final String errorTitle = MessageManager
4611               .getString("label.implementation_error")
4612               + MessageManager.getString("label.translation_failed");
4613       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4614               errorTitle, JvOptionPane.ERROR_MESSAGE);
4615       return;
4616     }
4617     if (al == null || al.getHeight() == 0)
4618     {
4619       final String msg = MessageManager.getString(
4620               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4621       final String errorTitle = MessageManager
4622               .getString("label.translation_failed");
4623       JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4624               errorTitle, JvOptionPane.WARNING_MESSAGE);
4625     }
4626     else
4627     {
4628       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4629       af.setFileFormat(this.currentFileFormat);
4630       final String newTitle = MessageManager
4631               .formatMessage("label.translation_of_params", new Object[]
4632               { this.getTitle(), codeTable.getId() });
4633       af.setTitle(newTitle);
4634       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4635       {
4636         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4637         AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4638       }
4639       else
4640       {
4641         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4642                 DEFAULT_HEIGHT);
4643       }
4644     }
4645   }
4646
4647   /**
4648    * Set the file format
4649    * 
4650    * @param format
4651    */
4652   public void setFileFormat(FileFormatI format)
4653   {
4654     this.currentFileFormat = format;
4655   }
4656
4657   /**
4658    * Try to load a features file onto the alignment.
4659    * 
4660    * @param file
4661    *          contents or path to retrieve file or a File object
4662    * @param sourceType
4663    *          access mode of file (see jalview.io.AlignFile)
4664    * @return true if features file was parsed correctly.
4665    */
4666   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4667   {
4668     // BH 2018
4669     return avc.parseFeaturesFile(file, sourceType,
4670             Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4671
4672   }
4673
4674   
4675   @Override
4676   public void refreshFeatureUI(boolean enableIfNecessary)
4677   {
4678     // note - currently this is only still here rather than in the controller
4679     // because of the featureSettings hard reference that is yet to be
4680     // abstracted
4681     if (enableIfNecessary)
4682     {
4683       viewport.setShowSequenceFeatures(true);
4684       showSeqFeatures.setSelected(true);
4685     }
4686
4687   }
4688
4689   
4690   @Override
4691   public void dragEnter(DropTargetDragEvent evt)
4692   {
4693   }
4694
4695   
4696   @Override
4697   public void dragExit(DropTargetEvent evt)
4698   {
4699   }
4700
4701   
4702   @Override
4703   public void dragOver(DropTargetDragEvent evt)
4704   {
4705   }
4706
4707   
4708   @Override
4709   public void dropActionChanged(DropTargetDragEvent evt)
4710   {
4711   }
4712
4713   
4714   @Override
4715   public void drop(DropTargetDropEvent evt)
4716   {
4717     // JAL-1552 - acceptDrop required before getTransferable call for
4718     // Java's Transferable for native dnd
4719     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4720     Transferable t = evt.getTransferable();
4721
4722     final List<Object> files = new ArrayList<>();
4723     List<DataSourceType> protocols = new ArrayList<>();
4724
4725     try
4726     {
4727       Desktop.transferFromDropTarget(files, protocols, evt, t);
4728       if (files.size() > 0)
4729     {
4730       new Thread(new Runnable()
4731       {
4732         
4733         @Override
4734         public void run()
4735         {
4736             loadDroppedFiles(files, protocols, evt, t);
4737           }
4738         }).start();
4739       }
4740     } catch (Exception e)
4741     {
4742       e.printStackTrace();
4743     }
4744   }
4745
4746   protected void loadDroppedFiles(List<Object> files,
4747           List<DataSourceType> protocols, DropTargetDropEvent evt,
4748           Transferable t)
4749   {
4750           try
4751           {
4752             // check to see if any of these files have names matching sequences
4753             // in
4754             // the alignment
4755             SequenceIdMatcher idm = new SequenceIdMatcher(
4756                     viewport.getAlignment().getSequencesArray());
4757             /**
4758              * Object[] { String,SequenceI}
4759              */
4760             ArrayList<Object[]> filesmatched = new ArrayList<>();
4761             ArrayList<Object> filesnotmatched = new ArrayList<>();
4762             for (int i = 0; i < files.size(); i++)
4763             {
4764               // BH 2018
4765               Object file = files.get(i);
4766               String fileName = file.toString();
4767               String pdbfn = "";
4768               DataSourceType protocol = (file instanceof File
4769                       ? DataSourceType.FILE
4770                       : FormatAdapter.checkProtocol(fileName));
4771               if (protocol == DataSourceType.FILE)
4772               {
4773                 File fl;
4774                 if (file instanceof File)
4775                 {
4776                   fl = (File) file;
4777                   Platform.cacheFileData(fl);
4778                 }
4779                 else
4780                 {
4781                   fl = new File(fileName);
4782                 }
4783                 pdbfn = fl.getName();
4784               }
4785               else if (protocol == DataSourceType.URL)
4786               {
4787                 URL url = new URL(fileName);
4788                 pdbfn = url.getFile();
4789               }
4790               if (pdbfn.length() > 0)
4791               {
4792                 // attempt to find a match in the alignment
4793                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4794                 int l = 0, c = pdbfn.indexOf(".");
4795                 while (mtch == null && c != -1)
4796                 {
4797                   do
4798                   {
4799                     l = c;
4800                   } while ((c = pdbfn.indexOf(".", l)) > l);
4801                   if (l > -1)
4802                   {
4803                     pdbfn = pdbfn.substring(0, l);
4804                   }
4805                   mtch = idm.findAllIdMatches(pdbfn);
4806                 }
4807                 if (mtch != null)
4808                 {
4809                   FileFormatI type;
4810                   try
4811                   {
4812                     type = new IdentifyFile().identify(file, protocol);
4813                   } catch (Exception ex)
4814                   {
4815                     type = null;
4816                   }
4817                   if (type != null && type.isStructureFile())
4818                   {
4819                     filesmatched.add(new Object[] { file, protocol, mtch });
4820                     continue;
4821                   }
4822                 }
4823                 // File wasn't named like one of the sequences or wasn't a PDB
4824                 // file.
4825                 filesnotmatched.add(file);
4826               }
4827             }
4828             int assocfiles = 0;
4829             if (filesmatched.size() > 0)
4830             {
4831               boolean autoAssociate = Cache.getDefault(
4832                       Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4833               if (!autoAssociate)
4834               {
4835                 String msg = MessageManager.formatMessage(
4836                         "label.automatically_associate_structure_files_with_sequences_same_name",
4837                         new Object[]
4838                         { Integer.valueOf(filesmatched.size())
4839                                 .toString() });
4840                 String ttl = MessageManager.getString(
4841                         "label.automatically_associate_structure_files_by_name");
4842           int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
4843                   JvOptionPane.YES_NO_OPTION);
4844                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4845               }
4846               if (autoAssociate)
4847               {
4848                 for (Object[] fm : filesmatched)
4849                 {
4850                   // try and associate
4851                   // TODO: may want to set a standard ID naming formalism for
4852                   // associating PDB files which have no IDs.
4853                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4854                   {
4855                     PDBEntry pe = AssociatePdbFileWithSeq
4856                             .associatePdbWithSeq(fm[0].toString(),
4857                                     (DataSourceType) fm[1], toassoc, false);
4858                     if (pe != null)
4859                     {
4860                       System.err.println("Associated file : "
4861                               + (fm[0].toString()) + " with "
4862                               + toassoc.getDisplayId(true));
4863                       assocfiles++;
4864                     }
4865                   }
4866                   // TODO: do we need to update overview ? only if features are
4867                   // shown I guess
4868                   alignPanel.paintAlignment(true, false);
4869                 }
4870               }
4871               else
4872               {
4873                 /*
4874                  * add declined structures as sequences
4875                  */
4876                 for (Object[] o : filesmatched)
4877                 {
4878                   filesnotmatched.add(o[0]);
4879                 }
4880               }
4881             }
4882             if (filesnotmatched.size() > 0)
4883             {
4884         if (assocfiles > 0 && (Cache
4885                 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4886                 || JvOptionPane.showConfirmDialog(this,
4887                               "<html>" + MessageManager.formatMessage(
4888                                       "label.ignore_unmatched_dropped_files_info",
4889                                       new Object[]
4890                                       { Integer.valueOf(
4891                                               filesnotmatched.size())
4892                                               .toString() })
4893                                       + "</html>",
4894                               MessageManager.getString(
4895                                       "label.ignore_unmatched_dropped_files"),
4896                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4897               {
4898                 return;
4899               }
4900               for (Object fn : filesnotmatched)
4901               {
4902                 loadJalviewDataFile(fn, null, null, null);
4903               }
4904
4905             }
4906           } catch (Exception ex)
4907           {
4908             ex.printStackTrace();
4909           }
4910         }
4911
4912   /**
4913    * Attempt to load a "dropped" file or URL string, by testing in turn for
4914    * <ul>
4915    * <li>an Annotation file</li>
4916    * <li>a JNet file</li>
4917    * <li>a features file</li>
4918    * <li>else try to interpret as an alignment file</li>
4919    * </ul>
4920    * 
4921    * @param file
4922    *          either a filename or a URL string.
4923    */
4924   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4925           FileFormatI format, SequenceI assocSeq)
4926   {
4927     // BH 2018 was String file
4928     try
4929     {
4930       if (sourceType == null)
4931       {
4932         sourceType = FormatAdapter.checkProtocol(file);
4933       }
4934       // if the file isn't identified, or not positively identified as some
4935       // other filetype (PFAM is default unidentified alignment file type) then
4936       // try to parse as annotation.
4937       boolean isAnnotation = (format == null
4938               || FileFormat.Pfam.equals(format))
4939                       ? new AnnotationFile().annotateAlignmentView(viewport,
4940                               file, sourceType)
4941                       : false;
4942
4943       if (!isAnnotation)
4944       {
4945         // first see if its a T-COFFEE score file
4946         TCoffeeScoreFile tcf = null;
4947         try
4948         {
4949           tcf = new TCoffeeScoreFile(file, sourceType);
4950           if (tcf.isValid())
4951           {
4952             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4953             {
4954               buildColourMenu();
4955               changeColour(
4956                       new TCoffeeColourScheme(viewport.getAlignment()));
4957               isAnnotation = true;
4958               setStatus(MessageManager.getString(
4959                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4960             }
4961             else
4962             {
4963               // some problem - if no warning its probable that the ID matching
4964               // process didn't work
4965               JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4966                       tcf.getWarningMessage() == null
4967                               ? MessageManager.getString(
4968                                       "label.check_file_matches_sequence_ids_alignment")
4969                               : tcf.getWarningMessage(),
4970                       MessageManager.getString(
4971                               "label.problem_reading_tcoffee_score_file"),
4972                       JvOptionPane.WARNING_MESSAGE);
4973             }
4974           }
4975           else
4976           {
4977             tcf = null;
4978           }
4979         } catch (Exception x)
4980         {
4981           Cache.log.debug(
4982                   "Exception when processing data source as T-COFFEE score file",
4983                   x);
4984           tcf = null;
4985         }
4986         if (tcf == null)
4987         {
4988           // try to see if its a JNet 'concise' style annotation file *before*
4989           // we
4990           // try to parse it as a features file
4991           if (format == null)
4992           {
4993             format = new IdentifyFile().identify(file, sourceType);
4994           }
4995           if (FileFormat.ScoreMatrix == format)
4996           {
4997             ScoreMatrixFile sm = new ScoreMatrixFile(
4998                     new FileParse(file, sourceType));
4999             sm.parse();
5000             // todo: i18n this message
5001             setStatus(MessageManager.formatMessage(
5002                     "label.successfully_loaded_matrix",
5003                     sm.getMatrixName()));
5004           }
5005           else if (FileFormat.Jnet.equals(format))
5006           {
5007             JPredFile predictions = new JPredFile(file, sourceType);
5008             new JnetAnnotationMaker();
5009             JnetAnnotationMaker.add_annotation(predictions,
5010                     viewport.getAlignment(), 0, false);
5011             viewport.getAlignment().setupJPredAlignment();
5012             isAnnotation = true;
5013           }
5014           // else if (IdentifyFile.FeaturesFile.equals(format))
5015           else if (FileFormat.Features.equals(format))
5016           {
5017             if (parseFeaturesFile(file, sourceType))
5018             {
5019               SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5020               if (splitFrame != null)
5021               {
5022                 splitFrame.repaint();
5023               }
5024               else
5025               {
5026               alignPanel.paintAlignment(true, true);
5027             }
5028           }
5029           }
5030           else
5031           {
5032             new FileLoader().loadFile(viewport, file, sourceType, format);
5033           }
5034         }
5035       }
5036       if (isAnnotation)
5037       {
5038         updateForAnnotations();
5039       }
5040     } catch (Exception ex)
5041     {
5042       ex.printStackTrace();
5043     } catch (OutOfMemoryError oom)
5044     {
5045       try
5046       {
5047         System.gc();
5048       } catch (Exception x)
5049       {
5050       }
5051       new OOMWarning(
5052               "loading data "
5053                       + (sourceType != null
5054                               ? (sourceType == DataSourceType.PASTE
5055                                       ? "from clipboard."
5056                                       : "using " + sourceType + " from "
5057                                               + file)
5058                               : ".")
5059                       + (format != null
5060                               ? "(parsing as '" + format + "' file)"
5061                               : ""),
5062               oom, Desktop.getDesktopPane());
5063     }
5064   }
5065
5066   /**
5067    * Do all updates necessary after an annotation file such as jnet. Also called
5068    * from Jalview.loadAppletParams for "annotations", "jnetFile"
5069    */
5070   public void updateForAnnotations()
5071   {
5072     alignPanel.adjustAnnotationHeight();
5073     viewport.updateSequenceIdColours();
5074     buildSortByAnnotationScoresMenu();
5075     alignPanel.paintAlignment(true, true);
5076   }
5077
5078   /**
5079    * Change the display state for the given feature groups -- Added by BH from
5080    * JalviewLite
5081    * 
5082    * @param groups
5083    *          list of group strings
5084    * @param state
5085    *          visible or invisible
5086    */
5087   
5088   public void setFeatureGroupState(String[] groups, boolean state)
5089   {
5090     jalview.api.FeatureRenderer fr = null;
5091     viewport.setShowSequenceFeatures(true);
5092     if (alignPanel != null
5093             && (fr = alignPanel.getFeatureRenderer()) != null)
5094     {
5095
5096       fr.setGroupVisibility(Arrays.asList(groups), state);
5097       alignPanel.getSeqPanel().seqCanvas.repaint();
5098       if (alignPanel.overviewPanel != null)
5099       {
5100         alignPanel.overviewPanel.updateOverviewImage();
5101       }
5102     }
5103   }
5104
5105   /**
5106    * Method invoked by the ChangeListener on the tabbed pane, in other words
5107    * when a different tabbed pane is selected by the user or programmatically.
5108    */
5109   
5110   @Override
5111   public void tabSelectionChanged(int index)
5112   {
5113     if (index > -1)
5114     {
5115       alignPanel = alignPanels.get(index);
5116       viewport = alignPanel.av;
5117       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5118       setMenusFromViewport(viewport);
5119       if (featureSettings != null// && featureSettings.isOpen()
5120               && featureSettings.fr.getViewport() != viewport)
5121       {
5122         if (viewport.isShowSequenceFeatures())
5123         {
5124           // refresh the featureSettings to reflect UI change
5125           showFeatureSettingsUI();
5126         }
5127         else
5128         {
5129           // close feature settings for this view.
5130           featureSettings.close();
5131         }
5132       }
5133
5134     }
5135
5136     /*
5137      * 'focus' any colour slider that is open to the selected viewport
5138      */
5139     if (viewport.getConservationSelected())
5140     {
5141       SliderPanel.setConservationSlider(alignPanel,
5142               viewport.getResidueShading(), alignPanel.getViewName());
5143     }
5144     else
5145     {
5146       SliderPanel.hideConservationSlider();
5147     }
5148     if (viewport.getAbovePIDThreshold())
5149     {
5150       SliderPanel.setPIDSliderSource(alignPanel,
5151               viewport.getResidueShading(), alignPanel.getViewName());
5152     }
5153     else
5154     {
5155       SliderPanel.hidePIDSlider();
5156     }
5157
5158     /*
5159      * If there is a frame linked to this one in a SplitPane, switch it to the
5160      * same view tab index. No infinite recursion of calls should happen, since
5161      * tabSelectionChanged() should not get invoked on setting the selected
5162      * index to an unchanged value. Guard against setting an invalid index
5163      * before the new view peer tab has been created.
5164      */
5165     final AlignViewportI peer = viewport.getCodingComplement();
5166     if (peer != null)
5167     {
5168       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5169               .getAlignPanel().alignFrame;
5170       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5171       {
5172         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5173       }
5174     }
5175   }
5176
5177   /**
5178    * On right mouse click on view tab, prompt for and set new view name.
5179    */
5180   
5181   @Override
5182   public void tabbedPane_mousePressed(MouseEvent e)
5183   {
5184     if (e.isPopupTrigger())
5185     {
5186       String msg = MessageManager.getString("label.enter_view_name");
5187       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5188       String reply = JvOptionPane.showInputDialog(msg, ttl);
5189
5190       if (reply != null)
5191       {
5192         viewport.setViewName(reply);
5193         // TODO warn if reply is in getExistingViewNames()?
5194         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5195       }
5196     }
5197   }
5198
5199   public AlignViewport getCurrentView()
5200   {
5201     return viewport;
5202   }
5203
5204   /**
5205    * Open the dialog for regex description parsing.
5206    */
5207   
5208   @Override
5209   protected void extractScores_actionPerformed(ActionEvent e)
5210   {
5211     ParseProperties pp = new jalview.analysis.ParseProperties(
5212             viewport.getAlignment());
5213     // TODO: verify regex and introduce GUI dialog for version 2.5
5214     // if (pp.getScoresFromDescription("col", "score column ",
5215     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5216     // true)>0)
5217     if (pp.getScoresFromDescription("description column",
5218             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5219     {
5220       buildSortByAnnotationScoresMenu();
5221     }
5222   }
5223
5224   /*
5225    * (non-Javadoc)
5226    * 
5227    * @see
5228    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5229    * )
5230    */
5231   
5232   @Override
5233   protected void showDbRefs_actionPerformed(ActionEvent e)
5234   {
5235     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5236   }
5237
5238   /*
5239    * (non-Javadoc)
5240    * 
5241    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5242    * ActionEvent)
5243    */
5244   
5245   @Override
5246   protected void showNpFeats_actionPerformed(ActionEvent e)
5247   {
5248     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5249   }
5250
5251   /**
5252    * find the viewport amongst the tabs in this alignment frame and close that
5253    * tab
5254    * 
5255    * @param av
5256    */
5257   public boolean closeView(AlignViewportI av)
5258   {
5259     if (viewport == av)
5260     {
5261       this.closeMenuItem_actionPerformed(false);
5262       return true;
5263     }
5264     Component[] comp = tabbedPane.getComponents();
5265     for (int i = 0; comp != null && i < comp.length; i++)
5266     {
5267       if (comp[i] instanceof AlignmentPanel)
5268       {
5269         if (((AlignmentPanel) comp[i]).av == av)
5270         {
5271           // close the view.
5272           closeView((AlignmentPanel) comp[i]);
5273           return true;
5274         }
5275       }
5276     }
5277     return false;
5278   }
5279
5280   protected void build_fetchdbmenu(JMenu webService)
5281   {
5282     // Temporary hack - DBRef Fetcher always top level ws entry.
5283     // TODO We probably want to store a sequence database checklist in
5284     // preferences and have checkboxes.. rather than individual sources selected
5285     // here
5286     final JMenu rfetch = new JMenu(
5287             MessageManager.getString("action.fetch_db_references"));
5288     rfetch.setToolTipText(MessageManager.getString(
5289             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5290     webService.add(rfetch);
5291
5292     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5293             MessageManager.getString("option.trim_retrieved_seqs"));
5294     trimrs.setToolTipText(
5295             MessageManager.getString("label.trim_retrieved_sequences"));
5296     trimrs.setSelected(
5297             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5298     trimrs.addActionListener(new ActionListener()
5299     {
5300       
5301       @Override
5302       public void actionPerformed(ActionEvent e)
5303       {
5304         trimrs.setSelected(trimrs.isSelected());
5305         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5306                 Boolean.valueOf(trimrs.isSelected()).toString());
5307       }
5308     });
5309     rfetch.add(trimrs);
5310     JMenuItem fetchr = new JMenuItem(
5311             MessageManager.getString("label.standard_databases"));
5312     fetchr.setToolTipText(
5313             MessageManager.getString("label.fetch_embl_uniprot"));
5314     fetchr.addActionListener(new ActionListener()
5315     {
5316
5317       
5318       @Override
5319       public void actionPerformed(ActionEvent e)
5320       {
5321         new Thread(new Runnable()
5322         {
5323           
5324           @Override
5325           public void run()
5326           {
5327             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5328                     .getAlignment().isNucleotide();
5329             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5330                     alignPanel.av.getSequenceSelection(),
5331                     alignPanel.alignFrame, null,
5332                     alignPanel.alignFrame.featureSettings, isNucleotide);
5333             dbRefFetcher.addListener(new FetchFinishedListenerI()
5334             {
5335               
5336               @Override
5337               public void finished()
5338               {
5339                 //
5340                 // for (FeatureSettingsModelI srcSettings : dbRefFetcher
5341                 // .getFeatureSettingsModels())
5342                 // {
5343                 //
5344                 // alignPanel.av.mergeFeaturesStyle(srcSettings);
5345                 // }
5346                 AlignFrame.this.setMenusForViewport();
5347               }
5348             });
5349             dbRefFetcher.fetchDBRefs(false);
5350           }
5351         }).start();
5352
5353       }
5354
5355     });
5356     rfetch.add(fetchr);
5357     new Thread(new Runnable()
5358     {
5359       
5360       @Override
5361       public void run()
5362       {
5363         javax.swing.SwingUtilities.invokeLater(new Runnable()
5364         {
5365           
5366           @Override
5367           public void run()
5368           {
5369                   jalview.ws.SequenceFetcher
5370                   sf = jalview.ws.SequenceFetcher.getInstance();
5371             String[] dbclasses = sf.getNonAlignmentSources();
5372             List<DbSourceProxy> otherdb;
5373             JMenu dfetch = new JMenu();
5374             JMenu ifetch = new JMenu();
5375             JMenuItem fetchr = null;
5376             int comp = 0, icomp = 0, mcomp = 15;
5377             String mname = null;
5378             int dbi = 0;
5379             for (String dbclass : dbclasses)
5380             {
5381               otherdb = sf.getSourceProxy(dbclass);
5382               // add a single entry for this class, or submenu allowing 'fetch
5383               // all' or pick one
5384               if (otherdb == null || otherdb.size() < 1)
5385               {
5386                 continue;
5387               }
5388               if (mname == null)
5389               {
5390                 mname = "From " + dbclass;
5391               }
5392               if (otherdb.size() == 1)
5393               {
5394                 DbSourceProxy src = otherdb.get(0);
5395                 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5396                 fetchr = new JMenuItem(src.getDbSource());
5397                 fetchr.addActionListener(new ActionListener()
5398                 {
5399
5400                   
5401                   @Override
5402                   public void actionPerformed(ActionEvent e)
5403                   {
5404                     new Thread(new Runnable()
5405                     {
5406
5407                       
5408                       @Override
5409                       public void run()
5410                       {
5411                         boolean isNucleotide = alignPanel.alignFrame
5412                                 .getViewport().getAlignment()
5413                                 .isNucleotide();
5414                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5415                                 alignPanel.av.getSequenceSelection(),
5416                                 alignPanel.alignFrame, dassource,
5417                                 alignPanel.alignFrame.featureSettings,
5418                                 isNucleotide);
5419                         dbRefFetcher
5420                                 .addListener(new FetchFinishedListenerI()
5421                                 {
5422                                   
5423                                   @Override
5424                                   public void finished()
5425                                   {
5426                                     FeatureSettingsModelI srcSettings = dassource[0]
5427                                             .getFeatureColourScheme();
5428                                     // alignPanel.av.mergeFeaturesStyle(
5429                                     // srcSettings);
5430                                     AlignFrame.this.setMenusForViewport();
5431                                   }
5432                                 });
5433                         dbRefFetcher.fetchDBRefs(false);
5434                       }
5435                     }).start();
5436                   }
5437
5438                 });
5439                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5440                         MessageManager.formatMessage(
5441                                 "label.fetch_retrieve_from", new Object[]
5442                                 { src.getDbName() })));
5443                 dfetch.add(fetchr);
5444                 comp++;
5445               }
5446               else
5447               {
5448                 final DbSourceProxy[] dassource = otherdb
5449                         .toArray(new DbSourceProxy[0]);
5450                 // fetch all entry
5451                 DbSourceProxy src = otherdb.get(0);
5452                 fetchr = new JMenuItem(MessageManager
5453                         .formatMessage("label.fetch_all_param", new Object[]
5454                         { src.getDbSource() }));
5455                 fetchr.addActionListener(new ActionListener()
5456                 {
5457                   
5458                   @Override
5459                   public void actionPerformed(ActionEvent e)
5460                   {
5461                     new Thread(new Runnable()
5462                     {
5463
5464                       
5465                       @Override
5466                       public void run()
5467                       {
5468                         boolean isNucleotide = alignPanel.alignFrame
5469                                 .getViewport().getAlignment()
5470                                 .isNucleotide();
5471                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5472                                 alignPanel.av.getSequenceSelection(),
5473                                 alignPanel.alignFrame, dassource,
5474                                 alignPanel.alignFrame.featureSettings,
5475                                 isNucleotide);
5476                         dbRefFetcher
5477                                 .addListener(new FetchFinishedListenerI()
5478                                 {
5479                                   
5480                                   @Override
5481                                   public void finished()
5482                                   {
5483                                     AlignFrame.this.setMenusForViewport();
5484                                   }
5485                                 });
5486                         dbRefFetcher.fetchDBRefs(false);
5487                       }
5488                     }).start();
5489                   }
5490                 });
5491
5492                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5493                         MessageManager.formatMessage(
5494                                 "label.fetch_retrieve_from_all_sources",
5495                                 new Object[]
5496                                 { Integer.valueOf(otherdb.size())
5497                                         .toString(),
5498                                     src.getDbSource(), src.getDbName() })));
5499                 dfetch.add(fetchr);
5500                 comp++;
5501                 // and then build the rest of the individual menus
5502                 ifetch = new JMenu(MessageManager.formatMessage(
5503                         "label.source_from_db_source", new Object[]
5504                         { src.getDbSource() }));
5505                 icomp = 0;
5506                 String imname = null;
5507                 int i = 0;
5508                 for (DbSourceProxy sproxy : otherdb)
5509                 {
5510                   String dbname = sproxy.getDbName();
5511                   String sname = dbname.length() > 5
5512                           ? dbname.substring(0, 5) + "..."
5513                           : dbname;
5514                   String msname = dbname.length() > 10
5515                           ? dbname.substring(0, 10) + "..."
5516                           : dbname;
5517                   if (imname == null)
5518                   {
5519                     imname = MessageManager
5520                             .formatMessage("label.from_msname", new Object[]
5521                             { sname });
5522                   }
5523                   fetchr = new JMenuItem(msname);
5524                   final DbSourceProxy[] dassrc = { sproxy };
5525                   fetchr.addActionListener(new ActionListener()
5526                   {
5527
5528                     
5529                     @Override
5530                     public void actionPerformed(ActionEvent e)
5531                     {
5532                       new Thread(new Runnable()
5533                       {
5534
5535                         
5536                         @Override
5537                         public void run()
5538                         {
5539                           boolean isNucleotide = alignPanel.alignFrame
5540                                   .getViewport().getAlignment()
5541                                   .isNucleotide();
5542                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5543                                   alignPanel.av.getSequenceSelection(),
5544                                   alignPanel.alignFrame, dassrc,
5545                                   alignPanel.alignFrame.featureSettings,
5546                                   isNucleotide);
5547                           dbRefFetcher
5548                                   .addListener(new FetchFinishedListenerI()
5549                                   {
5550                                     
5551                                     @Override
5552                                     public void finished()
5553                                     {
5554                                       AlignFrame.this.setMenusForViewport();
5555                                     }
5556                                   });
5557                           dbRefFetcher.fetchDBRefs(false);
5558                         }
5559                       }).start();
5560                     }
5561
5562                   });
5563                   fetchr.setToolTipText(
5564                           "<html>" + MessageManager.formatMessage(
5565                                   "label.fetch_retrieve_from", new Object[]
5566                                   { dbname }));
5567                   ifetch.add(fetchr);
5568                   ++i;
5569                   if (++icomp >= mcomp || i == (otherdb.size()))
5570                   {
5571                     ifetch.setText(MessageManager.formatMessage(
5572                             "label.source_to_target", imname, sname));
5573                     dfetch.add(ifetch);
5574                     ifetch = new JMenu();
5575                     imname = null;
5576                     icomp = 0;
5577                     comp++;
5578                   }
5579                 }
5580               }
5581               ++dbi;
5582               if (comp >= mcomp || dbi >= (dbclasses.length))
5583               {
5584                 dfetch.setText(MessageManager.formatMessage(
5585                         "label.source_to_target", mname, dbclass));
5586                 rfetch.add(dfetch);
5587                 dfetch = new JMenu();
5588                 mname = null;
5589                 comp = 0;
5590               }
5591             }
5592           }
5593         });
5594       }
5595     }).start();
5596
5597   }
5598
5599   /**
5600    * Left justify the whole alignment.
5601    */
5602   
5603   @Override
5604   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5605   {
5606     AlignmentI al = viewport.getAlignment();
5607     al.justify(false);
5608     viewport.firePropertyChange("alignment", null, al);
5609   }
5610
5611   /**
5612    * Right justify the whole alignment.
5613    */
5614   
5615   @Override
5616   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5617   {
5618     AlignmentI al = viewport.getAlignment();
5619     al.justify(true);
5620     viewport.firePropertyChange("alignment", null, al);
5621   }
5622
5623   
5624   @Override
5625   public void setShowSeqFeatures(boolean b)
5626   {
5627     showSeqFeatures.setSelected(b);
5628     viewport.setShowSequenceFeatures(b);
5629   }
5630
5631   /*
5632    * (non-Javadoc)
5633    * 
5634    * @see
5635    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5636    * awt.event.ActionEvent)
5637    */
5638   
5639   @Override
5640   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5641   {
5642     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5643     alignPanel.paintAlignment(false, false);
5644   }
5645
5646   /*
5647    * (non-Javadoc)
5648    * 
5649    * @see
5650    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5651    * .ActionEvent)
5652    */
5653   
5654   @Override
5655   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5656   {
5657     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5658     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5659
5660   }
5661
5662   /*
5663    * (non-Javadoc)
5664    * 
5665    * @see
5666    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5667    * .event.ActionEvent)
5668    */
5669   
5670   @Override
5671   protected void showGroupConservation_actionPerformed(ActionEvent e)
5672   {
5673     viewport.setShowGroupConservation(showGroupConservation.getState());
5674     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5675   }
5676
5677   /*
5678    * (non-Javadoc)
5679    * 
5680    * @see
5681    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5682    * .event.ActionEvent)
5683    */
5684   
5685   @Override
5686   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5687   {
5688     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5689     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5690   }
5691
5692   /*
5693    * (non-Javadoc)
5694    * 
5695    * @see
5696    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5697    * .event.ActionEvent)
5698    */
5699   
5700   @Override
5701   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5702   {
5703     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5704     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5705   }
5706
5707   
5708   @Override
5709   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5710   {
5711     showSequenceLogo.setState(true);
5712     viewport.setShowSequenceLogo(true);
5713     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5714     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5715   }
5716
5717   
5718   @Override
5719   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5720   {
5721     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5722   }
5723
5724   /*
5725    * (non-Javadoc)
5726    * 
5727    * @see
5728    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5729    * .event.ActionEvent)
5730    */
5731   
5732   @Override
5733   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5734   {
5735     if (avc.makeGroupsFromSelection())
5736     {
5737       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5738       alignPanel.updateAnnotation();
5739       alignPanel.paintAlignment(true,
5740               viewport.needToUpdateStructureViews());
5741     }
5742   }
5743
5744   public void clearAlignmentSeqRep()
5745   {
5746     // TODO refactor alignmentseqrep to controller
5747     if (viewport.getAlignment().hasSeqrep())
5748     {
5749       viewport.getAlignment().setSeqrep(null);
5750       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5751       alignPanel.updateAnnotation();
5752       alignPanel.paintAlignment(true, true);
5753     }
5754   }
5755
5756   
5757   @Override
5758   protected void createGroup_actionPerformed(ActionEvent e)
5759   {
5760     if (avc.createGroup())
5761     {
5762       if (applyAutoAnnotationSettings.isSelected())
5763       {
5764         alignPanel.updateAnnotation(true, false);
5765       }
5766       alignPanel.alignmentChanged();
5767     }
5768   }
5769
5770   
5771   @Override
5772   protected void unGroup_actionPerformed(ActionEvent e)
5773   {
5774     if (avc.unGroup())
5775     {
5776       alignPanel.alignmentChanged();
5777     }
5778   }
5779
5780   /**
5781    * make the given alignmentPanel the currently selected tab
5782    * 
5783    * @param alignmentPanel
5784    */
5785   public void setDisplayedView(AlignmentPanel alignmentPanel)
5786   {
5787     if (!viewport.getSequenceSetId()
5788             .equals(alignmentPanel.av.getSequenceSetId()))
5789     {
5790       throw new Error(MessageManager.getString(
5791               "error.implementation_error_cannot_show_view_alignment_frame"));
5792     }
5793     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5794             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5795     {
5796       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5797     }
5798   }
5799
5800   /**
5801    * Action on selection of menu options to Show or Hide annotations.
5802    * 
5803    * @param visible
5804    * @param forSequences
5805    *          update sequence-related annotations
5806    * @param forAlignment
5807    *          update non-sequence-related annotations
5808    */
5809   
5810   @Override
5811   protected void setAnnotationsVisibility(boolean visible,
5812           boolean forSequences, boolean forAlignment)
5813   {
5814     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5815             .getAlignmentAnnotation();
5816     if (anns == null)
5817     {
5818       return;
5819     }
5820     for (AlignmentAnnotation aa : anns)
5821     {
5822       /*
5823        * don't display non-positional annotations on an alignment
5824        */
5825       if (aa.annotations == null)
5826       {
5827         continue;
5828       }
5829       boolean apply = (aa.sequenceRef == null && forAlignment)
5830               || (aa.sequenceRef != null && forSequences);
5831       if (apply)
5832       {
5833         aa.visible = visible;
5834       }
5835     }
5836     alignPanel.validateAnnotationDimensions(true);
5837     alignPanel.alignmentChanged();
5838   }
5839
5840   /**
5841    * Store selected annotation sort order for the view and repaint.
5842    */
5843   
5844   @Override
5845   protected void sortAnnotations_actionPerformed()
5846   {
5847     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5848     this.alignPanel.av
5849             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5850     alignPanel.paintAlignment(false, false);
5851   }
5852
5853   /**
5854    * 
5855    * @return alignment panels in this alignment frame
5856    */
5857   public List<? extends AlignmentViewPanel> getAlignPanels()
5858   {
5859     // alignPanels is never null
5860     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5861     return alignPanels;
5862   }
5863
5864   /**
5865    * Open a new alignment window, with the cDNA associated with this (protein)
5866    * alignment, aligned as is the protein.
5867    */
5868   protected void viewAsCdna_actionPerformed()
5869   {
5870     // TODO no longer a menu action - refactor as required
5871     final AlignmentI alignment = getViewport().getAlignment();
5872     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5873     if (mappings == null)
5874     {
5875       return;
5876     }
5877     List<SequenceI> cdnaSeqs = new ArrayList<>();
5878     for (SequenceI aaSeq : alignment.getSequences())
5879     {
5880       for (AlignedCodonFrame acf : mappings)
5881       {
5882         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5883         if (dnaSeq != null)
5884         {
5885           /*
5886            * There is a cDNA mapping for this protein sequence - add to new
5887            * alignment. It will share the same dataset sequence as other mapped
5888            * cDNA (no new mappings need to be created).
5889            */
5890           final Sequence newSeq = new Sequence(dnaSeq);
5891           newSeq.setDatasetSequence(dnaSeq);
5892           cdnaSeqs.add(newSeq);
5893         }
5894       }
5895     }
5896     if (cdnaSeqs.size() == 0)
5897     {
5898       // show a warning dialog no mapped cDNA
5899       return;
5900     }
5901     AlignmentI cdna = new Alignment(
5902             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5903     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5904             AlignFrame.DEFAULT_HEIGHT);
5905     cdna.alignAs(alignment);
5906     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5907             + this.title;
5908     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5909             AlignFrame.DEFAULT_HEIGHT);
5910   }
5911
5912   /**
5913    * Set visibility of dna/protein complement view (available when shown in a
5914    * split frame).
5915    * 
5916    * @param show
5917    */
5918   
5919   @Override
5920   protected void showComplement_actionPerformed(boolean show)
5921   {
5922     SplitContainerI sf = getSplitViewContainer();
5923     if (sf != null)
5924     {
5925       sf.setComplementVisible(this, show);
5926     }
5927   }
5928
5929   /**
5930    * Generate the reverse (optionally complemented) of the selected sequences,
5931    * and add them to the alignment
5932    */
5933   
5934   @Override
5935   protected void showReverse_actionPerformed(boolean complement)
5936   {
5937     AlignmentI al = null;
5938     try
5939     {
5940       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5941       al = dna.reverseCdna(complement);
5942       viewport.addAlignment(al, "");
5943       addHistoryItem(new EditCommand(
5944               MessageManager.getString("label.add_sequences"), Action.PASTE,
5945               al.getSequencesArray(), 0, al.getWidth(),
5946               viewport.getAlignment()));
5947     } catch (Exception ex)
5948     {
5949       System.err.println(ex.getMessage());
5950       return;
5951     }
5952   }
5953
5954   /**
5955    * Try to run a script in the Groovy console, having first ensured that this
5956    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5957    * be targeted at this alignment.
5958    */
5959   
5960   @Override
5961   protected void runGroovy_actionPerformed()
5962   {
5963     Jalview.setCurrentAlignFrame(this);
5964     groovy.ui.Console console = Desktop.getGroovyConsole();
5965     if (console != null)
5966     {
5967       try
5968       {
5969         console.runScript();
5970       } catch (Exception ex)
5971       {
5972         System.err.println((ex.toString()));
5973         JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5974                 MessageManager.getString("label.couldnt_run_groovy_script"),
5975                 MessageManager.getString("label.groovy_support_failed"),
5976                 JvOptionPane.ERROR_MESSAGE);
5977       }
5978     }
5979     else
5980     {
5981       System.err.println("Can't run Groovy script as console not found");
5982     }
5983   }
5984
5985   /**
5986    * Hides columns containing (or not containing) a specified feature, provided
5987    * that would not leave all columns hidden
5988    * 
5989    * @param featureType
5990    * @param columnsContaining
5991    * @return
5992    */
5993   public boolean hideFeatureColumns(String featureType,
5994           boolean columnsContaining)
5995   {
5996     boolean notForHiding = avc.markColumnsContainingFeatures(
5997             columnsContaining, false, false, featureType);
5998     if (notForHiding)
5999     {
6000       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6001               false, featureType))
6002       {
6003         getViewport().hideSelectedColumns();
6004         return true;
6005       }
6006     }
6007     return false;
6008   }
6009
6010   
6011   @Override
6012   protected void selectHighlightedColumns_actionPerformed(
6013           ActionEvent actionEvent)
6014   {
6015     // include key modifier check in case user selects from menu
6016     avc.markHighlightedColumns(
6017             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6018             (actionEvent.getModifiers() & (ActionEvent.META_MASK
6019                     | ActionEvent.CTRL_MASK)) != 0);
6020   }
6021
6022   /**
6023    * Rebuilds the Colour menu, including any user-defined colours which have
6024    * been loaded either on startup or during the session
6025    */
6026   public void buildColourMenu()
6027   {
6028     colourMenu.removeAll();
6029
6030     colourMenu.add(applyToAllGroups);
6031     colourMenu.add(textColour);
6032     colourMenu.addSeparator();
6033
6034     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6035             viewport.getAlignment(), false);
6036
6037     colourMenu.add(annotationColour);
6038     bg.add(annotationColour);
6039     colourMenu.addSeparator();
6040     colourMenu.add(conservationMenuItem);
6041     colourMenu.add(modifyConservation);
6042     colourMenu.add(abovePIDThreshold);
6043     colourMenu.add(modifyPID);
6044
6045     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6046     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6047   }
6048
6049   /**
6050    * Open a dialog (if not already open) that allows the user to select and
6051    * calculate PCA or Tree analysis
6052    */
6053   protected void openTreePcaDialog()
6054   {
6055     if (alignPanel.getCalculationDialog() == null)
6056     {
6057       new CalculationChooser(AlignFrame.this);
6058     }
6059   }
6060
6061   
6062   @Override
6063   protected void loadVcf_actionPerformed()
6064   {
6065     JalviewFileChooser chooser = new JalviewFileChooser(
6066             Cache.getProperty("LAST_DIRECTORY"));
6067     chooser.setFileView(new JalviewFileView());
6068     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6069     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6070     final AlignFrame us = this;
6071     chooser.setResponseHandler(0, new Runnable()
6072     {
6073       
6074       @Override
6075       public void run()
6076       {
6077         String choice = chooser.getSelectedFile().getPath();
6078         Cache.setProperty("LAST_DIRECTORY", choice);
6079         SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6080         new VCFLoader(choice).loadVCF(seqs, us);
6081       }
6082     });
6083     chooser.showOpenDialog(null);
6084
6085   }
6086
6087   private Rectangle lastFeatureSettingsBounds = null;
6088
6089   
6090   public void setFeatureSettingsGeometry(Rectangle bounds)
6091   {
6092     lastFeatureSettingsBounds = bounds;
6093   }
6094
6095   
6096   public Rectangle getFeatureSettingsGeometry()
6097   {
6098     return lastFeatureSettingsBounds;
6099   }
6100
6101   
6102   public void scrollTo(int row, int column)
6103   {
6104     alignPanel.getSeqPanel().scrollTo(row, column);
6105   }
6106
6107   
6108   public void scrollToRow(int row)
6109   {
6110     alignPanel.getSeqPanel().scrollToRow(row);
6111   }
6112
6113   
6114   public void scrollToColumn(int column)
6115   {
6116     alignPanel.getSeqPanel().scrollToColumn(column);
6117   }
6118
6119   /**
6120    * BH 2019 from JalviewLite
6121    * 
6122    * get sequence feature groups that are hidden or shown
6123    * 
6124    * @param visible
6125    *          true is visible
6126    * @return list
6127    */
6128   public String[] getFeatureGroupsOfState(boolean visible)
6129   {
6130     jalview.api.FeatureRenderer fr = null;
6131     if (alignPanel != null
6132             && (fr = alignPanel.getFeatureRenderer()) != null)
6133     {
6134       List<String> gps = fr.getGroups(visible);
6135       String[] _gps = gps.toArray(new String[gps.size()]);
6136       return _gps;
6137     }
6138     return null;
6139   }
6140
6141   /**
6142    * 
6143    * @return list of feature groups on the view
6144    */
6145   public String[] getFeatureGroups()
6146   {
6147     jalview.api.FeatureRenderer fr = null;
6148     if (alignPanel != null
6149             && (fr = alignPanel.getFeatureRenderer()) != null)
6150     {
6151       List<String> gps = fr.getFeatureGroups();
6152       String[] _gps = gps.toArray(new String[gps.size()]);
6153       return _gps;
6154     }
6155     return null;
6156   }
6157
6158   public void select(SequenceGroup sel, ColumnSelection csel,
6159           HiddenColumns hidden)
6160   {
6161     alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6162   }
6163
6164 }
6165
6166 class PrintThread extends Thread
6167 {
6168   AlignmentPanel ap;
6169
6170   public PrintThread(AlignmentPanel ap)
6171   {
6172     this.ap = ap;
6173   }
6174
6175   static PageFormat pf;
6176
6177   @Override
6178   public void run()
6179   {
6180     PrinterJob printJob = PrinterJob.getPrinterJob();
6181
6182     if (pf != null)
6183     {
6184       printJob.setPrintable(ap, pf);
6185     }
6186     else
6187     {
6188       printJob.setPrintable(ap);
6189     }
6190
6191     if (printJob.printDialog())
6192     {
6193       try
6194       {
6195         printJob.print();
6196       } catch (Exception PrintException)
6197       {
6198         PrintException.printStackTrace();
6199       }
6200     }
6201   }
6202
6203 }