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