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