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