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