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