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