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