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