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