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