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