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