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