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