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