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