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