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