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