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