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