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