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