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