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