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