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