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