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