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