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