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